CodeGenDAGPatterns.cpp 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293
  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  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 file implements the CodeGenDAGPatterns class, which is used to read and
  11. // represent the patterns present in a .td file for instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenDAGPatterns.h"
  15. #include "llvm/TableGen/Error.h"
  16. #include "llvm/TableGen/Record.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include <algorithm>
  22. #include <cstdio>
  23. #include <set>
  24. using namespace llvm;
  25. //===----------------------------------------------------------------------===//
  26. // EEVT::TypeSet Implementation
  27. //===----------------------------------------------------------------------===//
  28. static inline bool isInteger(MVT::SimpleValueType VT) {
  29. return EVT(VT).isInteger();
  30. }
  31. static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
  32. return EVT(VT).isFloatingPoint();
  33. }
  34. static inline bool isVector(MVT::SimpleValueType VT) {
  35. return EVT(VT).isVector();
  36. }
  37. static inline bool isScalar(MVT::SimpleValueType VT) {
  38. return !EVT(VT).isVector();
  39. }
  40. EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
  41. if (VT == MVT::iAny)
  42. EnforceInteger(TP);
  43. else if (VT == MVT::fAny)
  44. EnforceFloatingPoint(TP);
  45. else if (VT == MVT::vAny)
  46. EnforceVector(TP);
  47. else {
  48. assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
  49. VT == MVT::iPTRAny) && "Not a concrete type!");
  50. TypeVec.push_back(VT);
  51. }
  52. }
  53. EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
  54. assert(!VTList.empty() && "empty list?");
  55. TypeVec.append(VTList.begin(), VTList.end());
  56. if (!VTList.empty())
  57. assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
  58. VTList[0] != MVT::fAny);
  59. // Verify no duplicates.
  60. array_pod_sort(TypeVec.begin(), TypeVec.end());
  61. assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
  62. }
  63. /// FillWithPossibleTypes - Set to all legal types and return true, only valid
  64. /// on completely unknown type sets.
  65. bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
  66. bool (*Pred)(MVT::SimpleValueType),
  67. const char *PredicateName) {
  68. assert(isCompletelyUnknown());
  69. const std::vector<MVT::SimpleValueType> &LegalTypes =
  70. TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
  71. for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
  72. if (Pred == 0 || Pred(LegalTypes[i]))
  73. TypeVec.push_back(LegalTypes[i]);
  74. // If we have nothing that matches the predicate, bail out.
  75. if (TypeVec.empty())
  76. TP.error("Type inference contradiction found, no " +
  77. std::string(PredicateName) + " types found");
  78. // No need to sort with one element.
  79. if (TypeVec.size() == 1) return true;
  80. // Remove duplicates.
  81. array_pod_sort(TypeVec.begin(), TypeVec.end());
  82. TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
  83. return true;
  84. }
  85. /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
  86. /// integer value type.
  87. bool EEVT::TypeSet::hasIntegerTypes() const {
  88. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  89. if (isInteger(TypeVec[i]))
  90. return true;
  91. return false;
  92. }
  93. /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
  94. /// a floating point value type.
  95. bool EEVT::TypeSet::hasFloatingPointTypes() const {
  96. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  97. if (isFloatingPoint(TypeVec[i]))
  98. return true;
  99. return false;
  100. }
  101. /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
  102. /// value type.
  103. bool EEVT::TypeSet::hasVectorTypes() const {
  104. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  105. if (isVector(TypeVec[i]))
  106. return true;
  107. return false;
  108. }
  109. std::string EEVT::TypeSet::getName() const {
  110. if (TypeVec.empty()) return "<empty>";
  111. std::string Result;
  112. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
  113. std::string VTName = llvm::getEnumName(TypeVec[i]);
  114. // Strip off MVT:: prefix if present.
  115. if (VTName.substr(0,5) == "MVT::")
  116. VTName = VTName.substr(5);
  117. if (i) Result += ':';
  118. Result += VTName;
  119. }
  120. if (TypeVec.size() == 1)
  121. return Result;
  122. return "{" + Result + "}";
  123. }
  124. /// MergeInTypeInfo - This merges in type information from the specified
  125. /// argument. If 'this' changes, it returns true. If the two types are
  126. /// contradictory (e.g. merge f32 into i32) then this throws an exception.
  127. bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
  128. if (InVT.isCompletelyUnknown() || *this == InVT)
  129. return false;
  130. if (isCompletelyUnknown()) {
  131. *this = InVT;
  132. return true;
  133. }
  134. assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
  135. // Handle the abstract cases, seeing if we can resolve them better.
  136. switch (TypeVec[0]) {
  137. default: break;
  138. case MVT::iPTR:
  139. case MVT::iPTRAny:
  140. if (InVT.hasIntegerTypes()) {
  141. EEVT::TypeSet InCopy(InVT);
  142. InCopy.EnforceInteger(TP);
  143. InCopy.EnforceScalar(TP);
  144. if (InCopy.isConcrete()) {
  145. // If the RHS has one integer type, upgrade iPTR to i32.
  146. TypeVec[0] = InVT.TypeVec[0];
  147. return true;
  148. }
  149. // If the input has multiple scalar integers, this doesn't add any info.
  150. if (!InCopy.isCompletelyUnknown())
  151. return false;
  152. }
  153. break;
  154. }
  155. // If the input constraint is iAny/iPTR and this is an integer type list,
  156. // remove non-integer types from the list.
  157. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  158. hasIntegerTypes()) {
  159. bool MadeChange = EnforceInteger(TP);
  160. // If we're merging in iPTR/iPTRAny and the node currently has a list of
  161. // multiple different integer types, replace them with a single iPTR.
  162. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  163. TypeVec.size() != 1) {
  164. TypeVec.resize(1);
  165. TypeVec[0] = InVT.TypeVec[0];
  166. MadeChange = true;
  167. }
  168. return MadeChange;
  169. }
  170. // If this is a type list and the RHS is a typelist as well, eliminate entries
  171. // from this list that aren't in the other one.
  172. bool MadeChange = false;
  173. TypeSet InputSet(*this);
  174. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  175. bool InInVT = false;
  176. for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
  177. if (TypeVec[i] == InVT.TypeVec[j]) {
  178. InInVT = true;
  179. break;
  180. }
  181. if (InInVT) continue;
  182. TypeVec.erase(TypeVec.begin()+i--);
  183. MadeChange = true;
  184. }
  185. // If we removed all of our types, we have a type contradiction.
  186. if (!TypeVec.empty())
  187. return MadeChange;
  188. // FIXME: Really want an SMLoc here!
  189. TP.error("Type inference contradiction found, merging '" +
  190. InVT.getName() + "' into '" + InputSet.getName() + "'");
  191. return true; // unreachable
  192. }
  193. /// EnforceInteger - Remove all non-integer types from this set.
  194. bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
  195. // If we know nothing, then get the full set.
  196. if (TypeVec.empty())
  197. return FillWithPossibleTypes(TP, isInteger, "integer");
  198. if (!hasFloatingPointTypes())
  199. return false;
  200. TypeSet InputSet(*this);
  201. // Filter out all the fp types.
  202. for (unsigned i = 0; i != TypeVec.size(); ++i)
  203. if (!isInteger(TypeVec[i]))
  204. TypeVec.erase(TypeVec.begin()+i--);
  205. if (TypeVec.empty())
  206. TP.error("Type inference contradiction found, '" +
  207. InputSet.getName() + "' needs to be integer");
  208. return true;
  209. }
  210. /// EnforceFloatingPoint - Remove all integer types from this set.
  211. bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
  212. // If we know nothing, then get the full set.
  213. if (TypeVec.empty())
  214. return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
  215. if (!hasIntegerTypes())
  216. return false;
  217. TypeSet InputSet(*this);
  218. // Filter out all the fp types.
  219. for (unsigned i = 0; i != TypeVec.size(); ++i)
  220. if (!isFloatingPoint(TypeVec[i]))
  221. TypeVec.erase(TypeVec.begin()+i--);
  222. if (TypeVec.empty())
  223. TP.error("Type inference contradiction found, '" +
  224. InputSet.getName() + "' needs to be floating point");
  225. return true;
  226. }
  227. /// EnforceScalar - Remove all vector types from this.
  228. bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
  229. // If we know nothing, then get the full set.
  230. if (TypeVec.empty())
  231. return FillWithPossibleTypes(TP, isScalar, "scalar");
  232. if (!hasVectorTypes())
  233. return false;
  234. TypeSet InputSet(*this);
  235. // Filter out all the vector types.
  236. for (unsigned i = 0; i != TypeVec.size(); ++i)
  237. if (!isScalar(TypeVec[i]))
  238. TypeVec.erase(TypeVec.begin()+i--);
  239. if (TypeVec.empty())
  240. TP.error("Type inference contradiction found, '" +
  241. InputSet.getName() + "' needs to be scalar");
  242. return true;
  243. }
  244. /// EnforceVector - Remove all vector types from this.
  245. bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
  246. // If we know nothing, then get the full set.
  247. if (TypeVec.empty())
  248. return FillWithPossibleTypes(TP, isVector, "vector");
  249. TypeSet InputSet(*this);
  250. bool MadeChange = false;
  251. // Filter out all the scalar types.
  252. for (unsigned i = 0; i != TypeVec.size(); ++i)
  253. if (!isVector(TypeVec[i])) {
  254. TypeVec.erase(TypeVec.begin()+i--);
  255. MadeChange = true;
  256. }
  257. if (TypeVec.empty())
  258. TP.error("Type inference contradiction found, '" +
  259. InputSet.getName() + "' needs to be a vector");
  260. return MadeChange;
  261. }
  262. /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
  263. /// this an other based on this information.
  264. bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
  265. // Both operands must be integer or FP, but we don't care which.
  266. bool MadeChange = false;
  267. if (isCompletelyUnknown())
  268. MadeChange = FillWithPossibleTypes(TP);
  269. if (Other.isCompletelyUnknown())
  270. MadeChange = Other.FillWithPossibleTypes(TP);
  271. // If one side is known to be integer or known to be FP but the other side has
  272. // no information, get at least the type integrality info in there.
  273. if (!hasFloatingPointTypes())
  274. MadeChange |= Other.EnforceInteger(TP);
  275. else if (!hasIntegerTypes())
  276. MadeChange |= Other.EnforceFloatingPoint(TP);
  277. if (!Other.hasFloatingPointTypes())
  278. MadeChange |= EnforceInteger(TP);
  279. else if (!Other.hasIntegerTypes())
  280. MadeChange |= EnforceFloatingPoint(TP);
  281. assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
  282. "Should have a type list now");
  283. // If one contains vectors but the other doesn't pull vectors out.
  284. if (!hasVectorTypes())
  285. MadeChange |= Other.EnforceScalar(TP);
  286. if (!hasVectorTypes())
  287. MadeChange |= EnforceScalar(TP);
  288. if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
  289. // If we are down to concrete types, this code does not currently
  290. // handle nodes which have multiple types, where some types are
  291. // integer, and some are fp. Assert that this is not the case.
  292. assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
  293. !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
  294. "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
  295. // Otherwise, if these are both vector types, either this vector
  296. // must have a larger bitsize than the other, or this element type
  297. // must be larger than the other.
  298. EVT Type(TypeVec[0]);
  299. EVT OtherType(Other.TypeVec[0]);
  300. if (hasVectorTypes() && Other.hasVectorTypes()) {
  301. if (Type.getSizeInBits() >= OtherType.getSizeInBits())
  302. if (Type.getVectorElementType().getSizeInBits()
  303. >= OtherType.getVectorElementType().getSizeInBits())
  304. TP.error("Type inference contradiction found, '" +
  305. getName() + "' element type not smaller than '" +
  306. Other.getName() +"'!");
  307. }
  308. else
  309. // For scalar types, the bitsize of this type must be larger
  310. // than that of the other.
  311. if (Type.getSizeInBits() >= OtherType.getSizeInBits())
  312. TP.error("Type inference contradiction found, '" +
  313. getName() + "' is not smaller than '" +
  314. Other.getName() +"'!");
  315. }
  316. // Handle int and fp as disjoint sets. This won't work for patterns
  317. // that have mixed fp/int types but those are likely rare and would
  318. // not have been accepted by this code previously.
  319. // Okay, find the smallest type from the current set and remove it from the
  320. // largest set.
  321. MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
  322. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  323. if (isInteger(TypeVec[i])) {
  324. SmallestInt = TypeVec[i];
  325. break;
  326. }
  327. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  328. if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
  329. SmallestInt = TypeVec[i];
  330. MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
  331. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  332. if (isFloatingPoint(TypeVec[i])) {
  333. SmallestFP = TypeVec[i];
  334. break;
  335. }
  336. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  337. if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
  338. SmallestFP = TypeVec[i];
  339. int OtherIntSize = 0;
  340. int OtherFPSize = 0;
  341. for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
  342. Other.TypeVec.begin();
  343. TVI != Other.TypeVec.end();
  344. /* NULL */) {
  345. if (isInteger(*TVI)) {
  346. ++OtherIntSize;
  347. if (*TVI == SmallestInt) {
  348. TVI = Other.TypeVec.erase(TVI);
  349. --OtherIntSize;
  350. MadeChange = true;
  351. continue;
  352. }
  353. }
  354. else if (isFloatingPoint(*TVI)) {
  355. ++OtherFPSize;
  356. if (*TVI == SmallestFP) {
  357. TVI = Other.TypeVec.erase(TVI);
  358. --OtherFPSize;
  359. MadeChange = true;
  360. continue;
  361. }
  362. }
  363. ++TVI;
  364. }
  365. // If this is the only type in the large set, the constraint can never be
  366. // satisfied.
  367. if ((Other.hasIntegerTypes() && OtherIntSize == 0)
  368. || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
  369. TP.error("Type inference contradiction found, '" +
  370. Other.getName() + "' has nothing larger than '" + getName() +"'!");
  371. // Okay, find the largest type in the Other set and remove it from the
  372. // current set.
  373. MVT::SimpleValueType LargestInt = MVT::Other;
  374. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  375. if (isInteger(Other.TypeVec[i])) {
  376. LargestInt = Other.TypeVec[i];
  377. break;
  378. }
  379. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  380. if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
  381. LargestInt = Other.TypeVec[i];
  382. MVT::SimpleValueType LargestFP = MVT::Other;
  383. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  384. if (isFloatingPoint(Other.TypeVec[i])) {
  385. LargestFP = Other.TypeVec[i];
  386. break;
  387. }
  388. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  389. if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
  390. LargestFP = Other.TypeVec[i];
  391. int IntSize = 0;
  392. int FPSize = 0;
  393. for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
  394. TypeVec.begin();
  395. TVI != TypeVec.end();
  396. /* NULL */) {
  397. if (isInteger(*TVI)) {
  398. ++IntSize;
  399. if (*TVI == LargestInt) {
  400. TVI = TypeVec.erase(TVI);
  401. --IntSize;
  402. MadeChange = true;
  403. continue;
  404. }
  405. }
  406. else if (isFloatingPoint(*TVI)) {
  407. ++FPSize;
  408. if (*TVI == LargestFP) {
  409. TVI = TypeVec.erase(TVI);
  410. --FPSize;
  411. MadeChange = true;
  412. continue;
  413. }
  414. }
  415. ++TVI;
  416. }
  417. // If this is the only type in the small set, the constraint can never be
  418. // satisfied.
  419. if ((hasIntegerTypes() && IntSize == 0)
  420. || (hasFloatingPointTypes() && FPSize == 0))
  421. TP.error("Type inference contradiction found, '" +
  422. getName() + "' has nothing smaller than '" + Other.getName()+"'!");
  423. return MadeChange;
  424. }
  425. /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
  426. /// whose element is specified by VTOperand.
  427. bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
  428. TreePattern &TP) {
  429. // "This" must be a vector and "VTOperand" must be a scalar.
  430. bool MadeChange = false;
  431. MadeChange |= EnforceVector(TP);
  432. MadeChange |= VTOperand.EnforceScalar(TP);
  433. // If we know the vector type, it forces the scalar to agree.
  434. if (isConcrete()) {
  435. EVT IVT = getConcrete();
  436. IVT = IVT.getVectorElementType();
  437. return MadeChange |
  438. VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
  439. }
  440. // If the scalar type is known, filter out vector types whose element types
  441. // disagree.
  442. if (!VTOperand.isConcrete())
  443. return MadeChange;
  444. MVT::SimpleValueType VT = VTOperand.getConcrete();
  445. TypeSet InputSet(*this);
  446. // Filter out all the types which don't have the right element type.
  447. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  448. assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
  449. if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
  450. TypeVec.erase(TypeVec.begin()+i--);
  451. MadeChange = true;
  452. }
  453. }
  454. if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
  455. TP.error("Type inference contradiction found, forcing '" +
  456. InputSet.getName() + "' to have a vector element");
  457. return MadeChange;
  458. }
  459. /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
  460. /// vector type specified by VTOperand.
  461. bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
  462. TreePattern &TP) {
  463. // "This" must be a vector and "VTOperand" must be a vector.
  464. bool MadeChange = false;
  465. MadeChange |= EnforceVector(TP);
  466. MadeChange |= VTOperand.EnforceVector(TP);
  467. // "This" must be larger than "VTOperand."
  468. MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
  469. // If we know the vector type, it forces the scalar types to agree.
  470. if (isConcrete()) {
  471. EVT IVT = getConcrete();
  472. IVT = IVT.getVectorElementType();
  473. EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
  474. MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
  475. } else if (VTOperand.isConcrete()) {
  476. EVT IVT = VTOperand.getConcrete();
  477. IVT = IVT.getVectorElementType();
  478. EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
  479. MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
  480. }
  481. return MadeChange;
  482. }
  483. //===----------------------------------------------------------------------===//
  484. // Helpers for working with extended types.
  485. bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
  486. return LHS->getID() < RHS->getID();
  487. }
  488. /// Dependent variable map for CodeGenDAGPattern variant generation
  489. typedef std::map<std::string, int> DepVarMap;
  490. /// Const iterator shorthand for DepVarMap
  491. typedef DepVarMap::const_iterator DepVarMap_citer;
  492. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  493. if (N->isLeaf()) {
  494. if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
  495. DepMap[N->getName()]++;
  496. } else {
  497. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  498. FindDepVarsOf(N->getChild(i), DepMap);
  499. }
  500. }
  501. /// Find dependent variables within child patterns
  502. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  503. DepVarMap depcounts;
  504. FindDepVarsOf(N, depcounts);
  505. for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
  506. if (i->second > 1) // std::pair<std::string, int>
  507. DepVars.insert(i->first);
  508. }
  509. }
  510. #ifndef NDEBUG
  511. /// Dump the dependent variable set:
  512. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  513. if (DepVars.empty()) {
  514. DEBUG(errs() << "<empty set>");
  515. } else {
  516. DEBUG(errs() << "[ ");
  517. for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
  518. e = DepVars.end(); i != e; ++i) {
  519. DEBUG(errs() << (*i) << " ");
  520. }
  521. DEBUG(errs() << "]");
  522. }
  523. }
  524. #endif
  525. //===----------------------------------------------------------------------===//
  526. // TreePredicateFn Implementation
  527. //===----------------------------------------------------------------------===//
  528. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  529. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  530. assert((getPredCode().empty() || getImmCode().empty()) &&
  531. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  532. }
  533. std::string TreePredicateFn::getPredCode() const {
  534. return PatFragRec->getRecord()->getValueAsString("PredicateCode");
  535. }
  536. std::string TreePredicateFn::getImmCode() const {
  537. return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
  538. }
  539. /// isAlwaysTrue - Return true if this is a noop predicate.
  540. bool TreePredicateFn::isAlwaysTrue() const {
  541. return getPredCode().empty() && getImmCode().empty();
  542. }
  543. /// Return the name to use in the generated code to reference this, this is
  544. /// "Predicate_foo" if from a pattern fragment "foo".
  545. std::string TreePredicateFn::getFnName() const {
  546. return "Predicate_" + PatFragRec->getRecord()->getName();
  547. }
  548. /// getCodeToRunOnSDNode - Return the code for the function body that
  549. /// evaluates this predicate. The argument is expected to be in "Node",
  550. /// not N. This handles casting and conversion to a concrete node type as
  551. /// appropriate.
  552. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  553. // Handle immediate predicates first.
  554. std::string ImmCode = getImmCode();
  555. if (!ImmCode.empty()) {
  556. std::string Result =
  557. " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
  558. return Result + ImmCode;
  559. }
  560. // Handle arbitrary node predicates.
  561. assert(!getPredCode().empty() && "Don't have any predicate code!");
  562. std::string ClassName;
  563. if (PatFragRec->getOnlyTree()->isLeaf())
  564. ClassName = "SDNode";
  565. else {
  566. Record *Op = PatFragRec->getOnlyTree()->getOperator();
  567. ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
  568. }
  569. std::string Result;
  570. if (ClassName == "SDNode")
  571. Result = " SDNode *N = Node;\n";
  572. else
  573. Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
  574. return Result + getPredCode();
  575. }
  576. //===----------------------------------------------------------------------===//
  577. // PatternToMatch implementation
  578. //
  579. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  580. /// patterns before small ones. This is used to determine the size of a
  581. /// pattern.
  582. static unsigned getPatternSize(const TreePatternNode *P,
  583. const CodeGenDAGPatterns &CGP) {
  584. unsigned Size = 3; // The node itself.
  585. // If the root node is a ConstantSDNode, increases its size.
  586. // e.g. (set R32:$dst, 0).
  587. if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
  588. Size += 2;
  589. // FIXME: This is a hack to statically increase the priority of patterns
  590. // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
  591. // Later we can allow complexity / cost for each pattern to be (optionally)
  592. // specified. To get best possible pattern match we'll need to dynamically
  593. // calculate the complexity of all patterns a dag can potentially map to.
  594. const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
  595. if (AM)
  596. Size += AM->getNumOperands() * 3;
  597. // If this node has some predicate function that must match, it adds to the
  598. // complexity of this node.
  599. if (!P->getPredicateFns().empty())
  600. ++Size;
  601. // Count children in the count if they are also nodes.
  602. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  603. TreePatternNode *Child = P->getChild(i);
  604. if (!Child->isLeaf() && Child->getNumTypes() &&
  605. Child->getType(0) != MVT::Other)
  606. Size += getPatternSize(Child, CGP);
  607. else if (Child->isLeaf()) {
  608. if (dynamic_cast<IntInit*>(Child->getLeafValue()))
  609. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  610. else if (Child->getComplexPatternInfo(CGP))
  611. Size += getPatternSize(Child, CGP);
  612. else if (!Child->getPredicateFns().empty())
  613. ++Size;
  614. }
  615. }
  616. return Size;
  617. }
  618. /// Compute the complexity metric for the input pattern. This roughly
  619. /// corresponds to the number of nodes that are covered.
  620. unsigned PatternToMatch::
  621. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  622. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  623. }
  624. /// getPredicateCheck - Return a single string containing all of this
  625. /// pattern's predicates concatenated with "&&" operators.
  626. ///
  627. std::string PatternToMatch::getPredicateCheck() const {
  628. std::string PredicateCheck;
  629. for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
  630. if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
  631. Record *Def = Pred->getDef();
  632. if (!Def->isSubClassOf("Predicate")) {
  633. #ifndef NDEBUG
  634. Def->dump();
  635. #endif
  636. llvm_unreachable("Unknown predicate type!");
  637. }
  638. if (!PredicateCheck.empty())
  639. PredicateCheck += " && ";
  640. PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
  641. }
  642. }
  643. return PredicateCheck;
  644. }
  645. //===----------------------------------------------------------------------===//
  646. // SDTypeConstraint implementation
  647. //
  648. SDTypeConstraint::SDTypeConstraint(Record *R) {
  649. OperandNo = R->getValueAsInt("OperandNum");
  650. if (R->isSubClassOf("SDTCisVT")) {
  651. ConstraintType = SDTCisVT;
  652. x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
  653. if (x.SDTCisVT_Info.VT == MVT::isVoid)
  654. throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  655. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  656. ConstraintType = SDTCisPtrTy;
  657. } else if (R->isSubClassOf("SDTCisInt")) {
  658. ConstraintType = SDTCisInt;
  659. } else if (R->isSubClassOf("SDTCisFP")) {
  660. ConstraintType = SDTCisFP;
  661. } else if (R->isSubClassOf("SDTCisVec")) {
  662. ConstraintType = SDTCisVec;
  663. } else if (R->isSubClassOf("SDTCisSameAs")) {
  664. ConstraintType = SDTCisSameAs;
  665. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  666. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  667. ConstraintType = SDTCisVTSmallerThanOp;
  668. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  669. R->getValueAsInt("OtherOperandNum");
  670. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  671. ConstraintType = SDTCisOpSmallerThanOp;
  672. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  673. R->getValueAsInt("BigOperandNum");
  674. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  675. ConstraintType = SDTCisEltOfVec;
  676. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  677. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  678. ConstraintType = SDTCisSubVecOfVec;
  679. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  680. R->getValueAsInt("OtherOpNum");
  681. } else {
  682. errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
  683. exit(1);
  684. }
  685. }
  686. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  687. /// N, and the result number in ResNo.
  688. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  689. const SDNodeInfo &NodeInfo,
  690. unsigned &ResNo) {
  691. unsigned NumResults = NodeInfo.getNumResults();
  692. if (OpNo < NumResults) {
  693. ResNo = OpNo;
  694. return N;
  695. }
  696. OpNo -= NumResults;
  697. if (OpNo >= N->getNumChildren()) {
  698. errs() << "Invalid operand number in type constraint "
  699. << (OpNo+NumResults) << " ";
  700. N->dump();
  701. errs() << '\n';
  702. exit(1);
  703. }
  704. return N->getChild(OpNo);
  705. }
  706. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  707. /// constraint to the nodes operands. This returns true if it makes a
  708. /// change, false otherwise. If a type contradiction is found, throw an
  709. /// exception.
  710. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  711. const SDNodeInfo &NodeInfo,
  712. TreePattern &TP) const {
  713. unsigned ResNo = 0; // The result number being referenced.
  714. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  715. switch (ConstraintType) {
  716. case SDTCisVT:
  717. // Operand must be a particular type.
  718. return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
  719. case SDTCisPtrTy:
  720. // Operand must be same as target pointer type.
  721. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  722. case SDTCisInt:
  723. // Require it to be one of the legal integer VTs.
  724. return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
  725. case SDTCisFP:
  726. // Require it to be one of the legal fp VTs.
  727. return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
  728. case SDTCisVec:
  729. // Require it to be one of the legal vector VTs.
  730. return NodeToApply->getExtType(ResNo).EnforceVector(TP);
  731. case SDTCisSameAs: {
  732. unsigned OResNo = 0;
  733. TreePatternNode *OtherNode =
  734. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  735. return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
  736. OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
  737. }
  738. case SDTCisVTSmallerThanOp: {
  739. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  740. // have an integer type that is smaller than the VT.
  741. if (!NodeToApply->isLeaf() ||
  742. !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
  743. !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
  744. ->isSubClassOf("ValueType"))
  745. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  746. MVT::SimpleValueType VT =
  747. getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
  748. EEVT::TypeSet TypeListTmp(VT, TP);
  749. unsigned OResNo = 0;
  750. TreePatternNode *OtherNode =
  751. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  752. OResNo);
  753. return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
  754. }
  755. case SDTCisOpSmallerThanOp: {
  756. unsigned BResNo = 0;
  757. TreePatternNode *BigOperand =
  758. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  759. BResNo);
  760. return NodeToApply->getExtType(ResNo).
  761. EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
  762. }
  763. case SDTCisEltOfVec: {
  764. unsigned VResNo = 0;
  765. TreePatternNode *VecOperand =
  766. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  767. VResNo);
  768. // Filter vector types out of VecOperand that don't have the right element
  769. // type.
  770. return VecOperand->getExtType(VResNo).
  771. EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
  772. }
  773. case SDTCisSubVecOfVec: {
  774. unsigned VResNo = 0;
  775. TreePatternNode *BigVecOperand =
  776. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  777. VResNo);
  778. // Filter vector types out of BigVecOperand that don't have the
  779. // right subvector type.
  780. return BigVecOperand->getExtType(VResNo).
  781. EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
  782. }
  783. }
  784. llvm_unreachable("Invalid ConstraintType!");
  785. }
  786. //===----------------------------------------------------------------------===//
  787. // SDNodeInfo implementation
  788. //
  789. SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
  790. EnumName = R->getValueAsString("Opcode");
  791. SDClassName = R->getValueAsString("SDClass");
  792. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  793. NumResults = TypeProfile->getValueAsInt("NumResults");
  794. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  795. // Parse the properties.
  796. Properties = 0;
  797. std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
  798. for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
  799. if (PropList[i]->getName() == "SDNPCommutative") {
  800. Properties |= 1 << SDNPCommutative;
  801. } else if (PropList[i]->getName() == "SDNPAssociative") {
  802. Properties |= 1 << SDNPAssociative;
  803. } else if (PropList[i]->getName() == "SDNPHasChain") {
  804. Properties |= 1 << SDNPHasChain;
  805. } else if (PropList[i]->getName() == "SDNPOutGlue") {
  806. Properties |= 1 << SDNPOutGlue;
  807. } else if (PropList[i]->getName() == "SDNPInGlue") {
  808. Properties |= 1 << SDNPInGlue;
  809. } else if (PropList[i]->getName() == "SDNPOptInGlue") {
  810. Properties |= 1 << SDNPOptInGlue;
  811. } else if (PropList[i]->getName() == "SDNPMayStore") {
  812. Properties |= 1 << SDNPMayStore;
  813. } else if (PropList[i]->getName() == "SDNPMayLoad") {
  814. Properties |= 1 << SDNPMayLoad;
  815. } else if (PropList[i]->getName() == "SDNPSideEffect") {
  816. Properties |= 1 << SDNPSideEffect;
  817. } else if (PropList[i]->getName() == "SDNPMemOperand") {
  818. Properties |= 1 << SDNPMemOperand;
  819. } else if (PropList[i]->getName() == "SDNPVariadic") {
  820. Properties |= 1 << SDNPVariadic;
  821. } else {
  822. errs() << "Unknown SD Node property '" << PropList[i]->getName()
  823. << "' on node '" << R->getName() << "'!\n";
  824. exit(1);
  825. }
  826. }
  827. // Parse the type constraints.
  828. std::vector<Record*> ConstraintList =
  829. TypeProfile->getValueAsListOfDefs("Constraints");
  830. TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
  831. }
  832. /// getKnownType - If the type constraints on this node imply a fixed type
  833. /// (e.g. all stores return void, etc), then return it as an
  834. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  835. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  836. unsigned NumResults = getNumResults();
  837. assert(NumResults <= 1 &&
  838. "We only work with nodes with zero or one result so far!");
  839. assert(ResNo == 0 && "Only handles single result nodes so far");
  840. for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
  841. // Make sure that this applies to the correct node result.
  842. if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
  843. continue;
  844. switch (TypeConstraints[i].ConstraintType) {
  845. default: break;
  846. case SDTypeConstraint::SDTCisVT:
  847. return TypeConstraints[i].x.SDTCisVT_Info.VT;
  848. case SDTypeConstraint::SDTCisPtrTy:
  849. return MVT::iPTR;
  850. }
  851. }
  852. return MVT::Other;
  853. }
  854. //===----------------------------------------------------------------------===//
  855. // TreePatternNode implementation
  856. //
  857. TreePatternNode::~TreePatternNode() {
  858. #if 0 // FIXME: implement refcounted tree nodes!
  859. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  860. delete getChild(i);
  861. #endif
  862. }
  863. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  864. if (Operator->getName() == "set" ||
  865. Operator->getName() == "implicit")
  866. return 0; // All return nothing.
  867. if (Operator->isSubClassOf("Intrinsic"))
  868. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  869. if (Operator->isSubClassOf("SDNode"))
  870. return CDP.getSDNodeInfo(Operator).getNumResults();
  871. if (Operator->isSubClassOf("PatFrag")) {
  872. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  873. // the forward reference case where one pattern fragment references another
  874. // before it is processed.
  875. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
  876. return PFRec->getOnlyTree()->getNumTypes();
  877. // Get the result tree.
  878. DagInit *Tree = Operator->getValueAsDag("Fragment");
  879. Record *Op = 0;
  880. if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
  881. Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
  882. assert(Op && "Invalid Fragment");
  883. return GetNumNodeResults(Op, CDP);
  884. }
  885. if (Operator->isSubClassOf("Instruction")) {
  886. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  887. // FIXME: Should allow access to all the results here.
  888. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  889. // Add on one implicit def if it has a resolvable type.
  890. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  891. ++NumDefsToAdd;
  892. return NumDefsToAdd;
  893. }
  894. if (Operator->isSubClassOf("SDNodeXForm"))
  895. return 1; // FIXME: Generalize SDNodeXForm
  896. Operator->dump();
  897. errs() << "Unhandled node in GetNumNodeResults\n";
  898. exit(1);
  899. }
  900. void TreePatternNode::print(raw_ostream &OS) const {
  901. if (isLeaf())
  902. OS << *getLeafValue();
  903. else
  904. OS << '(' << getOperator()->getName();
  905. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  906. OS << ':' << getExtType(i).getName();
  907. if (!isLeaf()) {
  908. if (getNumChildren() != 0) {
  909. OS << " ";
  910. getChild(0)->print(OS);
  911. for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
  912. OS << ", ";
  913. getChild(i)->print(OS);
  914. }
  915. }
  916. OS << ")";
  917. }
  918. for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
  919. OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
  920. if (TransformFn)
  921. OS << "<<X:" << TransformFn->getName() << ">>";
  922. if (!getName().empty())
  923. OS << ":$" << getName();
  924. }
  925. void TreePatternNode::dump() const {
  926. print(errs());
  927. }
  928. /// isIsomorphicTo - Return true if this node is recursively
  929. /// isomorphic to the specified node. For this comparison, the node's
  930. /// entire state is considered. The assigned name is ignored, since
  931. /// nodes with differing names are considered isomorphic. However, if
  932. /// the assigned name is present in the dependent variable set, then
  933. /// the assigned name is considered significant and the node is
  934. /// isomorphic if the names match.
  935. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  936. const MultipleUseVarSet &DepVars) const {
  937. if (N == this) return true;
  938. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  939. getPredicateFns() != N->getPredicateFns() ||
  940. getTransformFn() != N->getTransformFn())
  941. return false;
  942. if (isLeaf()) {
  943. if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
  944. if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
  945. return ((DI->getDef() == NDI->getDef())
  946. && (DepVars.find(getName()) == DepVars.end()
  947. || getName() == N->getName()));
  948. }
  949. }
  950. return getLeafValue() == N->getLeafValue();
  951. }
  952. if (N->getOperator() != getOperator() ||
  953. N->getNumChildren() != getNumChildren()) return false;
  954. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  955. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  956. return false;
  957. return true;
  958. }
  959. /// clone - Make a copy of this tree and all of its children.
  960. ///
  961. TreePatternNode *TreePatternNode::clone() const {
  962. TreePatternNode *New;
  963. if (isLeaf()) {
  964. New = new TreePatternNode(getLeafValue(), getNumTypes());
  965. } else {
  966. std::vector<TreePatternNode*> CChildren;
  967. CChildren.reserve(Children.size());
  968. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  969. CChildren.push_back(getChild(i)->clone());
  970. New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
  971. }
  972. New->setName(getName());
  973. New->Types = Types;
  974. New->setPredicateFns(getPredicateFns());
  975. New->setTransformFn(getTransformFn());
  976. return New;
  977. }
  978. /// RemoveAllTypes - Recursively strip all the types of this tree.
  979. void TreePatternNode::RemoveAllTypes() {
  980. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  981. Types[i] = EEVT::TypeSet(); // Reset to unknown type.
  982. if (isLeaf()) return;
  983. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  984. getChild(i)->RemoveAllTypes();
  985. }
  986. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  987. /// with actual values specified by ArgMap.
  988. void TreePatternNode::
  989. SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
  990. if (isLeaf()) return;
  991. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  992. TreePatternNode *Child = getChild(i);
  993. if (Child->isLeaf()) {
  994. Init *Val = Child->getLeafValue();
  995. if (dynamic_cast<DefInit*>(Val) &&
  996. static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
  997. // We found a use of a formal argument, replace it with its value.
  998. TreePatternNode *NewChild = ArgMap[Child->getName()];
  999. assert(NewChild && "Couldn't find formal argument!");
  1000. assert((Child->getPredicateFns().empty() ||
  1001. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1002. "Non-empty child predicate clobbered!");
  1003. setChild(i, NewChild);
  1004. }
  1005. } else {
  1006. getChild(i)->SubstituteFormalArguments(ArgMap);
  1007. }
  1008. }
  1009. }
  1010. /// InlinePatternFragments - If this pattern refers to any pattern
  1011. /// fragments, inline them into place, giving us a pattern without any
  1012. /// PatFrag references.
  1013. TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
  1014. if (isLeaf()) return this; // nothing to do.
  1015. Record *Op = getOperator();
  1016. if (!Op->isSubClassOf("PatFrag")) {
  1017. // Just recursively inline children nodes.
  1018. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1019. TreePatternNode *Child = getChild(i);
  1020. TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
  1021. assert((Child->getPredicateFns().empty() ||
  1022. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1023. "Non-empty child predicate clobbered!");
  1024. setChild(i, NewChild);
  1025. }
  1026. return this;
  1027. }
  1028. // Otherwise, we found a reference to a fragment. First, look up its
  1029. // TreePattern record.
  1030. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1031. // Verify that we are passing the right number of operands.
  1032. if (Frag->getNumArgs() != Children.size())
  1033. TP.error("'" + Op->getName() + "' fragment requires " +
  1034. utostr(Frag->getNumArgs()) + " operands!");
  1035. TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
  1036. TreePredicateFn PredFn(Frag);
  1037. if (!PredFn.isAlwaysTrue())
  1038. FragTree->addPredicateFn(PredFn);
  1039. // Resolve formal arguments to their actual value.
  1040. if (Frag->getNumArgs()) {
  1041. // Compute the map of formal to actual arguments.
  1042. std::map<std::string, TreePatternNode*> ArgMap;
  1043. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
  1044. ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
  1045. FragTree->SubstituteFormalArguments(ArgMap);
  1046. }
  1047. FragTree->setName(getName());
  1048. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1049. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1050. // Transfer in the old predicates.
  1051. for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
  1052. FragTree->addPredicateFn(getPredicateFns()[i]);
  1053. // Get a new copy of this fragment to stitch into here.
  1054. //delete this; // FIXME: implement refcounting!
  1055. // The fragment we inlined could have recursive inlining that is needed. See
  1056. // if there are any pattern fragments in it and inline them as needed.
  1057. return FragTree->InlinePatternFragments(TP);
  1058. }
  1059. /// getImplicitType - Check to see if the specified record has an implicit
  1060. /// type which should be applied to it. This will infer the type of register
  1061. /// references from the register file information, for example.
  1062. ///
  1063. static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
  1064. bool NotRegisters, TreePattern &TP) {
  1065. // Check to see if this is a register operand.
  1066. if (R->isSubClassOf("RegisterOperand")) {
  1067. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1068. if (NotRegisters)
  1069. return EEVT::TypeSet(); // Unknown.
  1070. Record *RegClass = R->getValueAsDef("RegClass");
  1071. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1072. return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
  1073. }
  1074. // Check to see if this is a register or a register class.
  1075. if (R->isSubClassOf("RegisterClass")) {
  1076. assert(ResNo == 0 && "Regclass ref only has one result!");
  1077. if (NotRegisters)
  1078. return EEVT::TypeSet(); // Unknown.
  1079. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1080. return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
  1081. }
  1082. if (R->isSubClassOf("PatFrag")) {
  1083. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1084. // Pattern fragment types will be resolved when they are inlined.
  1085. return EEVT::TypeSet(); // Unknown.
  1086. }
  1087. if (R->isSubClassOf("Register")) {
  1088. assert(ResNo == 0 && "Registers only produce one result!");
  1089. if (NotRegisters)
  1090. return EEVT::TypeSet(); // Unknown.
  1091. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1092. return EEVT::TypeSet(T.getRegisterVTs(R));
  1093. }
  1094. if (R->isSubClassOf("SubRegIndex")) {
  1095. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1096. return EEVT::TypeSet();
  1097. }
  1098. if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
  1099. assert(ResNo == 0 && "This node only has one result!");
  1100. // Using a VTSDNode or CondCodeSDNode.
  1101. return EEVT::TypeSet(MVT::Other, TP);
  1102. }
  1103. if (R->isSubClassOf("ComplexPattern")) {
  1104. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1105. if (NotRegisters)
  1106. return EEVT::TypeSet(); // Unknown.
  1107. return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
  1108. TP);
  1109. }
  1110. if (R->isSubClassOf("PointerLikeRegClass")) {
  1111. assert(ResNo == 0 && "Regclass can only have one result!");
  1112. return EEVT::TypeSet(MVT::iPTR, TP);
  1113. }
  1114. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  1115. R->getName() == "zero_reg") {
  1116. // Placeholder.
  1117. return EEVT::TypeSet(); // Unknown.
  1118. }
  1119. TP.error("Unknown node flavor used in pattern: " + R->getName());
  1120. return EEVT::TypeSet(MVT::Other, TP);
  1121. }
  1122. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  1123. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  1124. const CodeGenIntrinsic *TreePatternNode::
  1125. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  1126. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  1127. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  1128. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  1129. return 0;
  1130. unsigned IID =
  1131. dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
  1132. return &CDP.getIntrinsicInfo(IID);
  1133. }
  1134. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  1135. /// return the ComplexPattern information, otherwise return null.
  1136. const ComplexPattern *
  1137. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  1138. if (!isLeaf()) return 0;
  1139. DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
  1140. if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
  1141. return &CGP.getComplexPattern(DI->getDef());
  1142. return 0;
  1143. }
  1144. /// NodeHasProperty - Return true if this node has the specified property.
  1145. bool TreePatternNode::NodeHasProperty(SDNP Property,
  1146. const CodeGenDAGPatterns &CGP) const {
  1147. if (isLeaf()) {
  1148. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  1149. return CP->hasProperty(Property);
  1150. return false;
  1151. }
  1152. Record *Operator = getOperator();
  1153. if (!Operator->isSubClassOf("SDNode")) return false;
  1154. return CGP.getSDNodeInfo(Operator).hasProperty(Property);
  1155. }
  1156. /// TreeHasProperty - Return true if any node in this tree has the specified
  1157. /// property.
  1158. bool TreePatternNode::TreeHasProperty(SDNP Property,
  1159. const CodeGenDAGPatterns &CGP) const {
  1160. if (NodeHasProperty(Property, CGP))
  1161. return true;
  1162. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1163. if (getChild(i)->TreeHasProperty(Property, CGP))
  1164. return true;
  1165. return false;
  1166. }
  1167. /// isCommutativeIntrinsic - Return true if the node corresponds to a
  1168. /// commutative intrinsic.
  1169. bool
  1170. TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
  1171. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
  1172. return Int->isCommutative;
  1173. return false;
  1174. }
  1175. /// ApplyTypeConstraints - Apply all of the type constraints relevant to
  1176. /// this node and its children in the tree. This returns true if it makes a
  1177. /// change, false otherwise. If a type contradiction is found, throw an
  1178. /// exception.
  1179. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
  1180. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  1181. if (isLeaf()) {
  1182. if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
  1183. // If it's a regclass or something else known, include the type.
  1184. bool MadeChange = false;
  1185. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1186. MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
  1187. NotRegisters, TP), TP);
  1188. return MadeChange;
  1189. }
  1190. if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
  1191. assert(Types.size() == 1 && "Invalid IntInit");
  1192. // Int inits are always integers. :)
  1193. bool MadeChange = Types[0].EnforceInteger(TP);
  1194. if (!Types[0].isConcrete())
  1195. return MadeChange;
  1196. MVT::SimpleValueType VT = getType(0);
  1197. if (VT == MVT::iPTR || VT == MVT::iPTRAny)
  1198. return MadeChange;
  1199. unsigned Size = EVT(VT).getSizeInBits();
  1200. // Make sure that the value is representable for this type.
  1201. if (Size >= 32) return MadeChange;
  1202. int Val = (II->getValue() << (32-Size)) >> (32-Size);
  1203. if (Val == II->getValue()) return MadeChange;
  1204. // If sign-extended doesn't fit, does it fit as unsigned?
  1205. unsigned ValueMask;
  1206. unsigned UnsignedVal;
  1207. ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
  1208. UnsignedVal = unsigned(II->getValue());
  1209. if ((ValueMask & UnsignedVal) == UnsignedVal)
  1210. return MadeChange;
  1211. TP.error("Integer value '" + itostr(II->getValue())+
  1212. "' is out of range for type '" + getEnumName(getType(0)) + "'!");
  1213. return MadeChange;
  1214. }
  1215. return false;
  1216. }
  1217. // special handling for set, which isn't really an SDNode.
  1218. if (getOperator()->getName() == "set") {
  1219. assert(getNumTypes() == 0 && "Set doesn't produce a value");
  1220. assert(getNumChildren() >= 2 && "Missing RHS of a set?");
  1221. unsigned NC = getNumChildren();
  1222. TreePatternNode *SetVal = getChild(NC-1);
  1223. bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
  1224. for (unsigned i = 0; i < NC-1; ++i) {
  1225. TreePatternNode *Child = getChild(i);
  1226. MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
  1227. // Types of operands must match.
  1228. MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
  1229. MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
  1230. }
  1231. return MadeChange;
  1232. }
  1233. if (getOperator()->getName() == "implicit") {
  1234. assert(getNumTypes() == 0 && "Node doesn't produce a value");
  1235. bool MadeChange = false;
  1236. for (unsigned i = 0; i < getNumChildren(); ++i)
  1237. MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1238. return MadeChange;
  1239. }
  1240. if (getOperator()->getName() == "COPY_TO_REGCLASS") {
  1241. bool MadeChange = false;
  1242. MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  1243. MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
  1244. assert(getChild(0)->getNumTypes() == 1 &&
  1245. getChild(1)->getNumTypes() == 1 && "Unhandled case");
  1246. // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
  1247. // what type it gets, so if it didn't get a concrete type just give it the
  1248. // first viable type from the reg class.
  1249. if (!getChild(1)->hasTypeSet(0) &&
  1250. !getChild(1)->getExtType(0).isCompletelyUnknown()) {
  1251. MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
  1252. MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
  1253. }
  1254. return MadeChange;
  1255. }
  1256. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
  1257. bool MadeChange = false;
  1258. // Apply the result type to the node.
  1259. unsigned NumRetVTs = Int->IS.RetVTs.size();
  1260. unsigned NumParamVTs = Int->IS.ParamVTs.size();
  1261. for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
  1262. MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
  1263. if (getNumChildren() != NumParamVTs + 1)
  1264. TP.error("Intrinsic '" + Int->Name + "' expects " +
  1265. utostr(NumParamVTs) + " operands, not " +
  1266. utostr(getNumChildren() - 1) + " operands!");
  1267. // Apply type info to the intrinsic ID.
  1268. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
  1269. for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
  1270. MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
  1271. MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
  1272. assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
  1273. MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
  1274. }
  1275. return MadeChange;
  1276. }
  1277. if (getOperator()->isSubClassOf("SDNode")) {
  1278. const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
  1279. // Check that the number of operands is sane. Negative operands -> varargs.
  1280. if (NI.getNumOperands() >= 0 &&
  1281. getNumChildren() != (unsigned)NI.getNumOperands())
  1282. TP.error(getOperator()->getName() + " node requires exactly " +
  1283. itostr(NI.getNumOperands()) + " operands!");
  1284. bool MadeChange = NI.ApplyTypeConstraints(this, TP);
  1285. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1286. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1287. return MadeChange;
  1288. }
  1289. if (getOperator()->isSubClassOf("Instruction")) {
  1290. const DAGInstruction &Inst = CDP.getInstruction(getOperator());
  1291. CodeGenInstruction &InstInfo =
  1292. CDP.getTargetInfo().getInstruction(getOperator());
  1293. bool MadeChange = false;
  1294. // Apply the result types to the node, these come from the things in the
  1295. // (outs) list of the instruction.
  1296. // FIXME: Cap at one result so far.
  1297. unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  1298. for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
  1299. Record *ResultNode = Inst.getResult(ResNo);
  1300. if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
  1301. MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
  1302. } else if (ResultNode->isSubClassOf("RegisterOperand")) {
  1303. Record *RegClass = ResultNode->getValueAsDef("RegClass");
  1304. const CodeGenRegisterClass &RC =
  1305. CDP.getTargetInfo().getRegisterClass(RegClass);
  1306. MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
  1307. } else if (ResultNode->getName() == "unknown") {
  1308. // Nothing to do.
  1309. } else {
  1310. assert(ResultNode->isSubClassOf("RegisterClass") &&
  1311. "Operands should be register classes!");
  1312. const CodeGenRegisterClass &RC =
  1313. CDP.getTargetInfo().getRegisterClass(ResultNode);
  1314. MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
  1315. }
  1316. }
  1317. // If the instruction has implicit defs, we apply the first one as a result.
  1318. // FIXME: This sucks, it should apply all implicit defs.
  1319. if (!InstInfo.ImplicitDefs.empty()) {
  1320. unsigned ResNo = NumResultsToAdd;
  1321. // FIXME: Generalize to multiple possible types and multiple possible
  1322. // ImplicitDefs.
  1323. MVT::SimpleValueType VT =
  1324. InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
  1325. if (VT != MVT::Other)
  1326. MadeChange |= UpdateNodeType(ResNo, VT, TP);
  1327. }
  1328. // If this is an INSERT_SUBREG, constrain the source and destination VTs to
  1329. // be the same.
  1330. if (getOperator()->getName() == "INSERT_SUBREG") {
  1331. assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
  1332. MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
  1333. MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
  1334. }
  1335. unsigned ChildNo = 0;
  1336. for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
  1337. Record *OperandNode = Inst.getOperand(i);
  1338. // If the instruction expects a predicate or optional def operand, we
  1339. // codegen this by setting the operand to it's default value if it has a
  1340. // non-empty DefaultOps field.
  1341. if ((OperandNode->isSubClassOf("PredicateOperand") ||
  1342. OperandNode->isSubClassOf("OptionalDefOperand")) &&
  1343. !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
  1344. continue;
  1345. // Verify that we didn't run out of provided operands.
  1346. if (ChildNo >= getNumChildren())
  1347. TP.error("Instruction '" + getOperator()->getName() +
  1348. "' expects more operands than were provided.");
  1349. MVT::SimpleValueType VT;
  1350. TreePatternNode *Child = getChild(ChildNo++);
  1351. unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
  1352. if (OperandNode->isSubClassOf("RegisterClass")) {
  1353. const CodeGenRegisterClass &RC =
  1354. CDP.getTargetInfo().getRegisterClass(OperandNode);
  1355. MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
  1356. } else if (OperandNode->isSubClassOf("RegisterOperand")) {
  1357. Record *RegClass = OperandNode->getValueAsDef("RegClass");
  1358. const CodeGenRegisterClass &RC =
  1359. CDP.getTargetInfo().getRegisterClass(RegClass);
  1360. MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
  1361. } else if (OperandNode->isSubClassOf("Operand")) {
  1362. VT = getValueType(OperandNode->getValueAsDef("Type"));
  1363. MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
  1364. } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
  1365. MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
  1366. } else if (OperandNode->getName() == "unknown") {
  1367. // Nothing to do.
  1368. } else
  1369. llvm_unreachable("Unknown operand type!");
  1370. MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
  1371. }
  1372. if (ChildNo != getNumChildren())
  1373. TP.error("Instruction '" + getOperator()->getName() +
  1374. "' was provided too many operands!");
  1375. return MadeChange;
  1376. }
  1377. assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
  1378. // Node transforms always take one operand.
  1379. if (getNumChildren() != 1)
  1380. TP.error("Node transform '" + getOperator()->getName() +
  1381. "' requires one operand!");
  1382. bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  1383. // If either the output or input of the xform does not have exact
  1384. // type info. We assume they must be the same. Otherwise, it is perfectly
  1385. // legal to transform from one type to a completely different type.
  1386. #if 0
  1387. if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
  1388. bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
  1389. MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
  1390. return MadeChange;
  1391. }
  1392. #endif
  1393. return MadeChange;
  1394. }
  1395. /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
  1396. /// RHS of a commutative operation, not the on LHS.
  1397. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
  1398. if (!N->isLeaf() && N->getOperator()->getName() == "imm")
  1399. return true;
  1400. if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
  1401. return true;
  1402. return false;
  1403. }
  1404. /// canPatternMatch - If it is impossible for this pattern to match on this
  1405. /// target, fill in Reason and return false. Otherwise, return true. This is
  1406. /// used as a sanity check for .td files (to prevent people from writing stuff
  1407. /// that can never possibly work), and to prevent the pattern permuter from
  1408. /// generating stuff that is useless.
  1409. bool TreePatternNode::canPatternMatch(std::string &Reason,
  1410. const CodeGenDAGPatterns &CDP) {
  1411. if (isLeaf()) return true;
  1412. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1413. if (!getChild(i)->canPatternMatch(Reason, CDP))
  1414. return false;
  1415. // If this is an intrinsic, handle cases that would make it not match. For
  1416. // example, if an operand is required to be an immediate.
  1417. if (getOperator()->isSubClassOf("Intrinsic")) {
  1418. // TODO:
  1419. return true;
  1420. }
  1421. // If this node is a commutative operator, check that the LHS isn't an
  1422. // immediate.
  1423. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
  1424. bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
  1425. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  1426. // Scan all of the operands of the node and make sure that only the last one
  1427. // is a constant node, unless the RHS also is.
  1428. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
  1429. bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  1430. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
  1431. if (OnlyOnRHSOfCommutative(getChild(i))) {
  1432. Reason="Immediate value must be on the RHS of commutative operators!";
  1433. return false;
  1434. }
  1435. }
  1436. }
  1437. return true;
  1438. }
  1439. //===----------------------------------------------------------------------===//
  1440. // TreePattern implementation
  1441. //
  1442. TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
  1443. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
  1444. isInputPattern = isInput;
  1445. for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
  1446. Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
  1447. }
  1448. TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
  1449. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
  1450. isInputPattern = isInput;
  1451. Trees.push_back(ParseTreePattern(Pat, ""));
  1452. }
  1453. TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
  1454. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
  1455. isInputPattern = isInput;
  1456. Trees.push_back(Pat);
  1457. }
  1458. void TreePattern::error(const std::string &Msg) const {
  1459. dump();
  1460. throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
  1461. }
  1462. void TreePattern::ComputeNamedNodes() {
  1463. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1464. ComputeNamedNodes(Trees[i]);
  1465. }
  1466. void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
  1467. if (!N->getName().empty())
  1468. NamedNodes[N->getName()].push_back(N);
  1469. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  1470. ComputeNamedNodes(N->getChild(i));
  1471. }
  1472. TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
  1473. if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
  1474. Record *R = DI->getDef();
  1475. // Direct reference to a leaf DagNode or PatFrag? Turn it into a
  1476. // TreePatternNode of its own. For example:
  1477. /// (foo GPR, imm) -> (foo GPR, (imm))
  1478. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
  1479. return ParseTreePattern(
  1480. DagInit::get(DI, "",
  1481. std::vector<std::pair<Init*, std::string> >()),
  1482. OpName);
  1483. // Input argument?
  1484. TreePatternNode *Res = new TreePatternNode(DI, 1);
  1485. if (R->getName() == "node" && !OpName.empty()) {
  1486. if (OpName.empty())
  1487. error("'node' argument requires a name to match with operand list");
  1488. Args.push_back(OpName);
  1489. }
  1490. Res->setName(OpName);
  1491. return Res;
  1492. }
  1493. if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
  1494. if (!OpName.empty())
  1495. error("Constant int argument should not have a name!");
  1496. return new TreePatternNode(II, 1);
  1497. }
  1498. if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
  1499. // Turn this into an IntInit.
  1500. Init *II = BI->convertInitializerTo(IntRecTy::get());
  1501. if (II == 0 || !dynamic_cast<IntInit*>(II))
  1502. error("Bits value must be constants!");
  1503. return ParseTreePattern(II, OpName);
  1504. }
  1505. DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
  1506. if (!Dag) {
  1507. TheInit->dump();
  1508. error("Pattern has unexpected init kind!");
  1509. }
  1510. DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
  1511. if (!OpDef) error("Pattern has unexpected operator type!");
  1512. Record *Operator = OpDef->getDef();
  1513. if (Operator->isSubClassOf("ValueType")) {
  1514. // If the operator is a ValueType, then this must be "type cast" of a leaf
  1515. // node.
  1516. if (Dag->getNumArgs() != 1)
  1517. error("Type cast only takes one operand!");
  1518. TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
  1519. // Apply the type cast.
  1520. assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
  1521. New->UpdateNodeType(0, getValueType(Operator), *this);
  1522. if (!OpName.empty())
  1523. error("ValueType cast should not have a name!");
  1524. return New;
  1525. }
  1526. // Verify that this is something that makes sense for an operator.
  1527. if (!Operator->isSubClassOf("PatFrag") &&
  1528. !Operator->isSubClassOf("SDNode") &&
  1529. !Operator->isSubClassOf("Instruction") &&
  1530. !Operator->isSubClassOf("SDNodeXForm") &&
  1531. !Operator->isSubClassOf("Intrinsic") &&
  1532. Operator->getName() != "set" &&
  1533. Operator->getName() != "implicit")
  1534. error("Unrecognized node '" + Operator->getName() + "'!");
  1535. // Check to see if this is something that is illegal in an input pattern.
  1536. if (isInputPattern) {
  1537. if (Operator->isSubClassOf("Instruction") ||
  1538. Operator->isSubClassOf("SDNodeXForm"))
  1539. error("Cannot use '" + Operator->getName() + "' in an input pattern!");
  1540. } else {
  1541. if (Operator->isSubClassOf("Intrinsic"))
  1542. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1543. if (Operator->isSubClassOf("SDNode") &&
  1544. Operator->getName() != "imm" &&
  1545. Operator->getName() != "fpimm" &&
  1546. Operator->getName() != "tglobaltlsaddr" &&
  1547. Operator->getName() != "tconstpool" &&
  1548. Operator->getName() != "tjumptable" &&
  1549. Operator->getName() != "tframeindex" &&
  1550. Operator->getName() != "texternalsym" &&
  1551. Operator->getName() != "tblockaddress" &&
  1552. Operator->getName() != "tglobaladdr" &&
  1553. Operator->getName() != "bb" &&
  1554. Operator->getName() != "vt")
  1555. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1556. }
  1557. std::vector<TreePatternNode*> Children;
  1558. // Parse all the operands.
  1559. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
  1560. Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
  1561. // If the operator is an intrinsic, then this is just syntactic sugar for for
  1562. // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
  1563. // convert the intrinsic name to a number.
  1564. if (Operator->isSubClassOf("Intrinsic")) {
  1565. const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
  1566. unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
  1567. // If this intrinsic returns void, it must have side-effects and thus a
  1568. // chain.
  1569. if (Int.IS.RetVTs.empty())
  1570. Operator = getDAGPatterns().get_intrinsic_void_sdnode();
  1571. else if (Int.ModRef != CodeGenIntrinsic::NoMem)
  1572. // Has side-effects, requires chain.
  1573. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
  1574. else // Otherwise, no chain.
  1575. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
  1576. TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
  1577. Children.insert(Children.begin(), IIDNode);
  1578. }
  1579. unsigned NumResults = GetNumNodeResults(Operator, CDP);
  1580. TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
  1581. Result->setName(OpName);
  1582. if (!Dag->getName().empty()) {
  1583. assert(Result->getName().empty());
  1584. Result->setName(Dag->getName());
  1585. }
  1586. return Result;
  1587. }
  1588. /// SimplifyTree - See if we can simplify this tree to eliminate something that
  1589. /// will never match in favor of something obvious that will. This is here
  1590. /// strictly as a convenience to target authors because it allows them to write
  1591. /// more type generic things and have useless type casts fold away.
  1592. ///
  1593. /// This returns true if any change is made.
  1594. static bool SimplifyTree(TreePatternNode *&N) {
  1595. if (N->isLeaf())
  1596. return false;
  1597. // If we have a bitconvert with a resolved type and if the source and
  1598. // destination types are the same, then the bitconvert is useless, remove it.
  1599. if (N->getOperator()->getName() == "bitconvert" &&
  1600. N->getExtType(0).isConcrete() &&
  1601. N->getExtType(0) == N->getChild(0)->getExtType(0) &&
  1602. N->getName().empty()) {
  1603. N = N->getChild(0);
  1604. SimplifyTree(N);
  1605. return true;
  1606. }
  1607. // Walk all children.
  1608. bool MadeChange = false;
  1609. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  1610. TreePatternNode *Child = N->getChild(i);
  1611. MadeChange |= SimplifyTree(Child);
  1612. N->setChild(i, Child);
  1613. }
  1614. return MadeChange;
  1615. }
  1616. /// InferAllTypes - Infer/propagate as many types throughout the expression
  1617. /// patterns as possible. Return true if all types are inferred, false
  1618. /// otherwise. Throw an exception if a type contradiction is found.
  1619. bool TreePattern::
  1620. InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
  1621. if (NamedNodes.empty())
  1622. ComputeNamedNodes();
  1623. bool MadeChange = true;
  1624. while (MadeChange) {
  1625. MadeChange = false;
  1626. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1627. MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
  1628. MadeChange |= SimplifyTree(Trees[i]);
  1629. }
  1630. // If there are constraints on our named nodes, apply them.
  1631. for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
  1632. I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
  1633. SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
  1634. // If we have input named node types, propagate their types to the named
  1635. // values here.
  1636. if (InNamedTypes) {
  1637. // FIXME: Should be error?
  1638. assert(InNamedTypes->count(I->getKey()) &&
  1639. "Named node in output pattern but not input pattern?");
  1640. const SmallVectorImpl<TreePatternNode*> &InNodes =
  1641. InNamedTypes->find(I->getKey())->second;
  1642. // The input types should be fully resolved by now.
  1643. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  1644. // If this node is a register class, and it is the root of the pattern
  1645. // then we're mapping something onto an input register. We allow
  1646. // changing the type of the input register in this case. This allows
  1647. // us to match things like:
  1648. // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
  1649. if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
  1650. DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
  1651. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1652. DI->getDef()->isSubClassOf("RegisterOperand")))
  1653. continue;
  1654. }
  1655. assert(Nodes[i]->getNumTypes() == 1 &&
  1656. InNodes[0]->getNumTypes() == 1 &&
  1657. "FIXME: cannot name multiple result nodes yet");
  1658. MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
  1659. *this);
  1660. }
  1661. }
  1662. // If there are multiple nodes with the same name, they must all have the
  1663. // same type.
  1664. if (I->second.size() > 1) {
  1665. for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
  1666. TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
  1667. assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
  1668. "FIXME: cannot name multiple result nodes yet");
  1669. MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
  1670. MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
  1671. }
  1672. }
  1673. }
  1674. }
  1675. bool HasUnresolvedTypes = false;
  1676. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1677. HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
  1678. return !HasUnresolvedTypes;
  1679. }
  1680. void TreePattern::print(raw_ostream &OS) const {
  1681. OS << getRecord()->getName();
  1682. if (!Args.empty()) {
  1683. OS << "(" << Args[0];
  1684. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  1685. OS << ", " << Args[i];
  1686. OS << ")";
  1687. }
  1688. OS << ": ";
  1689. if (Trees.size() > 1)
  1690. OS << "[\n";
  1691. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1692. OS << "\t";
  1693. Trees[i]->print(OS);
  1694. OS << "\n";
  1695. }
  1696. if (Trees.size() > 1)
  1697. OS << "]\n";
  1698. }
  1699. void TreePattern::dump() const { print(errs()); }
  1700. //===----------------------------------------------------------------------===//
  1701. // CodeGenDAGPatterns implementation
  1702. //
  1703. CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
  1704. Records(R), Target(R) {
  1705. Intrinsics = LoadIntrinsics(Records, false);
  1706. TgtIntrinsics = LoadIntrinsics(Records, true);
  1707. ParseNodeInfo();
  1708. ParseNodeTransforms();
  1709. ParseComplexPatterns();
  1710. ParsePatternFragments();
  1711. ParseDefaultOperands();
  1712. ParseInstructions();
  1713. ParsePatterns();
  1714. // Generate variants. For example, commutative patterns can match
  1715. // multiple ways. Add them to PatternsToMatch as well.
  1716. GenerateVariants();
  1717. // Infer instruction flags. For example, we can detect loads,
  1718. // stores, and side effects in many cases by examining an
  1719. // instruction's pattern.
  1720. InferInstructionFlags();
  1721. }
  1722. CodeGenDAGPatterns::~CodeGenDAGPatterns() {
  1723. for (pf_iterator I = PatternFragments.begin(),
  1724. E = PatternFragments.end(); I != E; ++I)
  1725. delete I->second;
  1726. }
  1727. Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
  1728. Record *N = Records.getDef(Name);
  1729. if (!N || !N->isSubClassOf("SDNode")) {
  1730. errs() << "Error getting SDNode '" << Name << "'!\n";
  1731. exit(1);
  1732. }
  1733. return N;
  1734. }
  1735. // Parse all of the SDNode definitions for the target, populating SDNodes.
  1736. void CodeGenDAGPatterns::ParseNodeInfo() {
  1737. std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
  1738. while (!Nodes.empty()) {
  1739. SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
  1740. Nodes.pop_back();
  1741. }
  1742. // Get the builtin intrinsic nodes.
  1743. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
  1744. intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
  1745. intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
  1746. }
  1747. /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
  1748. /// map, and emit them to the file as functions.
  1749. void CodeGenDAGPatterns::ParseNodeTransforms() {
  1750. std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
  1751. while (!Xforms.empty()) {
  1752. Record *XFormNode = Xforms.back();
  1753. Record *SDNode = XFormNode->getValueAsDef("Opcode");
  1754. std::string Code = XFormNode->getValueAsString("XFormFunction");
  1755. SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
  1756. Xforms.pop_back();
  1757. }
  1758. }
  1759. void CodeGenDAGPatterns::ParseComplexPatterns() {
  1760. std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
  1761. while (!AMs.empty()) {
  1762. ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
  1763. AMs.pop_back();
  1764. }
  1765. }
  1766. /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
  1767. /// file, building up the PatternFragments map. After we've collected them all,
  1768. /// inline fragments together as necessary, so that there are no references left
  1769. /// inside a pattern fragment to a pattern fragment.
  1770. ///
  1771. void CodeGenDAGPatterns::ParsePatternFragments() {
  1772. std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
  1773. // First step, parse all of the fragments.
  1774. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1775. DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
  1776. TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
  1777. PatternFragments[Fragments[i]] = P;
  1778. // Validate the argument list, converting it to set, to discard duplicates.
  1779. std::vector<std::string> &Args = P->getArgList();
  1780. std::set<std::string> OperandsSet(Args.begin(), Args.end());
  1781. if (OperandsSet.count(""))
  1782. P->error("Cannot have unnamed 'node' values in pattern fragment!");
  1783. // Parse the operands list.
  1784. DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
  1785. DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
  1786. // Special cases: ops == outs == ins. Different names are used to
  1787. // improve readability.
  1788. if (!OpsOp ||
  1789. (OpsOp->getDef()->getName() != "ops" &&
  1790. OpsOp->getDef()->getName() != "outs" &&
  1791. OpsOp->getDef()->getName() != "ins"))
  1792. P->error("Operands list should start with '(ops ... '!");
  1793. // Copy over the arguments.
  1794. Args.clear();
  1795. for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
  1796. if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
  1797. static_cast<DefInit*>(OpsList->getArg(j))->
  1798. getDef()->getName() != "node")
  1799. P->error("Operands list should all be 'node' values.");
  1800. if (OpsList->getArgName(j).empty())
  1801. P->error("Operands list should have names for each operand!");
  1802. if (!OperandsSet.count(OpsList->getArgName(j)))
  1803. P->error("'" + OpsList->getArgName(j) +
  1804. "' does not occur in pattern or was multiply specified!");
  1805. OperandsSet.erase(OpsList->getArgName(j));
  1806. Args.push_back(OpsList->getArgName(j));
  1807. }
  1808. if (!OperandsSet.empty())
  1809. P->error("Operands list does not contain an entry for operand '" +
  1810. *OperandsSet.begin() + "'!");
  1811. // If there is a code init for this fragment, keep track of the fact that
  1812. // this fragment uses it.
  1813. TreePredicateFn PredFn(P);
  1814. if (!PredFn.isAlwaysTrue())
  1815. P->getOnlyTree()->addPredicateFn(PredFn);
  1816. // If there is a node transformation corresponding to this, keep track of
  1817. // it.
  1818. Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
  1819. if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
  1820. P->getOnlyTree()->setTransformFn(Transform);
  1821. }
  1822. // Now that we've parsed all of the tree fragments, do a closure on them so
  1823. // that there are not references to PatFrags left inside of them.
  1824. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1825. TreePattern *ThePat = PatternFragments[Fragments[i]];
  1826. ThePat->InlinePatternFragments();
  1827. // Infer as many types as possible. Don't worry about it if we don't infer
  1828. // all of them, some may depend on the inputs of the pattern.
  1829. try {
  1830. ThePat->InferAllTypes();
  1831. } catch (...) {
  1832. // If this pattern fragment is not supported by this target (no types can
  1833. // satisfy its constraints), just ignore it. If the bogus pattern is
  1834. // actually used by instructions, the type consistency error will be
  1835. // reported there.
  1836. }
  1837. // If debugging, print out the pattern fragment result.
  1838. DEBUG(ThePat->dump());
  1839. }
  1840. }
  1841. void CodeGenDAGPatterns::ParseDefaultOperands() {
  1842. std::vector<Record*> DefaultOps[2];
  1843. DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
  1844. DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
  1845. // Find some SDNode.
  1846. assert(!SDNodes.empty() && "No SDNodes parsed?");
  1847. Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
  1848. for (unsigned iter = 0; iter != 2; ++iter) {
  1849. for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
  1850. DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
  1851. // Clone the DefaultInfo dag node, changing the operator from 'ops' to
  1852. // SomeSDnode so that we can parse this.
  1853. std::vector<std::pair<Init*, std::string> > Ops;
  1854. for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
  1855. Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
  1856. DefaultInfo->getArgName(op)));
  1857. DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
  1858. // Create a TreePattern to parse this.
  1859. TreePattern P(DefaultOps[iter][i], DI, false, *this);
  1860. assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
  1861. // Copy the operands over into a DAGDefaultOperand.
  1862. DAGDefaultOperand DefaultOpInfo;
  1863. TreePatternNode *T = P.getTree(0);
  1864. for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
  1865. TreePatternNode *TPN = T->getChild(op);
  1866. while (TPN->ApplyTypeConstraints(P, false))
  1867. /* Resolve all types */;
  1868. if (TPN->ContainsUnresolvedType()) {
  1869. if (iter == 0)
  1870. throw "Value #" + utostr(i) + " of PredicateOperand '" +
  1871. DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
  1872. else
  1873. throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
  1874. DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
  1875. }
  1876. DefaultOpInfo.DefaultOps.push_back(TPN);
  1877. }
  1878. // Insert it into the DefaultOperands map so we can find it later.
  1879. DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
  1880. }
  1881. }
  1882. }
  1883. /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
  1884. /// instruction input. Return true if this is a real use.
  1885. static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
  1886. std::map<std::string, TreePatternNode*> &InstInputs) {
  1887. // No name -> not interesting.
  1888. if (Pat->getName().empty()) {
  1889. if (Pat->isLeaf()) {
  1890. DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
  1891. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1892. DI->getDef()->isSubClassOf("RegisterOperand")))
  1893. I->error("Input " + DI->getDef()->getName() + " must be named!");
  1894. }
  1895. return false;
  1896. }
  1897. Record *Rec;
  1898. if (Pat->isLeaf()) {
  1899. DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
  1900. if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
  1901. Rec = DI->getDef();
  1902. } else {
  1903. Rec = Pat->getOperator();
  1904. }
  1905. // SRCVALUE nodes are ignored.
  1906. if (Rec->getName() == "srcvalue")
  1907. return false;
  1908. TreePatternNode *&Slot = InstInputs[Pat->getName()];
  1909. if (!Slot) {
  1910. Slot = Pat;
  1911. return true;
  1912. }
  1913. Record *SlotRec;
  1914. if (Slot->isLeaf()) {
  1915. SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
  1916. } else {
  1917. assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
  1918. SlotRec = Slot->getOperator();
  1919. }
  1920. // Ensure that the inputs agree if we've already seen this input.
  1921. if (Rec != SlotRec)
  1922. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  1923. if (Slot->getExtTypes() != Pat->getExtTypes())
  1924. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  1925. return true;
  1926. }
  1927. /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
  1928. /// part of "I", the instruction), computing the set of inputs and outputs of
  1929. /// the pattern. Report errors if we see anything naughty.
  1930. void CodeGenDAGPatterns::
  1931. FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
  1932. std::map<std::string, TreePatternNode*> &InstInputs,
  1933. std::map<std::string, TreePatternNode*>&InstResults,
  1934. std::vector<Record*> &InstImpResults) {
  1935. if (Pat->isLeaf()) {
  1936. bool isUse = HandleUse(I, Pat, InstInputs);
  1937. if (!isUse && Pat->getTransformFn())
  1938. I->error("Cannot specify a transform function for a non-input value!");
  1939. return;
  1940. }
  1941. if (Pat->getOperator()->getName() == "implicit") {
  1942. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  1943. TreePatternNode *Dest = Pat->getChild(i);
  1944. if (!Dest->isLeaf())
  1945. I->error("implicitly defined value should be a register!");
  1946. DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
  1947. if (!Val || !Val->getDef()->isSubClassOf("Register"))
  1948. I->error("implicitly defined value should be a register!");
  1949. InstImpResults.push_back(Val->getDef());
  1950. }
  1951. return;
  1952. }
  1953. if (Pat->getOperator()->getName() != "set") {
  1954. // If this is not a set, verify that the children nodes are not void typed,
  1955. // and recurse.
  1956. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  1957. if (Pat->getChild(i)->getNumTypes() == 0)
  1958. I->error("Cannot have void nodes inside of patterns!");
  1959. FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
  1960. InstImpResults);
  1961. }
  1962. // If this is a non-leaf node with no children, treat it basically as if
  1963. // it were a leaf. This handles nodes like (imm).
  1964. bool isUse = HandleUse(I, Pat, InstInputs);
  1965. if (!isUse && Pat->getTransformFn())
  1966. I->error("Cannot specify a transform function for a non-input value!");
  1967. return;
  1968. }
  1969. // Otherwise, this is a set, validate and collect instruction results.
  1970. if (Pat->getNumChildren() == 0)
  1971. I->error("set requires operands!");
  1972. if (Pat->getTransformFn())
  1973. I->error("Cannot specify a transform function on a set node!");
  1974. // Check the set destinations.
  1975. unsigned NumDests = Pat->getNumChildren()-1;
  1976. for (unsigned i = 0; i != NumDests; ++i) {
  1977. TreePatternNode *Dest = Pat->getChild(i);
  1978. if (!Dest->isLeaf())
  1979. I->error("set destination should be a register!");
  1980. DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
  1981. if (!Val)
  1982. I->error("set destination should be a register!");
  1983. if (Val->getDef()->isSubClassOf("RegisterClass") ||
  1984. Val->getDef()->isSubClassOf("RegisterOperand") ||
  1985. Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
  1986. if (Dest->getName().empty())
  1987. I->error("set destination must have a name!");
  1988. if (InstResults.count(Dest->getName()))
  1989. I->error("cannot set '" + Dest->getName() +"' multiple times");
  1990. InstResults[Dest->getName()] = Dest;
  1991. } else if (Val->getDef()->isSubClassOf("Register")) {
  1992. InstImpResults.push_back(Val->getDef());
  1993. } else {
  1994. I->error("set destination should be a register!");
  1995. }
  1996. }
  1997. // Verify and collect info from the computation.
  1998. FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
  1999. InstInputs, InstResults, InstImpResults);
  2000. }
  2001. //===----------------------------------------------------------------------===//
  2002. // Instruction Analysis
  2003. //===----------------------------------------------------------------------===//
  2004. class InstAnalyzer {
  2005. const CodeGenDAGPatterns &CDP;
  2006. bool &mayStore;
  2007. bool &mayLoad;
  2008. bool &IsBitcast;
  2009. bool &HasSideEffects;
  2010. bool &IsVariadic;
  2011. public:
  2012. InstAnalyzer(const CodeGenDAGPatterns &cdp,
  2013. bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
  2014. : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
  2015. HasSideEffects(hse), IsVariadic(isv) {
  2016. }
  2017. /// Analyze - Analyze the specified instruction, returning true if the
  2018. /// instruction had a pattern.
  2019. bool Analyze(Record *InstRecord) {
  2020. const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
  2021. if (Pattern == 0) {
  2022. HasSideEffects = 1;
  2023. return false; // No pattern.
  2024. }
  2025. // FIXME: Assume only the first tree is the pattern. The others are clobber
  2026. // nodes.
  2027. AnalyzeNode(Pattern->getTree(0));
  2028. return true;
  2029. }
  2030. private:
  2031. bool IsNodeBitcast(const TreePatternNode *N) const {
  2032. if (HasSideEffects || mayLoad || mayStore || IsVariadic)
  2033. return false;
  2034. if (N->getNumChildren() != 2)
  2035. return false;
  2036. const TreePatternNode *N0 = N->getChild(0);
  2037. if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
  2038. return false;
  2039. const TreePatternNode *N1 = N->getChild(1);
  2040. if (N1->isLeaf())
  2041. return false;
  2042. if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
  2043. return false;
  2044. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
  2045. if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
  2046. return false;
  2047. return OpInfo.getEnumName() == "ISD::BITCAST";
  2048. }
  2049. void AnalyzeNode(const TreePatternNode *N) {
  2050. if (N->isLeaf()) {
  2051. if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
  2052. Record *LeafRec = DI->getDef();
  2053. // Handle ComplexPattern leaves.
  2054. if (LeafRec->isSubClassOf("ComplexPattern")) {
  2055. const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
  2056. if (CP.hasProperty(SDNPMayStore)) mayStore = true;
  2057. if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
  2058. if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
  2059. }
  2060. }
  2061. return;
  2062. }
  2063. // Analyze children.
  2064. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2065. AnalyzeNode(N->getChild(i));
  2066. // Ignore set nodes, which are not SDNodes.
  2067. if (N->getOperator()->getName() == "set") {
  2068. IsBitcast = IsNodeBitcast(N);
  2069. return;
  2070. }
  2071. // Get information about the SDNode for the operator.
  2072. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
  2073. // Notice properties of the node.
  2074. if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
  2075. if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
  2076. if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
  2077. if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
  2078. if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
  2079. // If this is an intrinsic, analyze it.
  2080. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
  2081. mayLoad = true;// These may load memory.
  2082. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
  2083. mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
  2084. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
  2085. // WriteMem intrinsics can have other strange effects.
  2086. HasSideEffects = true;
  2087. }
  2088. }
  2089. };
  2090. static void InferFromPattern(const CodeGenInstruction &Inst,
  2091. bool &MayStore, bool &MayLoad,
  2092. bool &IsBitcast,
  2093. bool &HasSideEffects, bool &IsVariadic,
  2094. const CodeGenDAGPatterns &CDP) {
  2095. MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
  2096. bool HadPattern =
  2097. InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
  2098. .Analyze(Inst.TheDef);
  2099. // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
  2100. if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
  2101. // If we decided that this is a store from the pattern, then the .td file
  2102. // entry is redundant.
  2103. if (MayStore)
  2104. fprintf(stderr,
  2105. "Warning: mayStore flag explicitly set on instruction '%s'"
  2106. " but flag already inferred from pattern.\n",
  2107. Inst.TheDef->getName().c_str());
  2108. MayStore = true;
  2109. }
  2110. if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
  2111. // If we decided that this is a load from the pattern, then the .td file
  2112. // entry is redundant.
  2113. if (MayLoad)
  2114. fprintf(stderr,
  2115. "Warning: mayLoad flag explicitly set on instruction '%s'"
  2116. " but flag already inferred from pattern.\n",
  2117. Inst.TheDef->getName().c_str());
  2118. MayLoad = true;
  2119. }
  2120. if (Inst.neverHasSideEffects) {
  2121. if (HadPattern)
  2122. fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
  2123. "which already has a pattern\n", Inst.TheDef->getName().c_str());
  2124. HasSideEffects = false;
  2125. }
  2126. if (Inst.hasSideEffects) {
  2127. if (HasSideEffects)
  2128. fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
  2129. "which already inferred this.\n", Inst.TheDef->getName().c_str());
  2130. HasSideEffects = true;
  2131. }
  2132. if (Inst.Operands.isVariadic)
  2133. IsVariadic = true; // Can warn if we want.
  2134. }
  2135. /// ParseInstructions - Parse all of the instructions, inlining and resolving
  2136. /// any fragments involved. This populates the Instructions list with fully
  2137. /// resolved instructions.
  2138. void CodeGenDAGPatterns::ParseInstructions() {
  2139. std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
  2140. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2141. ListInit *LI = 0;
  2142. if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
  2143. LI = Instrs[i]->getValueAsListInit("Pattern");
  2144. // If there is no pattern, only collect minimal information about the
  2145. // instruction for its operand list. We have to assume that there is one
  2146. // result, as we have no detailed info.
  2147. if (!LI || LI->getSize() == 0) {
  2148. std::vector<Record*> Results;
  2149. std::vector<Record*> Operands;
  2150. CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2151. if (InstInfo.Operands.size() != 0) {
  2152. if (InstInfo.Operands.NumDefs == 0) {
  2153. // These produce no results
  2154. for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
  2155. Operands.push_back(InstInfo.Operands[j].Rec);
  2156. } else {
  2157. // Assume the first operand is the result.
  2158. Results.push_back(InstInfo.Operands[0].Rec);
  2159. // The rest are inputs.
  2160. for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
  2161. Operands.push_back(InstInfo.Operands[j].Rec);
  2162. }
  2163. }
  2164. // Create and insert the instruction.
  2165. std::vector<Record*> ImpResults;
  2166. Instructions.insert(std::make_pair(Instrs[i],
  2167. DAGInstruction(0, Results, Operands, ImpResults)));
  2168. continue; // no pattern.
  2169. }
  2170. // Parse the instruction.
  2171. TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
  2172. // Inline pattern fragments into it.
  2173. I->InlinePatternFragments();
  2174. // Infer as many types as possible. If we cannot infer all of them, we can
  2175. // never do anything with this instruction pattern: report it to the user.
  2176. if (!I->InferAllTypes())
  2177. I->error("Could not infer all types in pattern!");
  2178. // InstInputs - Keep track of all of the inputs of the instruction, along
  2179. // with the record they are declared as.
  2180. std::map<std::string, TreePatternNode*> InstInputs;
  2181. // InstResults - Keep track of all the virtual registers that are 'set'
  2182. // in the instruction, including what reg class they are.
  2183. std::map<std::string, TreePatternNode*> InstResults;
  2184. std::vector<Record*> InstImpResults;
  2185. // Verify that the top-level forms in the instruction are of void type, and
  2186. // fill in the InstResults map.
  2187. for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
  2188. TreePatternNode *Pat = I->getTree(j);
  2189. if (Pat->getNumTypes() != 0)
  2190. I->error("Top-level forms in instruction pattern should have"
  2191. " void types");
  2192. // Find inputs and outputs, and verify the structure of the uses/defs.
  2193. FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
  2194. InstImpResults);
  2195. }
  2196. // Now that we have inputs and outputs of the pattern, inspect the operands
  2197. // list for the instruction. This determines the order that operands are
  2198. // added to the machine instruction the node corresponds to.
  2199. unsigned NumResults = InstResults.size();
  2200. // Parse the operands list from the (ops) list, validating it.
  2201. assert(I->getArgList().empty() && "Args list should still be empty here!");
  2202. CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
  2203. // Check that all of the results occur first in the list.
  2204. std::vector<Record*> Results;
  2205. TreePatternNode *Res0Node = 0;
  2206. for (unsigned i = 0; i != NumResults; ++i) {
  2207. if (i == CGI.Operands.size())
  2208. I->error("'" + InstResults.begin()->first +
  2209. "' set but does not appear in operand list!");
  2210. const std::string &OpName = CGI.Operands[i].Name;
  2211. // Check that it exists in InstResults.
  2212. TreePatternNode *RNode = InstResults[OpName];
  2213. if (RNode == 0)
  2214. I->error("Operand $" + OpName + " does not exist in operand list!");
  2215. if (i == 0)
  2216. Res0Node = RNode;
  2217. Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
  2218. if (R == 0)
  2219. I->error("Operand $" + OpName + " should be a set destination: all "
  2220. "outputs must occur before inputs in operand list!");
  2221. if (CGI.Operands[i].Rec != R)
  2222. I->error("Operand $" + OpName + " class mismatch!");
  2223. // Remember the return type.
  2224. Results.push_back(CGI.Operands[i].Rec);
  2225. // Okay, this one checks out.
  2226. InstResults.erase(OpName);
  2227. }
  2228. // Loop over the inputs next. Make a copy of InstInputs so we can destroy
  2229. // the copy while we're checking the inputs.
  2230. std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
  2231. std::vector<TreePatternNode*> ResultNodeOperands;
  2232. std::vector<Record*> Operands;
  2233. for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
  2234. CGIOperandList::OperandInfo &Op = CGI.Operands[i];
  2235. const std::string &OpName = Op.Name;
  2236. if (OpName.empty())
  2237. I->error("Operand #" + utostr(i) + " in operands list has no name!");
  2238. if (!InstInputsCheck.count(OpName)) {
  2239. // If this is an predicate operand or optional def operand with an
  2240. // DefaultOps set filled in, we can ignore this. When we codegen it,
  2241. // we will do so as always executed.
  2242. if (Op.Rec->isSubClassOf("PredicateOperand") ||
  2243. Op.Rec->isSubClassOf("OptionalDefOperand")) {
  2244. // Does it have a non-empty DefaultOps field? If so, ignore this
  2245. // operand.
  2246. if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
  2247. continue;
  2248. }
  2249. I->error("Operand $" + OpName +
  2250. " does not appear in the instruction pattern");
  2251. }
  2252. TreePatternNode *InVal = InstInputsCheck[OpName];
  2253. InstInputsCheck.erase(OpName); // It occurred, remove from map.
  2254. if (InVal->isLeaf() &&
  2255. dynamic_cast<DefInit*>(InVal->getLeafValue())) {
  2256. Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
  2257. if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
  2258. I->error("Operand $" + OpName + "'s register class disagrees"
  2259. " between the operand and pattern");
  2260. }
  2261. Operands.push_back(Op.Rec);
  2262. // Construct the result for the dest-pattern operand list.
  2263. TreePatternNode *OpNode = InVal->clone();
  2264. // No predicate is useful on the result.
  2265. OpNode->clearPredicateFns();
  2266. // Promote the xform function to be an explicit node if set.
  2267. if (Record *Xform = OpNode->getTransformFn()) {
  2268. OpNode->setTransformFn(0);
  2269. std::vector<TreePatternNode*> Children;
  2270. Children.push_back(OpNode);
  2271. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2272. }
  2273. ResultNodeOperands.push_back(OpNode);
  2274. }
  2275. if (!InstInputsCheck.empty())
  2276. I->error("Input operand $" + InstInputsCheck.begin()->first +
  2277. " occurs in pattern but not in operands list!");
  2278. TreePatternNode *ResultPattern =
  2279. new TreePatternNode(I->getRecord(), ResultNodeOperands,
  2280. GetNumNodeResults(I->getRecord(), *this));
  2281. // Copy fully inferred output node type to instruction result pattern.
  2282. for (unsigned i = 0; i != NumResults; ++i)
  2283. ResultPattern->setType(i, Res0Node->getExtType(i));
  2284. // Create and insert the instruction.
  2285. // FIXME: InstImpResults should not be part of DAGInstruction.
  2286. DAGInstruction TheInst(I, Results, Operands, InstImpResults);
  2287. Instructions.insert(std::make_pair(I->getRecord(), TheInst));
  2288. // Use a temporary tree pattern to infer all types and make sure that the
  2289. // constructed result is correct. This depends on the instruction already
  2290. // being inserted into the Instructions map.
  2291. TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
  2292. Temp.InferAllTypes(&I->getNamedNodesMap());
  2293. DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
  2294. TheInsertedInst.setResultPattern(Temp.getOnlyTree());
  2295. DEBUG(I->dump());
  2296. }
  2297. // If we can, convert the instructions to be patterns that are matched!
  2298. for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
  2299. Instructions.begin(),
  2300. E = Instructions.end(); II != E; ++II) {
  2301. DAGInstruction &TheInst = II->second;
  2302. const TreePattern *I = TheInst.getPattern();
  2303. if (I == 0) continue; // No pattern.
  2304. // FIXME: Assume only the first tree is the pattern. The others are clobber
  2305. // nodes.
  2306. TreePatternNode *Pattern = I->getTree(0);
  2307. TreePatternNode *SrcPattern;
  2308. if (Pattern->getOperator()->getName() == "set") {
  2309. SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
  2310. } else{
  2311. // Not a set (store or something?)
  2312. SrcPattern = Pattern;
  2313. }
  2314. Record *Instr = II->first;
  2315. AddPatternToMatch(I,
  2316. PatternToMatch(Instr,
  2317. Instr->getValueAsListInit("Predicates"),
  2318. SrcPattern,
  2319. TheInst.getResultPattern(),
  2320. TheInst.getImpResults(),
  2321. Instr->getValueAsInt("AddedComplexity"),
  2322. Instr->getID()));
  2323. }
  2324. }
  2325. typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
  2326. static void FindNames(const TreePatternNode *P,
  2327. std::map<std::string, NameRecord> &Names,
  2328. const TreePattern *PatternTop) {
  2329. if (!P->getName().empty()) {
  2330. NameRecord &Rec = Names[P->getName()];
  2331. // If this is the first instance of the name, remember the node.
  2332. if (Rec.second++ == 0)
  2333. Rec.first = P;
  2334. else if (Rec.first->getExtTypes() != P->getExtTypes())
  2335. PatternTop->error("repetition of value: $" + P->getName() +
  2336. " where different uses have different types!");
  2337. }
  2338. if (!P->isLeaf()) {
  2339. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
  2340. FindNames(P->getChild(i), Names, PatternTop);
  2341. }
  2342. }
  2343. void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
  2344. const PatternToMatch &PTM) {
  2345. // Do some sanity checking on the pattern we're about to match.
  2346. std::string Reason;
  2347. if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
  2348. Pattern->error("Pattern can never match: " + Reason);
  2349. // If the source pattern's root is a complex pattern, that complex pattern
  2350. // must specify the nodes it can potentially match.
  2351. if (const ComplexPattern *CP =
  2352. PTM.getSrcPattern()->getComplexPatternInfo(*this))
  2353. if (CP->getRootNodes().empty())
  2354. Pattern->error("ComplexPattern at root must specify list of opcodes it"
  2355. " could match");
  2356. // Find all of the named values in the input and output, ensure they have the
  2357. // same type.
  2358. std::map<std::string, NameRecord> SrcNames, DstNames;
  2359. FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
  2360. FindNames(PTM.getDstPattern(), DstNames, Pattern);
  2361. // Scan all of the named values in the destination pattern, rejecting them if
  2362. // they don't exist in the input pattern.
  2363. for (std::map<std::string, NameRecord>::iterator
  2364. I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
  2365. if (SrcNames[I->first].first == 0)
  2366. Pattern->error("Pattern has input without matching name in output: $" +
  2367. I->first);
  2368. }
  2369. // Scan all of the named values in the source pattern, rejecting them if the
  2370. // name isn't used in the dest, and isn't used to tie two values together.
  2371. for (std::map<std::string, NameRecord>::iterator
  2372. I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
  2373. if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
  2374. Pattern->error("Pattern has dead named input: $" + I->first);
  2375. PatternsToMatch.push_back(PTM);
  2376. }
  2377. void CodeGenDAGPatterns::InferInstructionFlags() {
  2378. const std::vector<const CodeGenInstruction*> &Instructions =
  2379. Target.getInstructionsByEnumValue();
  2380. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  2381. CodeGenInstruction &InstInfo =
  2382. const_cast<CodeGenInstruction &>(*Instructions[i]);
  2383. // Determine properties of the instruction from its pattern.
  2384. bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
  2385. InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
  2386. HasSideEffects, IsVariadic, *this);
  2387. InstInfo.mayStore = MayStore;
  2388. InstInfo.mayLoad = MayLoad;
  2389. InstInfo.isBitcast = IsBitcast;
  2390. InstInfo.hasSideEffects = HasSideEffects;
  2391. InstInfo.Operands.isVariadic = IsVariadic;
  2392. // Sanity checks.
  2393. if (InstInfo.isReMaterializable && InstInfo.hasSideEffects)
  2394. throw TGError(InstInfo.TheDef->getLoc(), "The instruction " +
  2395. InstInfo.TheDef->getName() +
  2396. " is rematerializable AND has unmodeled side effects?");
  2397. }
  2398. }
  2399. /// Given a pattern result with an unresolved type, see if we can find one
  2400. /// instruction with an unresolved result type. Force this result type to an
  2401. /// arbitrary element if it's possible types to converge results.
  2402. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
  2403. if (N->isLeaf())
  2404. return false;
  2405. // Analyze children.
  2406. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2407. if (ForceArbitraryInstResultType(N->getChild(i), TP))
  2408. return true;
  2409. if (!N->getOperator()->isSubClassOf("Instruction"))
  2410. return false;
  2411. // If this type is already concrete or completely unknown we can't do
  2412. // anything.
  2413. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
  2414. if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
  2415. continue;
  2416. // Otherwise, force its type to the first possibility (an arbitrary choice).
  2417. if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
  2418. return true;
  2419. }
  2420. return false;
  2421. }
  2422. void CodeGenDAGPatterns::ParsePatterns() {
  2423. std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
  2424. for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
  2425. Record *CurPattern = Patterns[i];
  2426. DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
  2427. TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
  2428. // Inline pattern fragments into it.
  2429. Pattern->InlinePatternFragments();
  2430. ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
  2431. if (LI->getSize() == 0) continue; // no pattern.
  2432. // Parse the instruction.
  2433. TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
  2434. // Inline pattern fragments into it.
  2435. Result->InlinePatternFragments();
  2436. if (Result->getNumTrees() != 1)
  2437. Result->error("Cannot handle instructions producing instructions "
  2438. "with temporaries yet!");
  2439. bool IterateInference;
  2440. bool InferredAllPatternTypes, InferredAllResultTypes;
  2441. do {
  2442. // Infer as many types as possible. If we cannot infer all of them, we
  2443. // can never do anything with this pattern: report it to the user.
  2444. InferredAllPatternTypes =
  2445. Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
  2446. // Infer as many types as possible. If we cannot infer all of them, we
  2447. // can never do anything with this pattern: report it to the user.
  2448. InferredAllResultTypes =
  2449. Result->InferAllTypes(&Pattern->getNamedNodesMap());
  2450. IterateInference = false;
  2451. // Apply the type of the result to the source pattern. This helps us
  2452. // resolve cases where the input type is known to be a pointer type (which
  2453. // is considered resolved), but the result knows it needs to be 32- or
  2454. // 64-bits. Infer the other way for good measure.
  2455. for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
  2456. Pattern->getTree(0)->getNumTypes());
  2457. i != e; ++i) {
  2458. IterateInference = Pattern->getTree(0)->
  2459. UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
  2460. IterateInference |= Result->getTree(0)->
  2461. UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
  2462. }
  2463. // If our iteration has converged and the input pattern's types are fully
  2464. // resolved but the result pattern is not fully resolved, we may have a
  2465. // situation where we have two instructions in the result pattern and
  2466. // the instructions require a common register class, but don't care about
  2467. // what actual MVT is used. This is actually a bug in our modelling:
  2468. // output patterns should have register classes, not MVTs.
  2469. //
  2470. // In any case, to handle this, we just go through and disambiguate some
  2471. // arbitrary types to the result pattern's nodes.
  2472. if (!IterateInference && InferredAllPatternTypes &&
  2473. !InferredAllResultTypes)
  2474. IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
  2475. *Result);
  2476. } while (IterateInference);
  2477. // Verify that we inferred enough types that we can do something with the
  2478. // pattern and result. If these fire the user has to add type casts.
  2479. if (!InferredAllPatternTypes)
  2480. Pattern->error("Could not infer all types in pattern!");
  2481. if (!InferredAllResultTypes) {
  2482. Pattern->dump();
  2483. Result->error("Could not infer all types in pattern result!");
  2484. }
  2485. // Validate that the input pattern is correct.
  2486. std::map<std::string, TreePatternNode*> InstInputs;
  2487. std::map<std::string, TreePatternNode*> InstResults;
  2488. std::vector<Record*> InstImpResults;
  2489. for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
  2490. FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
  2491. InstInputs, InstResults,
  2492. InstImpResults);
  2493. // Promote the xform function to be an explicit node if set.
  2494. TreePatternNode *DstPattern = Result->getOnlyTree();
  2495. std::vector<TreePatternNode*> ResultNodeOperands;
  2496. for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
  2497. TreePatternNode *OpNode = DstPattern->getChild(ii);
  2498. if (Record *Xform = OpNode->getTransformFn()) {
  2499. OpNode->setTransformFn(0);
  2500. std::vector<TreePatternNode*> Children;
  2501. Children.push_back(OpNode);
  2502. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2503. }
  2504. ResultNodeOperands.push_back(OpNode);
  2505. }
  2506. DstPattern = Result->getOnlyTree();
  2507. if (!DstPattern->isLeaf())
  2508. DstPattern = new TreePatternNode(DstPattern->getOperator(),
  2509. ResultNodeOperands,
  2510. DstPattern->getNumTypes());
  2511. for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
  2512. DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
  2513. TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
  2514. Temp.InferAllTypes();
  2515. AddPatternToMatch(Pattern,
  2516. PatternToMatch(CurPattern,
  2517. CurPattern->getValueAsListInit("Predicates"),
  2518. Pattern->getTree(0),
  2519. Temp.getOnlyTree(), InstImpResults,
  2520. CurPattern->getValueAsInt("AddedComplexity"),
  2521. CurPattern->getID()));
  2522. }
  2523. }
  2524. /// CombineChildVariants - Given a bunch of permutations of each child of the
  2525. /// 'operator' node, put them together in all possible ways.
  2526. static void CombineChildVariants(TreePatternNode *Orig,
  2527. const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
  2528. std::vector<TreePatternNode*> &OutVariants,
  2529. CodeGenDAGPatterns &CDP,
  2530. const MultipleUseVarSet &DepVars) {
  2531. // Make sure that each operand has at least one variant to choose from.
  2532. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2533. if (ChildVariants[i].empty())
  2534. return;
  2535. // The end result is an all-pairs construction of the resultant pattern.
  2536. std::vector<unsigned> Idxs;
  2537. Idxs.resize(ChildVariants.size());
  2538. bool NotDone;
  2539. do {
  2540. #ifndef NDEBUG
  2541. DEBUG(if (!Idxs.empty()) {
  2542. errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
  2543. for (unsigned i = 0; i < Idxs.size(); ++i) {
  2544. errs() << Idxs[i] << " ";
  2545. }
  2546. errs() << "]\n";
  2547. });
  2548. #endif
  2549. // Create the variant and add it to the output list.
  2550. std::vector<TreePatternNode*> NewChildren;
  2551. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2552. NewChildren.push_back(ChildVariants[i][Idxs[i]]);
  2553. TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
  2554. Orig->getNumTypes());
  2555. // Copy over properties.
  2556. R->setName(Orig->getName());
  2557. R->setPredicateFns(Orig->getPredicateFns());
  2558. R->setTransformFn(Orig->getTransformFn());
  2559. for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
  2560. R->setType(i, Orig->getExtType(i));
  2561. // If this pattern cannot match, do not include it as a variant.
  2562. std::string ErrString;
  2563. if (!R->canPatternMatch(ErrString, CDP)) {
  2564. delete R;
  2565. } else {
  2566. bool AlreadyExists = false;
  2567. // Scan to see if this pattern has already been emitted. We can get
  2568. // duplication due to things like commuting:
  2569. // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
  2570. // which are the same pattern. Ignore the dups.
  2571. for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
  2572. if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
  2573. AlreadyExists = true;
  2574. break;
  2575. }
  2576. if (AlreadyExists)
  2577. delete R;
  2578. else
  2579. OutVariants.push_back(R);
  2580. }
  2581. // Increment indices to the next permutation by incrementing the
  2582. // indicies from last index backward, e.g., generate the sequence
  2583. // [0, 0], [0, 1], [1, 0], [1, 1].
  2584. int IdxsIdx;
  2585. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  2586. if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
  2587. Idxs[IdxsIdx] = 0;
  2588. else
  2589. break;
  2590. }
  2591. NotDone = (IdxsIdx >= 0);
  2592. } while (NotDone);
  2593. }
  2594. /// CombineChildVariants - A helper function for binary operators.
  2595. ///
  2596. static void CombineChildVariants(TreePatternNode *Orig,
  2597. const std::vector<TreePatternNode*> &LHS,
  2598. const std::vector<TreePatternNode*> &RHS,
  2599. std::vector<TreePatternNode*> &OutVariants,
  2600. CodeGenDAGPatterns &CDP,
  2601. const MultipleUseVarSet &DepVars) {
  2602. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2603. ChildVariants.push_back(LHS);
  2604. ChildVariants.push_back(RHS);
  2605. CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
  2606. }
  2607. static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
  2608. std::vector<TreePatternNode *> &Children) {
  2609. assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
  2610. Record *Operator = N->getOperator();
  2611. // Only permit raw nodes.
  2612. if (!N->getName().empty() || !N->getPredicateFns().empty() ||
  2613. N->getTransformFn()) {
  2614. Children.push_back(N);
  2615. return;
  2616. }
  2617. if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
  2618. Children.push_back(N->getChild(0));
  2619. else
  2620. GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
  2621. if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
  2622. Children.push_back(N->getChild(1));
  2623. else
  2624. GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
  2625. }
  2626. /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
  2627. /// the (potentially recursive) pattern by using algebraic laws.
  2628. ///
  2629. static void GenerateVariantsOf(TreePatternNode *N,
  2630. std::vector<TreePatternNode*> &OutVariants,
  2631. CodeGenDAGPatterns &CDP,
  2632. const MultipleUseVarSet &DepVars) {
  2633. // We cannot permute leaves.
  2634. if (N->isLeaf()) {
  2635. OutVariants.push_back(N);
  2636. return;
  2637. }
  2638. // Look up interesting info about the node.
  2639. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
  2640. // If this node is associative, re-associate.
  2641. if (NodeInfo.hasProperty(SDNPAssociative)) {
  2642. // Re-associate by pulling together all of the linked operators
  2643. std::vector<TreePatternNode*> MaximalChildren;
  2644. GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
  2645. // Only handle child sizes of 3. Otherwise we'll end up trying too many
  2646. // permutations.
  2647. if (MaximalChildren.size() == 3) {
  2648. // Find the variants of all of our maximal children.
  2649. std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
  2650. GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
  2651. GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
  2652. GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
  2653. // There are only two ways we can permute the tree:
  2654. // (A op B) op C and A op (B op C)
  2655. // Within these forms, we can also permute A/B/C.
  2656. // Generate legal pair permutations of A/B/C.
  2657. std::vector<TreePatternNode*> ABVariants;
  2658. std::vector<TreePatternNode*> BAVariants;
  2659. std::vector<TreePatternNode*> ACVariants;
  2660. std::vector<TreePatternNode*> CAVariants;
  2661. std::vector<TreePatternNode*> BCVariants;
  2662. std::vector<TreePatternNode*> CBVariants;
  2663. CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
  2664. CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
  2665. CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
  2666. CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
  2667. CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
  2668. CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
  2669. // Combine those into the result: (x op x) op x
  2670. CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
  2671. CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
  2672. CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
  2673. CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
  2674. CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
  2675. CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
  2676. // Combine those into the result: x op (x op x)
  2677. CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
  2678. CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
  2679. CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
  2680. CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
  2681. CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
  2682. CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
  2683. return;
  2684. }
  2685. }
  2686. // Compute permutations of all children.
  2687. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2688. ChildVariants.resize(N->getNumChildren());
  2689. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2690. GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
  2691. // Build all permutations based on how the children were formed.
  2692. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
  2693. // If this node is commutative, consider the commuted order.
  2694. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
  2695. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  2696. assert((N->getNumChildren()==2 || isCommIntrinsic) &&
  2697. "Commutative but doesn't have 2 children!");
  2698. // Don't count children which are actually register references.
  2699. unsigned NC = 0;
  2700. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  2701. TreePatternNode *Child = N->getChild(i);
  2702. if (Child->isLeaf())
  2703. if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
  2704. Record *RR = DI->getDef();
  2705. if (RR->isSubClassOf("Register"))
  2706. continue;
  2707. }
  2708. NC++;
  2709. }
  2710. // Consider the commuted order.
  2711. if (isCommIntrinsic) {
  2712. // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
  2713. // operands are the commutative operands, and there might be more operands
  2714. // after those.
  2715. assert(NC >= 3 &&
  2716. "Commutative intrinsic should have at least 3 childrean!");
  2717. std::vector<std::vector<TreePatternNode*> > Variants;
  2718. Variants.push_back(ChildVariants[0]); // Intrinsic id.
  2719. Variants.push_back(ChildVariants[2]);
  2720. Variants.push_back(ChildVariants[1]);
  2721. for (unsigned i = 3; i != NC; ++i)
  2722. Variants.push_back(ChildVariants[i]);
  2723. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  2724. } else if (NC == 2)
  2725. CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
  2726. OutVariants, CDP, DepVars);
  2727. }
  2728. }
  2729. // GenerateVariants - Generate variants. For example, commutative patterns can
  2730. // match multiple ways. Add them to PatternsToMatch as well.
  2731. void CodeGenDAGPatterns::GenerateVariants() {
  2732. DEBUG(errs() << "Generating instruction variants.\n");
  2733. // Loop over all of the patterns we've collected, checking to see if we can
  2734. // generate variants of the instruction, through the exploitation of
  2735. // identities. This permits the target to provide aggressive matching without
  2736. // the .td file having to contain tons of variants of instructions.
  2737. //
  2738. // Note that this loop adds new patterns to the PatternsToMatch list, but we
  2739. // intentionally do not reconsider these. Any variants of added patterns have
  2740. // already been added.
  2741. //
  2742. for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
  2743. MultipleUseVarSet DepVars;
  2744. std::vector<TreePatternNode*> Variants;
  2745. FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
  2746. DEBUG(errs() << "Dependent/multiply used variables: ");
  2747. DEBUG(DumpDepVars(DepVars));
  2748. DEBUG(errs() << "\n");
  2749. GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
  2750. DepVars);
  2751. assert(!Variants.empty() && "Must create at least original variant!");
  2752. Variants.erase(Variants.begin()); // Remove the original pattern.
  2753. if (Variants.empty()) // No variants for this pattern.
  2754. continue;
  2755. DEBUG(errs() << "FOUND VARIANTS OF: ";
  2756. PatternsToMatch[i].getSrcPattern()->dump();
  2757. errs() << "\n");
  2758. for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
  2759. TreePatternNode *Variant = Variants[v];
  2760. DEBUG(errs() << " VAR#" << v << ": ";
  2761. Variant->dump();
  2762. errs() << "\n");
  2763. // Scan to see if an instruction or explicit pattern already matches this.
  2764. bool AlreadyExists = false;
  2765. for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
  2766. // Skip if the top level predicates do not match.
  2767. if (PatternsToMatch[i].getPredicates() !=
  2768. PatternsToMatch[p].getPredicates())
  2769. continue;
  2770. // Check to see if this variant already exists.
  2771. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
  2772. DepVars)) {
  2773. DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
  2774. AlreadyExists = true;
  2775. break;
  2776. }
  2777. }
  2778. // If we already have it, ignore the variant.
  2779. if (AlreadyExists) continue;
  2780. // Otherwise, add it to the list of patterns we have.
  2781. PatternsToMatch.
  2782. push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
  2783. PatternsToMatch[i].getPredicates(),
  2784. Variant, PatternsToMatch[i].getDstPattern(),
  2785. PatternsToMatch[i].getDstRegs(),
  2786. PatternsToMatch[i].getAddedComplexity(),
  2787. Record::getNewUID()));
  2788. }
  2789. DEBUG(errs() << "\n");
  2790. }
  2791. }