CodeGenDAGPatterns.cpp 138 KB

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