CodeGenDAGPatterns.cpp 169 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735
  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the CodeGenDAGPatterns class, which is used to read and
  10. // represent the patterns present in a .td file for instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenDAGPatterns.h"
  14. #include "llvm/ADT/BitVector.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/MapVector.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/TypeSize.h"
  26. #include "llvm/TableGen/Error.h"
  27. #include "llvm/TableGen/Record.h"
  28. #include <algorithm>
  29. #include <cstdio>
  30. #include <iterator>
  31. #include <set>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "dag-patterns"
  34. static inline bool isIntegerOrPtr(MVT VT) {
  35. return VT.isInteger() || VT == MVT::iPTR;
  36. }
  37. static inline bool isFloatingPoint(MVT VT) {
  38. return VT.isFloatingPoint();
  39. }
  40. static inline bool isVector(MVT VT) {
  41. return VT.isVector();
  42. }
  43. static inline bool isScalar(MVT VT) {
  44. return !VT.isVector();
  45. }
  46. template <typename Predicate>
  47. static bool berase_if(MachineValueTypeSet &S, Predicate P) {
  48. bool Erased = false;
  49. // It is ok to iterate over MachineValueTypeSet and remove elements from it
  50. // at the same time.
  51. for (MVT T : S) {
  52. if (!P(T))
  53. continue;
  54. Erased = true;
  55. S.erase(T);
  56. }
  57. return Erased;
  58. }
  59. // --- TypeSetByHwMode
  60. // This is a parameterized type-set class. For each mode there is a list
  61. // of types that are currently possible for a given tree node. Type
  62. // inference will apply to each mode separately.
  63. TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
  64. for (const ValueTypeByHwMode &VVT : VTList) {
  65. insert(VVT);
  66. AddrSpaces.push_back(VVT.PtrAddrSpace);
  67. }
  68. }
  69. bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
  70. for (const auto &I : *this) {
  71. if (I.second.size() > 1)
  72. return false;
  73. if (!AllowEmpty && I.second.empty())
  74. return false;
  75. }
  76. return true;
  77. }
  78. ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
  79. assert(isValueTypeByHwMode(true) &&
  80. "The type set has multiple types for at least one HW mode");
  81. ValueTypeByHwMode VVT;
  82. auto ASI = AddrSpaces.begin();
  83. for (const auto &I : *this) {
  84. MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
  85. VVT.getOrCreateTypeForMode(I.first, T);
  86. if (ASI != AddrSpaces.end())
  87. VVT.PtrAddrSpace = *ASI++;
  88. }
  89. return VVT;
  90. }
  91. bool TypeSetByHwMode::isPossible() const {
  92. for (const auto &I : *this)
  93. if (!I.second.empty())
  94. return true;
  95. return false;
  96. }
  97. bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
  98. bool Changed = false;
  99. bool ContainsDefault = false;
  100. MVT DT = MVT::Other;
  101. SmallDenseSet<unsigned, 4> Modes;
  102. for (const auto &P : VVT) {
  103. unsigned M = P.first;
  104. Modes.insert(M);
  105. // Make sure there exists a set for each specific mode from VVT.
  106. Changed |= getOrCreate(M).insert(P.second).second;
  107. // Cache VVT's default mode.
  108. if (DefaultMode == M) {
  109. ContainsDefault = true;
  110. DT = P.second;
  111. }
  112. }
  113. // If VVT has a default mode, add the corresponding type to all
  114. // modes in "this" that do not exist in VVT.
  115. if (ContainsDefault)
  116. for (auto &I : *this)
  117. if (!Modes.count(I.first))
  118. Changed |= I.second.insert(DT).second;
  119. return Changed;
  120. }
  121. // Constrain the type set to be the intersection with VTS.
  122. bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
  123. bool Changed = false;
  124. if (hasDefault()) {
  125. for (const auto &I : VTS) {
  126. unsigned M = I.first;
  127. if (M == DefaultMode || hasMode(M))
  128. continue;
  129. Map.insert({M, Map.at(DefaultMode)});
  130. Changed = true;
  131. }
  132. }
  133. for (auto &I : *this) {
  134. unsigned M = I.first;
  135. SetType &S = I.second;
  136. if (VTS.hasMode(M) || VTS.hasDefault()) {
  137. Changed |= intersect(I.second, VTS.get(M));
  138. } else if (!S.empty()) {
  139. S.clear();
  140. Changed = true;
  141. }
  142. }
  143. return Changed;
  144. }
  145. template <typename Predicate>
  146. bool TypeSetByHwMode::constrain(Predicate P) {
  147. bool Changed = false;
  148. for (auto &I : *this)
  149. Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
  150. return Changed;
  151. }
  152. template <typename Predicate>
  153. bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
  154. assert(empty());
  155. for (const auto &I : VTS) {
  156. SetType &S = getOrCreate(I.first);
  157. for (auto J : I.second)
  158. if (P(J))
  159. S.insert(J);
  160. }
  161. return !empty();
  162. }
  163. void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
  164. SmallVector<unsigned, 4> Modes;
  165. Modes.reserve(Map.size());
  166. for (const auto &I : *this)
  167. Modes.push_back(I.first);
  168. if (Modes.empty()) {
  169. OS << "{}";
  170. return;
  171. }
  172. array_pod_sort(Modes.begin(), Modes.end());
  173. OS << '{';
  174. for (unsigned M : Modes) {
  175. OS << ' ' << getModeName(M) << ':';
  176. writeToStream(get(M), OS);
  177. }
  178. OS << " }";
  179. }
  180. void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
  181. SmallVector<MVT, 4> Types(S.begin(), S.end());
  182. array_pod_sort(Types.begin(), Types.end());
  183. OS << '[';
  184. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  185. OS << ValueTypeByHwMode::getMVTName(Types[i]);
  186. if (i != e-1)
  187. OS << ' ';
  188. }
  189. OS << ']';
  190. }
  191. bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
  192. // The isSimple call is much quicker than hasDefault - check this first.
  193. bool IsSimple = isSimple();
  194. bool VTSIsSimple = VTS.isSimple();
  195. if (IsSimple && VTSIsSimple)
  196. return *begin() == *VTS.begin();
  197. // Speedup: We have a default if the set is simple.
  198. bool HaveDefault = IsSimple || hasDefault();
  199. bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
  200. if (HaveDefault != VTSHaveDefault)
  201. return false;
  202. SmallDenseSet<unsigned, 4> Modes;
  203. for (auto &I : *this)
  204. Modes.insert(I.first);
  205. for (const auto &I : VTS)
  206. Modes.insert(I.first);
  207. if (HaveDefault) {
  208. // Both sets have default mode.
  209. for (unsigned M : Modes) {
  210. if (get(M) != VTS.get(M))
  211. return false;
  212. }
  213. } else {
  214. // Neither set has default mode.
  215. for (unsigned M : Modes) {
  216. // If there is no default mode, an empty set is equivalent to not having
  217. // the corresponding mode.
  218. bool NoModeThis = !hasMode(M) || get(M).empty();
  219. bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
  220. if (NoModeThis != NoModeVTS)
  221. return false;
  222. if (!NoModeThis)
  223. if (get(M) != VTS.get(M))
  224. return false;
  225. }
  226. }
  227. return true;
  228. }
  229. namespace llvm {
  230. raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
  231. T.writeToStream(OS);
  232. return OS;
  233. }
  234. }
  235. LLVM_DUMP_METHOD
  236. void TypeSetByHwMode::dump() const {
  237. dbgs() << *this << '\n';
  238. }
  239. bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
  240. bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
  241. auto Int = [&In](MVT T) -> bool { return !In.count(T); };
  242. if (OutP == InP)
  243. return berase_if(Out, Int);
  244. // Compute the intersection of scalars separately to account for only
  245. // one set containing iPTR.
  246. // The intersection of iPTR with a set of integer scalar types that does not
  247. // include iPTR will result in the most specific scalar type:
  248. // - iPTR is more specific than any set with two elements or more
  249. // - iPTR is less specific than any single integer scalar type.
  250. // For example
  251. // { iPTR } * { i32 } -> { i32 }
  252. // { iPTR } * { i32 i64 } -> { iPTR }
  253. // and
  254. // { iPTR i32 } * { i32 } -> { i32 }
  255. // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
  256. // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
  257. // Compute the difference between the two sets in such a way that the
  258. // iPTR is in the set that is being subtracted. This is to see if there
  259. // are any extra scalars in the set without iPTR that are not in the
  260. // set containing iPTR. Then the iPTR could be considered a "wildcard"
  261. // matching these scalars. If there is only one such scalar, it would
  262. // replace the iPTR, if there are more, the iPTR would be retained.
  263. SetType Diff;
  264. if (InP) {
  265. Diff = Out;
  266. berase_if(Diff, [&In](MVT T) { return In.count(T); });
  267. // Pre-remove these elements and rely only on InP/OutP to determine
  268. // whether a change has been made.
  269. berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
  270. } else {
  271. Diff = In;
  272. berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
  273. Out.erase(MVT::iPTR);
  274. }
  275. // The actual intersection.
  276. bool Changed = berase_if(Out, Int);
  277. unsigned NumD = Diff.size();
  278. if (NumD == 0)
  279. return Changed;
  280. if (NumD == 1) {
  281. Out.insert(*Diff.begin());
  282. // This is a change only if Out was the one with iPTR (which is now
  283. // being replaced).
  284. Changed |= OutP;
  285. } else {
  286. // Multiple elements from Out are now replaced with iPTR.
  287. Out.insert(MVT::iPTR);
  288. Changed |= !OutP;
  289. }
  290. return Changed;
  291. }
  292. bool TypeSetByHwMode::validate() const {
  293. #ifndef NDEBUG
  294. if (empty())
  295. return true;
  296. bool AllEmpty = true;
  297. for (const auto &I : *this)
  298. AllEmpty &= I.second.empty();
  299. return !AllEmpty;
  300. #endif
  301. return true;
  302. }
  303. // --- TypeInfer
  304. bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
  305. const TypeSetByHwMode &In) {
  306. ValidateOnExit _1(Out, *this);
  307. In.validate();
  308. if (In.empty() || Out == In || TP.hasError())
  309. return false;
  310. if (Out.empty()) {
  311. Out = In;
  312. return true;
  313. }
  314. bool Changed = Out.constrain(In);
  315. if (Changed && Out.empty())
  316. TP.error("Type contradiction");
  317. return Changed;
  318. }
  319. bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
  320. ValidateOnExit _1(Out, *this);
  321. if (TP.hasError())
  322. return false;
  323. assert(!Out.empty() && "cannot pick from an empty set");
  324. bool Changed = false;
  325. for (auto &I : Out) {
  326. TypeSetByHwMode::SetType &S = I.second;
  327. if (S.size() <= 1)
  328. continue;
  329. MVT T = *S.begin(); // Pick the first element.
  330. S.clear();
  331. S.insert(T);
  332. Changed = true;
  333. }
  334. return Changed;
  335. }
  336. bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
  337. ValidateOnExit _1(Out, *this);
  338. if (TP.hasError())
  339. return false;
  340. if (!Out.empty())
  341. return Out.constrain(isIntegerOrPtr);
  342. return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
  343. }
  344. bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
  345. ValidateOnExit _1(Out, *this);
  346. if (TP.hasError())
  347. return false;
  348. if (!Out.empty())
  349. return Out.constrain(isFloatingPoint);
  350. return Out.assign_if(getLegalTypes(), isFloatingPoint);
  351. }
  352. bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
  353. ValidateOnExit _1(Out, *this);
  354. if (TP.hasError())
  355. return false;
  356. if (!Out.empty())
  357. return Out.constrain(isScalar);
  358. return Out.assign_if(getLegalTypes(), isScalar);
  359. }
  360. bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
  361. ValidateOnExit _1(Out, *this);
  362. if (TP.hasError())
  363. return false;
  364. if (!Out.empty())
  365. return Out.constrain(isVector);
  366. return Out.assign_if(getLegalTypes(), isVector);
  367. }
  368. bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
  369. ValidateOnExit _1(Out, *this);
  370. if (TP.hasError() || !Out.empty())
  371. return false;
  372. Out = getLegalTypes();
  373. return true;
  374. }
  375. template <typename Iter, typename Pred, typename Less>
  376. static Iter min_if(Iter B, Iter E, Pred P, Less L) {
  377. if (B == E)
  378. return E;
  379. Iter Min = E;
  380. for (Iter I = B; I != E; ++I) {
  381. if (!P(*I))
  382. continue;
  383. if (Min == E || L(*I, *Min))
  384. Min = I;
  385. }
  386. return Min;
  387. }
  388. template <typename Iter, typename Pred, typename Less>
  389. static Iter max_if(Iter B, Iter E, Pred P, Less L) {
  390. if (B == E)
  391. return E;
  392. Iter Max = E;
  393. for (Iter I = B; I != E; ++I) {
  394. if (!P(*I))
  395. continue;
  396. if (Max == E || L(*Max, *I))
  397. Max = I;
  398. }
  399. return Max;
  400. }
  401. /// Make sure that for each type in Small, there exists a larger type in Big.
  402. bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
  403. TypeSetByHwMode &Big) {
  404. ValidateOnExit _1(Small, *this), _2(Big, *this);
  405. if (TP.hasError())
  406. return false;
  407. bool Changed = false;
  408. if (Small.empty())
  409. Changed |= EnforceAny(Small);
  410. if (Big.empty())
  411. Changed |= EnforceAny(Big);
  412. assert(Small.hasDefault() && Big.hasDefault());
  413. std::vector<unsigned> Modes = union_modes(Small, Big);
  414. // 1. Only allow integer or floating point types and make sure that
  415. // both sides are both integer or both floating point.
  416. // 2. Make sure that either both sides have vector types, or neither
  417. // of them does.
  418. for (unsigned M : Modes) {
  419. TypeSetByHwMode::SetType &S = Small.get(M);
  420. TypeSetByHwMode::SetType &B = Big.get(M);
  421. if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
  422. auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
  423. Changed |= berase_if(S, NotInt);
  424. Changed |= berase_if(B, NotInt);
  425. } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
  426. auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
  427. Changed |= berase_if(S, NotFP);
  428. Changed |= berase_if(B, NotFP);
  429. } else if (S.empty() || B.empty()) {
  430. Changed = !S.empty() || !B.empty();
  431. S.clear();
  432. B.clear();
  433. } else {
  434. TP.error("Incompatible types");
  435. return Changed;
  436. }
  437. if (none_of(S, isVector) || none_of(B, isVector)) {
  438. Changed |= berase_if(S, isVector);
  439. Changed |= berase_if(B, isVector);
  440. }
  441. }
  442. auto LT = [](MVT A, MVT B) -> bool {
  443. // Always treat non-scalable MVTs as smaller than scalable MVTs for the
  444. // purposes of ordering.
  445. auto ASize = std::make_tuple(A.isScalableVector(), A.getScalarSizeInBits(),
  446. A.getSizeInBits().getKnownMinSize());
  447. auto BSize = std::make_tuple(B.isScalableVector(), B.getScalarSizeInBits(),
  448. B.getSizeInBits().getKnownMinSize());
  449. return ASize < BSize;
  450. };
  451. auto SameKindLE = [](MVT A, MVT B) -> bool {
  452. // This function is used when removing elements: when a vector is compared
  453. // to a non-vector or a scalable vector to any non-scalable MVT, it should
  454. // return false (to avoid removal).
  455. if (std::make_tuple(A.isVector(), A.isScalableVector()) !=
  456. std::make_tuple(B.isVector(), B.isScalableVector()))
  457. return false;
  458. return std::make_tuple(A.getScalarSizeInBits(),
  459. A.getSizeInBits().getKnownMinSize()) <=
  460. std::make_tuple(B.getScalarSizeInBits(),
  461. B.getSizeInBits().getKnownMinSize());
  462. };
  463. for (unsigned M : Modes) {
  464. TypeSetByHwMode::SetType &S = Small.get(M);
  465. TypeSetByHwMode::SetType &B = Big.get(M);
  466. // MinS = min scalar in Small, remove all scalars from Big that are
  467. // smaller-or-equal than MinS.
  468. auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
  469. if (MinS != S.end())
  470. Changed |= berase_if(B, std::bind(SameKindLE,
  471. std::placeholders::_1, *MinS));
  472. // MaxS = max scalar in Big, remove all scalars from Small that are
  473. // larger than MaxS.
  474. auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
  475. if (MaxS != B.end())
  476. Changed |= berase_if(S, std::bind(SameKindLE,
  477. *MaxS, std::placeholders::_1));
  478. // MinV = min vector in Small, remove all vectors from Big that are
  479. // smaller-or-equal than MinV.
  480. auto MinV = min_if(S.begin(), S.end(), isVector, LT);
  481. if (MinV != S.end())
  482. Changed |= berase_if(B, std::bind(SameKindLE,
  483. std::placeholders::_1, *MinV));
  484. // MaxV = max vector in Big, remove all vectors from Small that are
  485. // larger than MaxV.
  486. auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
  487. if (MaxV != B.end())
  488. Changed |= berase_if(S, std::bind(SameKindLE,
  489. *MaxV, std::placeholders::_1));
  490. }
  491. return Changed;
  492. }
  493. /// 1. Ensure that for each type T in Vec, T is a vector type, and that
  494. /// for each type U in Elem, U is a scalar type.
  495. /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
  496. /// type T in Vec, such that U is the element type of T.
  497. bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
  498. TypeSetByHwMode &Elem) {
  499. ValidateOnExit _1(Vec, *this), _2(Elem, *this);
  500. if (TP.hasError())
  501. return false;
  502. bool Changed = false;
  503. if (Vec.empty())
  504. Changed |= EnforceVector(Vec);
  505. if (Elem.empty())
  506. Changed |= EnforceScalar(Elem);
  507. for (unsigned M : union_modes(Vec, Elem)) {
  508. TypeSetByHwMode::SetType &V = Vec.get(M);
  509. TypeSetByHwMode::SetType &E = Elem.get(M);
  510. Changed |= berase_if(V, isScalar); // Scalar = !vector
  511. Changed |= berase_if(E, isVector); // Vector = !scalar
  512. assert(!V.empty() && !E.empty());
  513. SmallSet<MVT,4> VT, ST;
  514. // Collect element types from the "vector" set.
  515. for (MVT T : V)
  516. VT.insert(T.getVectorElementType());
  517. // Collect scalar types from the "element" set.
  518. for (MVT T : E)
  519. ST.insert(T);
  520. // Remove from V all (vector) types whose element type is not in S.
  521. Changed |= berase_if(V, [&ST](MVT T) -> bool {
  522. return !ST.count(T.getVectorElementType());
  523. });
  524. // Remove from E all (scalar) types, for which there is no corresponding
  525. // type in V.
  526. Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
  527. }
  528. return Changed;
  529. }
  530. bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
  531. const ValueTypeByHwMode &VVT) {
  532. TypeSetByHwMode Tmp(VVT);
  533. ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
  534. return EnforceVectorEltTypeIs(Vec, Tmp);
  535. }
  536. /// Ensure that for each type T in Sub, T is a vector type, and there
  537. /// exists a type U in Vec such that U is a vector type with the same
  538. /// element type as T and at least as many elements as T.
  539. bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
  540. TypeSetByHwMode &Sub) {
  541. ValidateOnExit _1(Vec, *this), _2(Sub, *this);
  542. if (TP.hasError())
  543. return false;
  544. /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
  545. auto IsSubVec = [](MVT B, MVT P) -> bool {
  546. if (!B.isVector() || !P.isVector())
  547. return false;
  548. // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
  549. // but until there are obvious use-cases for this, keep the
  550. // types separate.
  551. if (B.isScalableVector() != P.isScalableVector())
  552. return false;
  553. if (B.getVectorElementType() != P.getVectorElementType())
  554. return false;
  555. return B.getVectorNumElements() < P.getVectorNumElements();
  556. };
  557. /// Return true if S has no element (vector type) that T is a sub-vector of,
  558. /// i.e. has the same element type as T and more elements.
  559. auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
  560. for (auto I : S)
  561. if (IsSubVec(T, I))
  562. return false;
  563. return true;
  564. };
  565. /// Return true if S has no element (vector type) that T is a super-vector
  566. /// of, i.e. has the same element type as T and fewer elements.
  567. auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
  568. for (auto I : S)
  569. if (IsSubVec(I, T))
  570. return false;
  571. return true;
  572. };
  573. bool Changed = false;
  574. if (Vec.empty())
  575. Changed |= EnforceVector(Vec);
  576. if (Sub.empty())
  577. Changed |= EnforceVector(Sub);
  578. for (unsigned M : union_modes(Vec, Sub)) {
  579. TypeSetByHwMode::SetType &S = Sub.get(M);
  580. TypeSetByHwMode::SetType &V = Vec.get(M);
  581. Changed |= berase_if(S, isScalar);
  582. // Erase all types from S that are not sub-vectors of a type in V.
  583. Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
  584. // Erase all types from V that are not super-vectors of a type in S.
  585. Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
  586. }
  587. return Changed;
  588. }
  589. /// 1. Ensure that V has a scalar type iff W has a scalar type.
  590. /// 2. Ensure that for each vector type T in V, there exists a vector
  591. /// type U in W, such that T and U have the same number of elements.
  592. /// 3. Ensure that for each vector type U in W, there exists a vector
  593. /// type T in V, such that T and U have the same number of elements
  594. /// (reverse of 2).
  595. bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
  596. ValidateOnExit _1(V, *this), _2(W, *this);
  597. if (TP.hasError())
  598. return false;
  599. bool Changed = false;
  600. if (V.empty())
  601. Changed |= EnforceAny(V);
  602. if (W.empty())
  603. Changed |= EnforceAny(W);
  604. // An actual vector type cannot have 0 elements, so we can treat scalars
  605. // as zero-length vectors. This way both vectors and scalars can be
  606. // processed identically.
  607. auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
  608. return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
  609. };
  610. for (unsigned M : union_modes(V, W)) {
  611. TypeSetByHwMode::SetType &VS = V.get(M);
  612. TypeSetByHwMode::SetType &WS = W.get(M);
  613. SmallSet<unsigned,2> VN, WN;
  614. for (MVT T : VS)
  615. VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
  616. for (MVT T : WS)
  617. WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
  618. Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
  619. Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
  620. }
  621. return Changed;
  622. }
  623. /// 1. Ensure that for each type T in A, there exists a type U in B,
  624. /// such that T and U have equal size in bits.
  625. /// 2. Ensure that for each type U in B, there exists a type T in A
  626. /// such that T and U have equal size in bits (reverse of 1).
  627. bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
  628. ValidateOnExit _1(A, *this), _2(B, *this);
  629. if (TP.hasError())
  630. return false;
  631. bool Changed = false;
  632. if (A.empty())
  633. Changed |= EnforceAny(A);
  634. if (B.empty())
  635. Changed |= EnforceAny(B);
  636. auto NoSize = [](const SmallSet<TypeSize, 2> &Sizes, MVT T) -> bool {
  637. return !Sizes.count(T.getSizeInBits());
  638. };
  639. for (unsigned M : union_modes(A, B)) {
  640. TypeSetByHwMode::SetType &AS = A.get(M);
  641. TypeSetByHwMode::SetType &BS = B.get(M);
  642. SmallSet<TypeSize, 2> AN, BN;
  643. for (MVT T : AS)
  644. AN.insert(T.getSizeInBits());
  645. for (MVT T : BS)
  646. BN.insert(T.getSizeInBits());
  647. Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
  648. Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
  649. }
  650. return Changed;
  651. }
  652. void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
  653. ValidateOnExit _1(VTS, *this);
  654. const TypeSetByHwMode &Legal = getLegalTypes();
  655. assert(Legal.isDefaultOnly() && "Default-mode only expected");
  656. const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
  657. for (auto &I : VTS)
  658. expandOverloads(I.second, LegalTypes);
  659. }
  660. void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
  661. const TypeSetByHwMode::SetType &Legal) {
  662. std::set<MVT> Ovs;
  663. for (MVT T : Out) {
  664. if (!T.isOverloaded())
  665. continue;
  666. Ovs.insert(T);
  667. // MachineValueTypeSet allows iteration and erasing.
  668. Out.erase(T);
  669. }
  670. for (MVT Ov : Ovs) {
  671. switch (Ov.SimpleTy) {
  672. case MVT::iPTRAny:
  673. Out.insert(MVT::iPTR);
  674. return;
  675. case MVT::iAny:
  676. for (MVT T : MVT::integer_valuetypes())
  677. if (Legal.count(T))
  678. Out.insert(T);
  679. for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
  680. if (Legal.count(T))
  681. Out.insert(T);
  682. for (MVT T : MVT::integer_scalable_vector_valuetypes())
  683. if (Legal.count(T))
  684. Out.insert(T);
  685. return;
  686. case MVT::fAny:
  687. for (MVT T : MVT::fp_valuetypes())
  688. if (Legal.count(T))
  689. Out.insert(T);
  690. for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
  691. if (Legal.count(T))
  692. Out.insert(T);
  693. for (MVT T : MVT::fp_scalable_vector_valuetypes())
  694. if (Legal.count(T))
  695. Out.insert(T);
  696. return;
  697. case MVT::vAny:
  698. for (MVT T : MVT::vector_valuetypes())
  699. if (Legal.count(T))
  700. Out.insert(T);
  701. return;
  702. case MVT::Any:
  703. for (MVT T : MVT::all_valuetypes())
  704. if (Legal.count(T))
  705. Out.insert(T);
  706. return;
  707. default:
  708. break;
  709. }
  710. }
  711. }
  712. const TypeSetByHwMode &TypeInfer::getLegalTypes() {
  713. if (!LegalTypesCached) {
  714. TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
  715. // Stuff all types from all modes into the default mode.
  716. const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
  717. for (const auto &I : LTS)
  718. LegalTypes.insert(I.second);
  719. LegalTypesCached = true;
  720. }
  721. assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
  722. return LegalCache;
  723. }
  724. #ifndef NDEBUG
  725. TypeInfer::ValidateOnExit::~ValidateOnExit() {
  726. if (Infer.Validate && !VTS.validate()) {
  727. dbgs() << "Type set is empty for each HW mode:\n"
  728. "possible type contradiction in the pattern below "
  729. "(use -print-records with llvm-tblgen to see all "
  730. "expanded records).\n";
  731. Infer.TP.dump();
  732. llvm_unreachable(nullptr);
  733. }
  734. }
  735. #endif
  736. //===----------------------------------------------------------------------===//
  737. // ScopedName Implementation
  738. //===----------------------------------------------------------------------===//
  739. bool ScopedName::operator==(const ScopedName &o) const {
  740. return Scope == o.Scope && Identifier == o.Identifier;
  741. }
  742. bool ScopedName::operator!=(const ScopedName &o) const {
  743. return !(*this == o);
  744. }
  745. //===----------------------------------------------------------------------===//
  746. // TreePredicateFn Implementation
  747. //===----------------------------------------------------------------------===//
  748. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  749. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  750. assert(
  751. (!hasPredCode() || !hasImmCode()) &&
  752. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  753. }
  754. bool TreePredicateFn::hasPredCode() const {
  755. return isLoad() || isStore() || isAtomic() ||
  756. !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
  757. }
  758. std::string TreePredicateFn::getPredCode() const {
  759. std::string Code;
  760. if (!isLoad() && !isStore() && !isAtomic()) {
  761. Record *MemoryVT = getMemoryVT();
  762. if (MemoryVT)
  763. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  764. "MemoryVT requires IsLoad or IsStore");
  765. }
  766. if (!isLoad() && !isStore()) {
  767. if (isUnindexed())
  768. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  769. "IsUnindexed requires IsLoad or IsStore");
  770. Record *ScalarMemoryVT = getScalarMemoryVT();
  771. if (ScalarMemoryVT)
  772. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  773. "ScalarMemoryVT requires IsLoad or IsStore");
  774. }
  775. if (isLoad() + isStore() + isAtomic() > 1)
  776. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  777. "IsLoad, IsStore, and IsAtomic are mutually exclusive");
  778. if (isLoad()) {
  779. if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
  780. !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
  781. getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
  782. getMinAlignment() < 1)
  783. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  784. "IsLoad cannot be used by itself");
  785. } else {
  786. if (isNonExtLoad())
  787. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  788. "IsNonExtLoad requires IsLoad");
  789. if (isAnyExtLoad())
  790. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  791. "IsAnyExtLoad requires IsLoad");
  792. if (isSignExtLoad())
  793. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  794. "IsSignExtLoad requires IsLoad");
  795. if (isZeroExtLoad())
  796. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  797. "IsZeroExtLoad requires IsLoad");
  798. }
  799. if (isStore()) {
  800. if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
  801. getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
  802. getAddressSpaces() == nullptr && getMinAlignment() < 1)
  803. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  804. "IsStore cannot be used by itself");
  805. } else {
  806. if (isNonTruncStore())
  807. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  808. "IsNonTruncStore requires IsStore");
  809. if (isTruncStore())
  810. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  811. "IsTruncStore requires IsStore");
  812. }
  813. if (isAtomic()) {
  814. if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
  815. getAddressSpaces() == nullptr &&
  816. !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
  817. !isAtomicOrderingAcquireRelease() &&
  818. !isAtomicOrderingSequentiallyConsistent() &&
  819. !isAtomicOrderingAcquireOrStronger() &&
  820. !isAtomicOrderingReleaseOrStronger() &&
  821. !isAtomicOrderingWeakerThanAcquire() &&
  822. !isAtomicOrderingWeakerThanRelease())
  823. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  824. "IsAtomic cannot be used by itself");
  825. } else {
  826. if (isAtomicOrderingMonotonic())
  827. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  828. "IsAtomicOrderingMonotonic requires IsAtomic");
  829. if (isAtomicOrderingAcquire())
  830. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  831. "IsAtomicOrderingAcquire requires IsAtomic");
  832. if (isAtomicOrderingRelease())
  833. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  834. "IsAtomicOrderingRelease requires IsAtomic");
  835. if (isAtomicOrderingAcquireRelease())
  836. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  837. "IsAtomicOrderingAcquireRelease requires IsAtomic");
  838. if (isAtomicOrderingSequentiallyConsistent())
  839. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  840. "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
  841. if (isAtomicOrderingAcquireOrStronger())
  842. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  843. "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
  844. if (isAtomicOrderingReleaseOrStronger())
  845. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  846. "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
  847. if (isAtomicOrderingWeakerThanAcquire())
  848. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  849. "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
  850. }
  851. if (isLoad() || isStore() || isAtomic()) {
  852. if (ListInit *AddressSpaces = getAddressSpaces()) {
  853. Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
  854. " if (";
  855. bool First = true;
  856. for (Init *Val : AddressSpaces->getValues()) {
  857. if (First)
  858. First = false;
  859. else
  860. Code += " && ";
  861. IntInit *IntVal = dyn_cast<IntInit>(Val);
  862. if (!IntVal) {
  863. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  864. "AddressSpaces element must be integer");
  865. }
  866. Code += "AddrSpace != " + utostr(IntVal->getValue());
  867. }
  868. Code += ")\nreturn false;\n";
  869. }
  870. int64_t MinAlign = getMinAlignment();
  871. if (MinAlign > 0) {
  872. Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
  873. Code += utostr(MinAlign);
  874. Code += "))\nreturn false;\n";
  875. }
  876. Record *MemoryVT = getMemoryVT();
  877. if (MemoryVT)
  878. Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
  879. MemoryVT->getName() + ") return false;\n")
  880. .str();
  881. }
  882. if (isAtomic() && isAtomicOrderingMonotonic())
  883. Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
  884. "AtomicOrdering::Monotonic) return false;\n";
  885. if (isAtomic() && isAtomicOrderingAcquire())
  886. Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
  887. "AtomicOrdering::Acquire) return false;\n";
  888. if (isAtomic() && isAtomicOrderingRelease())
  889. Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
  890. "AtomicOrdering::Release) return false;\n";
  891. if (isAtomic() && isAtomicOrderingAcquireRelease())
  892. Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
  893. "AtomicOrdering::AcquireRelease) return false;\n";
  894. if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
  895. Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
  896. "AtomicOrdering::SequentiallyConsistent) return false;\n";
  897. if (isAtomic() && isAtomicOrderingAcquireOrStronger())
  898. Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
  899. "return false;\n";
  900. if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
  901. Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
  902. "return false;\n";
  903. if (isAtomic() && isAtomicOrderingReleaseOrStronger())
  904. Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
  905. "return false;\n";
  906. if (isAtomic() && isAtomicOrderingWeakerThanRelease())
  907. Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
  908. "return false;\n";
  909. if (isLoad() || isStore()) {
  910. StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
  911. if (isUnindexed())
  912. Code += ("if (cast<" + SDNodeName +
  913. ">(N)->getAddressingMode() != ISD::UNINDEXED) "
  914. "return false;\n")
  915. .str();
  916. if (isLoad()) {
  917. if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
  918. isZeroExtLoad()) > 1)
  919. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  920. "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
  921. "IsZeroExtLoad are mutually exclusive");
  922. if (isNonExtLoad())
  923. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
  924. "ISD::NON_EXTLOAD) return false;\n";
  925. if (isAnyExtLoad())
  926. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
  927. "return false;\n";
  928. if (isSignExtLoad())
  929. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
  930. "return false;\n";
  931. if (isZeroExtLoad())
  932. Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
  933. "return false;\n";
  934. } else {
  935. if ((isNonTruncStore() + isTruncStore()) > 1)
  936. PrintFatalError(
  937. getOrigPatFragRecord()->getRecord()->getLoc(),
  938. "IsNonTruncStore, and IsTruncStore are mutually exclusive");
  939. if (isNonTruncStore())
  940. Code +=
  941. " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
  942. if (isTruncStore())
  943. Code +=
  944. " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
  945. }
  946. Record *ScalarMemoryVT = getScalarMemoryVT();
  947. if (ScalarMemoryVT)
  948. Code += ("if (cast<" + SDNodeName +
  949. ">(N)->getMemoryVT().getScalarType() != MVT::" +
  950. ScalarMemoryVT->getName() + ") return false;\n")
  951. .str();
  952. }
  953. std::string PredicateCode =
  954. std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
  955. Code += PredicateCode;
  956. if (PredicateCode.empty() && !Code.empty())
  957. Code += "return true;\n";
  958. return Code;
  959. }
  960. bool TreePredicateFn::hasImmCode() const {
  961. return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
  962. }
  963. std::string TreePredicateFn::getImmCode() const {
  964. return std::string(
  965. PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
  966. }
  967. bool TreePredicateFn::immCodeUsesAPInt() const {
  968. return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
  969. }
  970. bool TreePredicateFn::immCodeUsesAPFloat() const {
  971. bool Unset;
  972. // The return value will be false when IsAPFloat is unset.
  973. return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
  974. Unset);
  975. }
  976. bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
  977. bool Value) const {
  978. bool Unset;
  979. bool Result =
  980. getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
  981. if (Unset)
  982. return false;
  983. return Result == Value;
  984. }
  985. bool TreePredicateFn::usesOperands() const {
  986. return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
  987. }
  988. bool TreePredicateFn::isLoad() const {
  989. return isPredefinedPredicateEqualTo("IsLoad", true);
  990. }
  991. bool TreePredicateFn::isStore() const {
  992. return isPredefinedPredicateEqualTo("IsStore", true);
  993. }
  994. bool TreePredicateFn::isAtomic() const {
  995. return isPredefinedPredicateEqualTo("IsAtomic", true);
  996. }
  997. bool TreePredicateFn::isUnindexed() const {
  998. return isPredefinedPredicateEqualTo("IsUnindexed", true);
  999. }
  1000. bool TreePredicateFn::isNonExtLoad() const {
  1001. return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
  1002. }
  1003. bool TreePredicateFn::isAnyExtLoad() const {
  1004. return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
  1005. }
  1006. bool TreePredicateFn::isSignExtLoad() const {
  1007. return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
  1008. }
  1009. bool TreePredicateFn::isZeroExtLoad() const {
  1010. return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
  1011. }
  1012. bool TreePredicateFn::isNonTruncStore() const {
  1013. return isPredefinedPredicateEqualTo("IsTruncStore", false);
  1014. }
  1015. bool TreePredicateFn::isTruncStore() const {
  1016. return isPredefinedPredicateEqualTo("IsTruncStore", true);
  1017. }
  1018. bool TreePredicateFn::isAtomicOrderingMonotonic() const {
  1019. return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
  1020. }
  1021. bool TreePredicateFn::isAtomicOrderingAcquire() const {
  1022. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
  1023. }
  1024. bool TreePredicateFn::isAtomicOrderingRelease() const {
  1025. return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
  1026. }
  1027. bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
  1028. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
  1029. }
  1030. bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
  1031. return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
  1032. true);
  1033. }
  1034. bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
  1035. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
  1036. }
  1037. bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
  1038. return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
  1039. }
  1040. bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
  1041. return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
  1042. }
  1043. bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
  1044. return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
  1045. }
  1046. Record *TreePredicateFn::getMemoryVT() const {
  1047. Record *R = getOrigPatFragRecord()->getRecord();
  1048. if (R->isValueUnset("MemoryVT"))
  1049. return nullptr;
  1050. return R->getValueAsDef("MemoryVT");
  1051. }
  1052. ListInit *TreePredicateFn::getAddressSpaces() const {
  1053. Record *R = getOrigPatFragRecord()->getRecord();
  1054. if (R->isValueUnset("AddressSpaces"))
  1055. return nullptr;
  1056. return R->getValueAsListInit("AddressSpaces");
  1057. }
  1058. int64_t TreePredicateFn::getMinAlignment() const {
  1059. Record *R = getOrigPatFragRecord()->getRecord();
  1060. if (R->isValueUnset("MinAlignment"))
  1061. return 0;
  1062. return R->getValueAsInt("MinAlignment");
  1063. }
  1064. Record *TreePredicateFn::getScalarMemoryVT() const {
  1065. Record *R = getOrigPatFragRecord()->getRecord();
  1066. if (R->isValueUnset("ScalarMemoryVT"))
  1067. return nullptr;
  1068. return R->getValueAsDef("ScalarMemoryVT");
  1069. }
  1070. bool TreePredicateFn::hasGISelPredicateCode() const {
  1071. return !PatFragRec->getRecord()
  1072. ->getValueAsString("GISelPredicateCode")
  1073. .empty();
  1074. }
  1075. std::string TreePredicateFn::getGISelPredicateCode() const {
  1076. return std::string(
  1077. PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
  1078. }
  1079. StringRef TreePredicateFn::getImmType() const {
  1080. if (immCodeUsesAPInt())
  1081. return "const APInt &";
  1082. if (immCodeUsesAPFloat())
  1083. return "const APFloat &";
  1084. return "int64_t";
  1085. }
  1086. StringRef TreePredicateFn::getImmTypeIdentifier() const {
  1087. if (immCodeUsesAPInt())
  1088. return "APInt";
  1089. else if (immCodeUsesAPFloat())
  1090. return "APFloat";
  1091. return "I64";
  1092. }
  1093. /// isAlwaysTrue - Return true if this is a noop predicate.
  1094. bool TreePredicateFn::isAlwaysTrue() const {
  1095. return !hasPredCode() && !hasImmCode();
  1096. }
  1097. /// Return the name to use in the generated code to reference this, this is
  1098. /// "Predicate_foo" if from a pattern fragment "foo".
  1099. std::string TreePredicateFn::getFnName() const {
  1100. return "Predicate_" + PatFragRec->getRecord()->getName().str();
  1101. }
  1102. /// getCodeToRunOnSDNode - Return the code for the function body that
  1103. /// evaluates this predicate. The argument is expected to be in "Node",
  1104. /// not N. This handles casting and conversion to a concrete node type as
  1105. /// appropriate.
  1106. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  1107. // Handle immediate predicates first.
  1108. std::string ImmCode = getImmCode();
  1109. if (!ImmCode.empty()) {
  1110. if (isLoad())
  1111. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1112. "IsLoad cannot be used with ImmLeaf or its subclasses");
  1113. if (isStore())
  1114. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1115. "IsStore cannot be used with ImmLeaf or its subclasses");
  1116. if (isUnindexed())
  1117. PrintFatalError(
  1118. getOrigPatFragRecord()->getRecord()->getLoc(),
  1119. "IsUnindexed cannot be used with ImmLeaf or its subclasses");
  1120. if (isNonExtLoad())
  1121. PrintFatalError(
  1122. getOrigPatFragRecord()->getRecord()->getLoc(),
  1123. "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
  1124. if (isAnyExtLoad())
  1125. PrintFatalError(
  1126. getOrigPatFragRecord()->getRecord()->getLoc(),
  1127. "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
  1128. if (isSignExtLoad())
  1129. PrintFatalError(
  1130. getOrigPatFragRecord()->getRecord()->getLoc(),
  1131. "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
  1132. if (isZeroExtLoad())
  1133. PrintFatalError(
  1134. getOrigPatFragRecord()->getRecord()->getLoc(),
  1135. "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
  1136. if (isNonTruncStore())
  1137. PrintFatalError(
  1138. getOrigPatFragRecord()->getRecord()->getLoc(),
  1139. "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
  1140. if (isTruncStore())
  1141. PrintFatalError(
  1142. getOrigPatFragRecord()->getRecord()->getLoc(),
  1143. "IsTruncStore cannot be used with ImmLeaf or its subclasses");
  1144. if (getMemoryVT())
  1145. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1146. "MemoryVT cannot be used with ImmLeaf or its subclasses");
  1147. if (getScalarMemoryVT())
  1148. PrintFatalError(
  1149. getOrigPatFragRecord()->getRecord()->getLoc(),
  1150. "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
  1151. std::string Result = (" " + getImmType() + " Imm = ").str();
  1152. if (immCodeUsesAPFloat())
  1153. Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
  1154. else if (immCodeUsesAPInt())
  1155. Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
  1156. else
  1157. Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
  1158. return Result + ImmCode;
  1159. }
  1160. // Handle arbitrary node predicates.
  1161. assert(hasPredCode() && "Don't have any predicate code!");
  1162. // If this is using PatFrags, there are multiple trees to search. They should
  1163. // all have the same class. FIXME: Is there a way to find a common
  1164. // superclass?
  1165. StringRef ClassName;
  1166. for (const auto &Tree : PatFragRec->getTrees()) {
  1167. StringRef TreeClassName;
  1168. if (Tree->isLeaf())
  1169. TreeClassName = "SDNode";
  1170. else {
  1171. Record *Op = Tree->getOperator();
  1172. const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
  1173. TreeClassName = Info.getSDClassName();
  1174. }
  1175. if (ClassName.empty())
  1176. ClassName = TreeClassName;
  1177. else if (ClassName != TreeClassName) {
  1178. PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
  1179. "PatFrags trees do not have consistent class");
  1180. }
  1181. }
  1182. std::string Result;
  1183. if (ClassName == "SDNode")
  1184. Result = " SDNode *N = Node;\n";
  1185. else
  1186. Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
  1187. return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
  1188. }
  1189. //===----------------------------------------------------------------------===//
  1190. // PatternToMatch implementation
  1191. //
  1192. static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
  1193. if (!P->isLeaf())
  1194. return false;
  1195. DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
  1196. if (!DI)
  1197. return false;
  1198. Record *R = DI->getDef();
  1199. return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
  1200. }
  1201. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  1202. /// patterns before small ones. This is used to determine the size of a
  1203. /// pattern.
  1204. static unsigned getPatternSize(const TreePatternNode *P,
  1205. const CodeGenDAGPatterns &CGP) {
  1206. unsigned Size = 3; // The node itself.
  1207. // If the root node is a ConstantSDNode, increases its size.
  1208. // e.g. (set R32:$dst, 0).
  1209. if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
  1210. Size += 2;
  1211. if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
  1212. Size += AM->getComplexity();
  1213. // We don't want to count any children twice, so return early.
  1214. return Size;
  1215. }
  1216. // If this node has some predicate function that must match, it adds to the
  1217. // complexity of this node.
  1218. if (!P->getPredicateCalls().empty())
  1219. ++Size;
  1220. // Count children in the count if they are also nodes.
  1221. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  1222. const TreePatternNode *Child = P->getChild(i);
  1223. if (!Child->isLeaf() && Child->getNumTypes()) {
  1224. const TypeSetByHwMode &T0 = Child->getExtType(0);
  1225. // At this point, all variable type sets should be simple, i.e. only
  1226. // have a default mode.
  1227. if (T0.getMachineValueType() != MVT::Other) {
  1228. Size += getPatternSize(Child, CGP);
  1229. continue;
  1230. }
  1231. }
  1232. if (Child->isLeaf()) {
  1233. if (isa<IntInit>(Child->getLeafValue()))
  1234. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  1235. else if (Child->getComplexPatternInfo(CGP))
  1236. Size += getPatternSize(Child, CGP);
  1237. else if (isImmAllOnesAllZerosMatch(Child))
  1238. Size += 4; // Matches a build_vector(+3) and a predicate (+1).
  1239. else if (!Child->getPredicateCalls().empty())
  1240. ++Size;
  1241. }
  1242. }
  1243. return Size;
  1244. }
  1245. /// Compute the complexity metric for the input pattern. This roughly
  1246. /// corresponds to the number of nodes that are covered.
  1247. int PatternToMatch::
  1248. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  1249. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  1250. }
  1251. /// getPredicateCheck - Return a single string containing all of this
  1252. /// pattern's predicates concatenated with "&&" operators.
  1253. ///
  1254. std::string PatternToMatch::getPredicateCheck() const {
  1255. SmallVector<const Predicate*,4> PredList;
  1256. for (const Predicate &P : Predicates) {
  1257. if (!P.getCondString().empty())
  1258. PredList.push_back(&P);
  1259. }
  1260. llvm::sort(PredList, deref<std::less<>>());
  1261. std::string Check;
  1262. for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
  1263. if (i != 0)
  1264. Check += " && ";
  1265. Check += '(' + PredList[i]->getCondString() + ')';
  1266. }
  1267. return Check;
  1268. }
  1269. //===----------------------------------------------------------------------===//
  1270. // SDTypeConstraint implementation
  1271. //
  1272. SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
  1273. OperandNo = R->getValueAsInt("OperandNum");
  1274. if (R->isSubClassOf("SDTCisVT")) {
  1275. ConstraintType = SDTCisVT;
  1276. VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
  1277. for (const auto &P : VVT)
  1278. if (P.second == MVT::isVoid)
  1279. PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  1280. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  1281. ConstraintType = SDTCisPtrTy;
  1282. } else if (R->isSubClassOf("SDTCisInt")) {
  1283. ConstraintType = SDTCisInt;
  1284. } else if (R->isSubClassOf("SDTCisFP")) {
  1285. ConstraintType = SDTCisFP;
  1286. } else if (R->isSubClassOf("SDTCisVec")) {
  1287. ConstraintType = SDTCisVec;
  1288. } else if (R->isSubClassOf("SDTCisSameAs")) {
  1289. ConstraintType = SDTCisSameAs;
  1290. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  1291. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  1292. ConstraintType = SDTCisVTSmallerThanOp;
  1293. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  1294. R->getValueAsInt("OtherOperandNum");
  1295. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  1296. ConstraintType = SDTCisOpSmallerThanOp;
  1297. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  1298. R->getValueAsInt("BigOperandNum");
  1299. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  1300. ConstraintType = SDTCisEltOfVec;
  1301. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  1302. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  1303. ConstraintType = SDTCisSubVecOfVec;
  1304. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  1305. R->getValueAsInt("OtherOpNum");
  1306. } else if (R->isSubClassOf("SDTCVecEltisVT")) {
  1307. ConstraintType = SDTCVecEltisVT;
  1308. VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
  1309. for (const auto &P : VVT) {
  1310. MVT T = P.second;
  1311. if (T.isVector())
  1312. PrintFatalError(R->getLoc(),
  1313. "Cannot use vector type as SDTCVecEltisVT");
  1314. if (!T.isInteger() && !T.isFloatingPoint())
  1315. PrintFatalError(R->getLoc(), "Must use integer or floating point type "
  1316. "as SDTCVecEltisVT");
  1317. }
  1318. } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
  1319. ConstraintType = SDTCisSameNumEltsAs;
  1320. x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
  1321. R->getValueAsInt("OtherOperandNum");
  1322. } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
  1323. ConstraintType = SDTCisSameSizeAs;
  1324. x.SDTCisSameSizeAs_Info.OtherOperandNum =
  1325. R->getValueAsInt("OtherOperandNum");
  1326. } else {
  1327. PrintFatalError(R->getLoc(),
  1328. "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
  1329. }
  1330. }
  1331. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  1332. /// N, and the result number in ResNo.
  1333. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  1334. const SDNodeInfo &NodeInfo,
  1335. unsigned &ResNo) {
  1336. unsigned NumResults = NodeInfo.getNumResults();
  1337. if (OpNo < NumResults) {
  1338. ResNo = OpNo;
  1339. return N;
  1340. }
  1341. OpNo -= NumResults;
  1342. if (OpNo >= N->getNumChildren()) {
  1343. std::string S;
  1344. raw_string_ostream OS(S);
  1345. OS << "Invalid operand number in type constraint "
  1346. << (OpNo+NumResults) << " ";
  1347. N->print(OS);
  1348. PrintFatalError(OS.str());
  1349. }
  1350. return N->getChild(OpNo);
  1351. }
  1352. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  1353. /// constraint to the nodes operands. This returns true if it makes a
  1354. /// change, false otherwise. If a type contradiction is found, flag an error.
  1355. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  1356. const SDNodeInfo &NodeInfo,
  1357. TreePattern &TP) const {
  1358. if (TP.hasError())
  1359. return false;
  1360. unsigned ResNo = 0; // The result number being referenced.
  1361. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  1362. TypeInfer &TI = TP.getInfer();
  1363. switch (ConstraintType) {
  1364. case SDTCisVT:
  1365. // Operand must be a particular type.
  1366. return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
  1367. case SDTCisPtrTy:
  1368. // Operand must be same as target pointer type.
  1369. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  1370. case SDTCisInt:
  1371. // Require it to be one of the legal integer VTs.
  1372. return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
  1373. case SDTCisFP:
  1374. // Require it to be one of the legal fp VTs.
  1375. return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
  1376. case SDTCisVec:
  1377. // Require it to be one of the legal vector VTs.
  1378. return TI.EnforceVector(NodeToApply->getExtType(ResNo));
  1379. case SDTCisSameAs: {
  1380. unsigned OResNo = 0;
  1381. TreePatternNode *OtherNode =
  1382. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  1383. return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
  1384. OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
  1385. }
  1386. case SDTCisVTSmallerThanOp: {
  1387. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  1388. // have an integer type that is smaller than the VT.
  1389. if (!NodeToApply->isLeaf() ||
  1390. !isa<DefInit>(NodeToApply->getLeafValue()) ||
  1391. !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
  1392. ->isSubClassOf("ValueType")) {
  1393. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  1394. return false;
  1395. }
  1396. DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
  1397. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1398. auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
  1399. TypeSetByHwMode TypeListTmp(VVT);
  1400. unsigned OResNo = 0;
  1401. TreePatternNode *OtherNode =
  1402. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  1403. OResNo);
  1404. return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
  1405. }
  1406. case SDTCisOpSmallerThanOp: {
  1407. unsigned BResNo = 0;
  1408. TreePatternNode *BigOperand =
  1409. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  1410. BResNo);
  1411. return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
  1412. BigOperand->getExtType(BResNo));
  1413. }
  1414. case SDTCisEltOfVec: {
  1415. unsigned VResNo = 0;
  1416. TreePatternNode *VecOperand =
  1417. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  1418. VResNo);
  1419. // Filter vector types out of VecOperand that don't have the right element
  1420. // type.
  1421. return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
  1422. NodeToApply->getExtType(ResNo));
  1423. }
  1424. case SDTCisSubVecOfVec: {
  1425. unsigned VResNo = 0;
  1426. TreePatternNode *BigVecOperand =
  1427. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  1428. VResNo);
  1429. // Filter vector types out of BigVecOperand that don't have the
  1430. // right subvector type.
  1431. return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
  1432. NodeToApply->getExtType(ResNo));
  1433. }
  1434. case SDTCVecEltisVT: {
  1435. return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
  1436. }
  1437. case SDTCisSameNumEltsAs: {
  1438. unsigned OResNo = 0;
  1439. TreePatternNode *OtherNode =
  1440. getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
  1441. N, NodeInfo, OResNo);
  1442. return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
  1443. NodeToApply->getExtType(ResNo));
  1444. }
  1445. case SDTCisSameSizeAs: {
  1446. unsigned OResNo = 0;
  1447. TreePatternNode *OtherNode =
  1448. getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
  1449. N, NodeInfo, OResNo);
  1450. return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
  1451. NodeToApply->getExtType(ResNo));
  1452. }
  1453. }
  1454. llvm_unreachable("Invalid ConstraintType!");
  1455. }
  1456. // Update the node type to match an instruction operand or result as specified
  1457. // in the ins or outs lists on the instruction definition. Return true if the
  1458. // type was actually changed.
  1459. bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
  1460. Record *Operand,
  1461. TreePattern &TP) {
  1462. // The 'unknown' operand indicates that types should be inferred from the
  1463. // context.
  1464. if (Operand->isSubClassOf("unknown_class"))
  1465. return false;
  1466. // The Operand class specifies a type directly.
  1467. if (Operand->isSubClassOf("Operand")) {
  1468. Record *R = Operand->getValueAsDef("Type");
  1469. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1470. return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
  1471. }
  1472. // PointerLikeRegClass has a type that is determined at runtime.
  1473. if (Operand->isSubClassOf("PointerLikeRegClass"))
  1474. return UpdateNodeType(ResNo, MVT::iPTR, TP);
  1475. // Both RegisterClass and RegisterOperand operands derive their types from a
  1476. // register class def.
  1477. Record *RC = nullptr;
  1478. if (Operand->isSubClassOf("RegisterClass"))
  1479. RC = Operand;
  1480. else if (Operand->isSubClassOf("RegisterOperand"))
  1481. RC = Operand->getValueAsDef("RegClass");
  1482. assert(RC && "Unknown operand type");
  1483. CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
  1484. return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
  1485. }
  1486. bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
  1487. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1488. if (!TP.getInfer().isConcrete(Types[i], true))
  1489. return true;
  1490. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1491. if (getChild(i)->ContainsUnresolvedType(TP))
  1492. return true;
  1493. return false;
  1494. }
  1495. bool TreePatternNode::hasProperTypeByHwMode() const {
  1496. for (const TypeSetByHwMode &S : Types)
  1497. if (!S.isDefaultOnly())
  1498. return true;
  1499. for (const TreePatternNodePtr &C : Children)
  1500. if (C->hasProperTypeByHwMode())
  1501. return true;
  1502. return false;
  1503. }
  1504. bool TreePatternNode::hasPossibleType() const {
  1505. for (const TypeSetByHwMode &S : Types)
  1506. if (!S.isPossible())
  1507. return false;
  1508. for (const TreePatternNodePtr &C : Children)
  1509. if (!C->hasPossibleType())
  1510. return false;
  1511. return true;
  1512. }
  1513. bool TreePatternNode::setDefaultMode(unsigned Mode) {
  1514. for (TypeSetByHwMode &S : Types) {
  1515. S.makeSimple(Mode);
  1516. // Check if the selected mode had a type conflict.
  1517. if (S.get(DefaultMode).empty())
  1518. return false;
  1519. }
  1520. for (const TreePatternNodePtr &C : Children)
  1521. if (!C->setDefaultMode(Mode))
  1522. return false;
  1523. return true;
  1524. }
  1525. //===----------------------------------------------------------------------===//
  1526. // SDNodeInfo implementation
  1527. //
  1528. SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
  1529. EnumName = R->getValueAsString("Opcode");
  1530. SDClassName = R->getValueAsString("SDClass");
  1531. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  1532. NumResults = TypeProfile->getValueAsInt("NumResults");
  1533. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  1534. // Parse the properties.
  1535. Properties = parseSDPatternOperatorProperties(R);
  1536. // Parse the type constraints.
  1537. std::vector<Record*> ConstraintList =
  1538. TypeProfile->getValueAsListOfDefs("Constraints");
  1539. for (Record *R : ConstraintList)
  1540. TypeConstraints.emplace_back(R, CGH);
  1541. }
  1542. /// getKnownType - If the type constraints on this node imply a fixed type
  1543. /// (e.g. all stores return void, etc), then return it as an
  1544. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  1545. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  1546. unsigned NumResults = getNumResults();
  1547. assert(NumResults <= 1 &&
  1548. "We only work with nodes with zero or one result so far!");
  1549. assert(ResNo == 0 && "Only handles single result nodes so far");
  1550. for (const SDTypeConstraint &Constraint : TypeConstraints) {
  1551. // Make sure that this applies to the correct node result.
  1552. if (Constraint.OperandNo >= NumResults) // FIXME: need value #
  1553. continue;
  1554. switch (Constraint.ConstraintType) {
  1555. default: break;
  1556. case SDTypeConstraint::SDTCisVT:
  1557. if (Constraint.VVT.isSimple())
  1558. return Constraint.VVT.getSimple().SimpleTy;
  1559. break;
  1560. case SDTypeConstraint::SDTCisPtrTy:
  1561. return MVT::iPTR;
  1562. }
  1563. }
  1564. return MVT::Other;
  1565. }
  1566. //===----------------------------------------------------------------------===//
  1567. // TreePatternNode implementation
  1568. //
  1569. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  1570. if (Operator->getName() == "set" ||
  1571. Operator->getName() == "implicit")
  1572. return 0; // All return nothing.
  1573. if (Operator->isSubClassOf("Intrinsic"))
  1574. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  1575. if (Operator->isSubClassOf("SDNode"))
  1576. return CDP.getSDNodeInfo(Operator).getNumResults();
  1577. if (Operator->isSubClassOf("PatFrags")) {
  1578. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  1579. // the forward reference case where one pattern fragment references another
  1580. // before it is processed.
  1581. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
  1582. // The number of results of a fragment with alternative records is the
  1583. // maximum number of results across all alternatives.
  1584. unsigned NumResults = 0;
  1585. for (auto T : PFRec->getTrees())
  1586. NumResults = std::max(NumResults, T->getNumTypes());
  1587. return NumResults;
  1588. }
  1589. ListInit *LI = Operator->getValueAsListInit("Fragments");
  1590. assert(LI && "Invalid Fragment");
  1591. unsigned NumResults = 0;
  1592. for (Init *I : LI->getValues()) {
  1593. Record *Op = nullptr;
  1594. if (DagInit *Dag = dyn_cast<DagInit>(I))
  1595. if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
  1596. Op = DI->getDef();
  1597. assert(Op && "Invalid Fragment");
  1598. NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
  1599. }
  1600. return NumResults;
  1601. }
  1602. if (Operator->isSubClassOf("Instruction")) {
  1603. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  1604. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
  1605. // Subtract any defaulted outputs.
  1606. for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
  1607. Record *OperandNode = InstInfo.Operands[i].Rec;
  1608. if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
  1609. !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
  1610. --NumDefsToAdd;
  1611. }
  1612. // Add on one implicit def if it has a resolvable type.
  1613. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  1614. ++NumDefsToAdd;
  1615. return NumDefsToAdd;
  1616. }
  1617. if (Operator->isSubClassOf("SDNodeXForm"))
  1618. return 1; // FIXME: Generalize SDNodeXForm
  1619. if (Operator->isSubClassOf("ValueType"))
  1620. return 1; // A type-cast of one result.
  1621. if (Operator->isSubClassOf("ComplexPattern"))
  1622. return 1;
  1623. errs() << *Operator;
  1624. PrintFatalError("Unhandled node in GetNumNodeResults");
  1625. }
  1626. void TreePatternNode::print(raw_ostream &OS) const {
  1627. if (isLeaf())
  1628. OS << *getLeafValue();
  1629. else
  1630. OS << '(' << getOperator()->getName();
  1631. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  1632. OS << ':';
  1633. getExtType(i).writeToStream(OS);
  1634. }
  1635. if (!isLeaf()) {
  1636. if (getNumChildren() != 0) {
  1637. OS << " ";
  1638. getChild(0)->print(OS);
  1639. for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
  1640. OS << ", ";
  1641. getChild(i)->print(OS);
  1642. }
  1643. }
  1644. OS << ")";
  1645. }
  1646. for (const TreePredicateCall &Pred : PredicateCalls) {
  1647. OS << "<<P:";
  1648. if (Pred.Scope)
  1649. OS << Pred.Scope << ":";
  1650. OS << Pred.Fn.getFnName() << ">>";
  1651. }
  1652. if (TransformFn)
  1653. OS << "<<X:" << TransformFn->getName() << ">>";
  1654. if (!getName().empty())
  1655. OS << ":$" << getName();
  1656. for (const ScopedName &Name : NamesAsPredicateArg)
  1657. OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
  1658. }
  1659. void TreePatternNode::dump() const {
  1660. print(errs());
  1661. }
  1662. /// isIsomorphicTo - Return true if this node is recursively
  1663. /// isomorphic to the specified node. For this comparison, the node's
  1664. /// entire state is considered. The assigned name is ignored, since
  1665. /// nodes with differing names are considered isomorphic. However, if
  1666. /// the assigned name is present in the dependent variable set, then
  1667. /// the assigned name is considered significant and the node is
  1668. /// isomorphic if the names match.
  1669. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  1670. const MultipleUseVarSet &DepVars) const {
  1671. if (N == this) return true;
  1672. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  1673. getPredicateCalls() != N->getPredicateCalls() ||
  1674. getTransformFn() != N->getTransformFn())
  1675. return false;
  1676. if (isLeaf()) {
  1677. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1678. if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
  1679. return ((DI->getDef() == NDI->getDef())
  1680. && (DepVars.find(getName()) == DepVars.end()
  1681. || getName() == N->getName()));
  1682. }
  1683. }
  1684. return getLeafValue() == N->getLeafValue();
  1685. }
  1686. if (N->getOperator() != getOperator() ||
  1687. N->getNumChildren() != getNumChildren()) return false;
  1688. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1689. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  1690. return false;
  1691. return true;
  1692. }
  1693. /// clone - Make a copy of this tree and all of its children.
  1694. ///
  1695. TreePatternNodePtr TreePatternNode::clone() const {
  1696. TreePatternNodePtr New;
  1697. if (isLeaf()) {
  1698. New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
  1699. } else {
  1700. std::vector<TreePatternNodePtr> CChildren;
  1701. CChildren.reserve(Children.size());
  1702. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1703. CChildren.push_back(getChild(i)->clone());
  1704. New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
  1705. getNumTypes());
  1706. }
  1707. New->setName(getName());
  1708. New->setNamesAsPredicateArg(getNamesAsPredicateArg());
  1709. New->Types = Types;
  1710. New->setPredicateCalls(getPredicateCalls());
  1711. New->setTransformFn(getTransformFn());
  1712. return New;
  1713. }
  1714. /// RemoveAllTypes - Recursively strip all the types of this tree.
  1715. void TreePatternNode::RemoveAllTypes() {
  1716. // Reset to unknown type.
  1717. std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
  1718. if (isLeaf()) return;
  1719. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1720. getChild(i)->RemoveAllTypes();
  1721. }
  1722. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  1723. /// with actual values specified by ArgMap.
  1724. void TreePatternNode::SubstituteFormalArguments(
  1725. std::map<std::string, TreePatternNodePtr> &ArgMap) {
  1726. if (isLeaf()) return;
  1727. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1728. TreePatternNode *Child = getChild(i);
  1729. if (Child->isLeaf()) {
  1730. Init *Val = Child->getLeafValue();
  1731. // Note that, when substituting into an output pattern, Val might be an
  1732. // UnsetInit.
  1733. if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
  1734. cast<DefInit>(Val)->getDef()->getName() == "node")) {
  1735. // We found a use of a formal argument, replace it with its value.
  1736. TreePatternNodePtr NewChild = ArgMap[Child->getName()];
  1737. assert(NewChild && "Couldn't find formal argument!");
  1738. assert((Child->getPredicateCalls().empty() ||
  1739. NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
  1740. "Non-empty child predicate clobbered!");
  1741. setChild(i, std::move(NewChild));
  1742. }
  1743. } else {
  1744. getChild(i)->SubstituteFormalArguments(ArgMap);
  1745. }
  1746. }
  1747. }
  1748. /// InlinePatternFragments - If this pattern refers to any pattern
  1749. /// fragments, return the set of inlined versions (this can be more than
  1750. /// one if a PatFrags record has multiple alternatives).
  1751. void TreePatternNode::InlinePatternFragments(
  1752. TreePatternNodePtr T, TreePattern &TP,
  1753. std::vector<TreePatternNodePtr> &OutAlternatives) {
  1754. if (TP.hasError())
  1755. return;
  1756. if (isLeaf()) {
  1757. OutAlternatives.push_back(T); // nothing to do.
  1758. return;
  1759. }
  1760. Record *Op = getOperator();
  1761. if (!Op->isSubClassOf("PatFrags")) {
  1762. if (getNumChildren() == 0) {
  1763. OutAlternatives.push_back(T);
  1764. return;
  1765. }
  1766. // Recursively inline children nodes.
  1767. std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
  1768. ChildAlternatives.resize(getNumChildren());
  1769. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1770. TreePatternNodePtr Child = getChildShared(i);
  1771. Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
  1772. // If there are no alternatives for any child, there are no
  1773. // alternatives for this expression as whole.
  1774. if (ChildAlternatives[i].empty())
  1775. return;
  1776. for (auto NewChild : ChildAlternatives[i])
  1777. assert((Child->getPredicateCalls().empty() ||
  1778. NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
  1779. "Non-empty child predicate clobbered!");
  1780. }
  1781. // The end result is an all-pairs construction of the resultant pattern.
  1782. std::vector<unsigned> Idxs;
  1783. Idxs.resize(ChildAlternatives.size());
  1784. bool NotDone;
  1785. do {
  1786. // Create the variant and add it to the output list.
  1787. std::vector<TreePatternNodePtr> NewChildren;
  1788. for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
  1789. NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
  1790. TreePatternNodePtr R = std::make_shared<TreePatternNode>(
  1791. getOperator(), std::move(NewChildren), getNumTypes());
  1792. // Copy over properties.
  1793. R->setName(getName());
  1794. R->setNamesAsPredicateArg(getNamesAsPredicateArg());
  1795. R->setPredicateCalls(getPredicateCalls());
  1796. R->setTransformFn(getTransformFn());
  1797. for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
  1798. R->setType(i, getExtType(i));
  1799. for (unsigned i = 0, e = getNumResults(); i != e; ++i)
  1800. R->setResultIndex(i, getResultIndex(i));
  1801. // Register alternative.
  1802. OutAlternatives.push_back(R);
  1803. // Increment indices to the next permutation by incrementing the
  1804. // indices from last index backward, e.g., generate the sequence
  1805. // [0, 0], [0, 1], [1, 0], [1, 1].
  1806. int IdxsIdx;
  1807. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  1808. if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
  1809. Idxs[IdxsIdx] = 0;
  1810. else
  1811. break;
  1812. }
  1813. NotDone = (IdxsIdx >= 0);
  1814. } while (NotDone);
  1815. return;
  1816. }
  1817. // Otherwise, we found a reference to a fragment. First, look up its
  1818. // TreePattern record.
  1819. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1820. // Verify that we are passing the right number of operands.
  1821. if (Frag->getNumArgs() != Children.size()) {
  1822. TP.error("'" + Op->getName() + "' fragment requires " +
  1823. Twine(Frag->getNumArgs()) + " operands!");
  1824. return;
  1825. }
  1826. TreePredicateFn PredFn(Frag);
  1827. unsigned Scope = 0;
  1828. if (TreePredicateFn(Frag).usesOperands())
  1829. Scope = TP.getDAGPatterns().allocateScope();
  1830. // Compute the map of formal to actual arguments.
  1831. std::map<std::string, TreePatternNodePtr> ArgMap;
  1832. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
  1833. TreePatternNodePtr Child = getChildShared(i);
  1834. if (Scope != 0) {
  1835. Child = Child->clone();
  1836. Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
  1837. }
  1838. ArgMap[Frag->getArgName(i)] = Child;
  1839. }
  1840. // Loop over all fragment alternatives.
  1841. for (auto Alternative : Frag->getTrees()) {
  1842. TreePatternNodePtr FragTree = Alternative->clone();
  1843. if (!PredFn.isAlwaysTrue())
  1844. FragTree->addPredicateCall(PredFn, Scope);
  1845. // Resolve formal arguments to their actual value.
  1846. if (Frag->getNumArgs())
  1847. FragTree->SubstituteFormalArguments(ArgMap);
  1848. // Transfer types. Note that the resolved alternative may have fewer
  1849. // (but not more) results than the PatFrags node.
  1850. FragTree->setName(getName());
  1851. for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
  1852. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1853. // Transfer in the old predicates.
  1854. for (const TreePredicateCall &Pred : getPredicateCalls())
  1855. FragTree->addPredicateCall(Pred);
  1856. // The fragment we inlined could have recursive inlining that is needed. See
  1857. // if there are any pattern fragments in it and inline them as needed.
  1858. FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
  1859. }
  1860. }
  1861. /// getImplicitType - Check to see if the specified record has an implicit
  1862. /// type which should be applied to it. This will infer the type of register
  1863. /// references from the register file information, for example.
  1864. ///
  1865. /// When Unnamed is set, return the type of a DAG operand with no name, such as
  1866. /// the F8RC register class argument in:
  1867. ///
  1868. /// (COPY_TO_REGCLASS GPR:$src, F8RC)
  1869. ///
  1870. /// When Unnamed is false, return the type of a named DAG operand such as the
  1871. /// GPR:$src operand above.
  1872. ///
  1873. static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
  1874. bool NotRegisters,
  1875. bool Unnamed,
  1876. TreePattern &TP) {
  1877. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  1878. // Check to see if this is a register operand.
  1879. if (R->isSubClassOf("RegisterOperand")) {
  1880. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1881. if (NotRegisters)
  1882. return TypeSetByHwMode(); // Unknown.
  1883. Record *RegClass = R->getValueAsDef("RegClass");
  1884. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1885. return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
  1886. }
  1887. // Check to see if this is a register or a register class.
  1888. if (R->isSubClassOf("RegisterClass")) {
  1889. assert(ResNo == 0 && "Regclass ref only has one result!");
  1890. // An unnamed register class represents itself as an i32 immediate, for
  1891. // example on a COPY_TO_REGCLASS instruction.
  1892. if (Unnamed)
  1893. return TypeSetByHwMode(MVT::i32);
  1894. // In a named operand, the register class provides the possible set of
  1895. // types.
  1896. if (NotRegisters)
  1897. return TypeSetByHwMode(); // Unknown.
  1898. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1899. return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
  1900. }
  1901. if (R->isSubClassOf("PatFrags")) {
  1902. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1903. // Pattern fragment types will be resolved when they are inlined.
  1904. return TypeSetByHwMode(); // Unknown.
  1905. }
  1906. if (R->isSubClassOf("Register")) {
  1907. assert(ResNo == 0 && "Registers only produce one result!");
  1908. if (NotRegisters)
  1909. return TypeSetByHwMode(); // Unknown.
  1910. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1911. return TypeSetByHwMode(T.getRegisterVTs(R));
  1912. }
  1913. if (R->isSubClassOf("SubRegIndex")) {
  1914. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1915. return TypeSetByHwMode(MVT::i32);
  1916. }
  1917. if (R->isSubClassOf("ValueType")) {
  1918. assert(ResNo == 0 && "This node only has one result!");
  1919. // An unnamed VTSDNode represents itself as an MVT::Other immediate.
  1920. //
  1921. // (sext_inreg GPR:$src, i16)
  1922. // ~~~
  1923. if (Unnamed)
  1924. return TypeSetByHwMode(MVT::Other);
  1925. // With a name, the ValueType simply provides the type of the named
  1926. // variable.
  1927. //
  1928. // (sext_inreg i32:$src, i16)
  1929. // ~~~~~~~~
  1930. if (NotRegisters)
  1931. return TypeSetByHwMode(); // Unknown.
  1932. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  1933. return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
  1934. }
  1935. if (R->isSubClassOf("CondCode")) {
  1936. assert(ResNo == 0 && "This node only has one result!");
  1937. // Using a CondCodeSDNode.
  1938. return TypeSetByHwMode(MVT::Other);
  1939. }
  1940. if (R->isSubClassOf("ComplexPattern")) {
  1941. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1942. if (NotRegisters)
  1943. return TypeSetByHwMode(); // Unknown.
  1944. return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
  1945. }
  1946. if (R->isSubClassOf("PointerLikeRegClass")) {
  1947. assert(ResNo == 0 && "Regclass can only have one result!");
  1948. TypeSetByHwMode VTS(MVT::iPTR);
  1949. TP.getInfer().expandOverloads(VTS);
  1950. return VTS;
  1951. }
  1952. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  1953. R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
  1954. R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
  1955. // Placeholder.
  1956. return TypeSetByHwMode(); // Unknown.
  1957. }
  1958. if (R->isSubClassOf("Operand")) {
  1959. const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
  1960. Record *T = R->getValueAsDef("Type");
  1961. return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
  1962. }
  1963. TP.error("Unknown node flavor used in pattern: " + R->getName());
  1964. return TypeSetByHwMode(MVT::Other);
  1965. }
  1966. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  1967. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  1968. const CodeGenIntrinsic *TreePatternNode::
  1969. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  1970. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  1971. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  1972. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  1973. return nullptr;
  1974. unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
  1975. return &CDP.getIntrinsicInfo(IID);
  1976. }
  1977. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  1978. /// return the ComplexPattern information, otherwise return null.
  1979. const ComplexPattern *
  1980. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  1981. Record *Rec;
  1982. if (isLeaf()) {
  1983. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  1984. if (!DI)
  1985. return nullptr;
  1986. Rec = DI->getDef();
  1987. } else
  1988. Rec = getOperator();
  1989. if (!Rec->isSubClassOf("ComplexPattern"))
  1990. return nullptr;
  1991. return &CGP.getComplexPattern(Rec);
  1992. }
  1993. unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
  1994. // A ComplexPattern specifically declares how many results it fills in.
  1995. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  1996. return CP->getNumOperands();
  1997. // If MIOperandInfo is specified, that gives the count.
  1998. if (isLeaf()) {
  1999. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  2000. if (DI && DI->getDef()->isSubClassOf("Operand")) {
  2001. DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
  2002. if (MIOps->getNumArgs())
  2003. return MIOps->getNumArgs();
  2004. }
  2005. }
  2006. // Otherwise there is just one result.
  2007. return 1;
  2008. }
  2009. /// NodeHasProperty - Return true if this node has the specified property.
  2010. bool TreePatternNode::NodeHasProperty(SDNP Property,
  2011. const CodeGenDAGPatterns &CGP) const {
  2012. if (isLeaf()) {
  2013. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  2014. return CP->hasProperty(Property);
  2015. return false;
  2016. }
  2017. if (Property != SDNPHasChain) {
  2018. // The chain proprety is already present on the different intrinsic node
  2019. // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
  2020. // on the intrinsic. Anything else is specific to the individual intrinsic.
  2021. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
  2022. return Int->hasProperty(Property);
  2023. }
  2024. if (!Operator->isSubClassOf("SDPatternOperator"))
  2025. return false;
  2026. return CGP.getSDNodeInfo(Operator).hasProperty(Property);
  2027. }
  2028. /// TreeHasProperty - Return true if any node in this tree has the specified
  2029. /// property.
  2030. bool TreePatternNode::TreeHasProperty(SDNP Property,
  2031. const CodeGenDAGPatterns &CGP) const {
  2032. if (NodeHasProperty(Property, CGP))
  2033. return true;
  2034. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2035. if (getChild(i)->TreeHasProperty(Property, CGP))
  2036. return true;
  2037. return false;
  2038. }
  2039. /// isCommutativeIntrinsic - Return true if the node corresponds to a
  2040. /// commutative intrinsic.
  2041. bool
  2042. TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
  2043. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
  2044. return Int->isCommutative;
  2045. return false;
  2046. }
  2047. static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
  2048. if (!N->isLeaf())
  2049. return N->getOperator()->isSubClassOf(Class);
  2050. DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
  2051. if (DI && DI->getDef()->isSubClassOf(Class))
  2052. return true;
  2053. return false;
  2054. }
  2055. static void emitTooManyOperandsError(TreePattern &TP,
  2056. StringRef InstName,
  2057. unsigned Expected,
  2058. unsigned Actual) {
  2059. TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
  2060. " operands but expected only " + Twine(Expected) + "!");
  2061. }
  2062. static void emitTooFewOperandsError(TreePattern &TP,
  2063. StringRef InstName,
  2064. unsigned Actual) {
  2065. TP.error("Instruction '" + InstName +
  2066. "' expects more than the provided " + Twine(Actual) + " operands!");
  2067. }
  2068. /// ApplyTypeConstraints - Apply all of the type constraints relevant to
  2069. /// this node and its children in the tree. This returns true if it makes a
  2070. /// change, false otherwise. If a type contradiction is found, flag an error.
  2071. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
  2072. if (TP.hasError())
  2073. return false;
  2074. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  2075. if (isLeaf()) {
  2076. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  2077. // If it's a regclass or something else known, include the type.
  2078. bool MadeChange = false;
  2079. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  2080. MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
  2081. NotRegisters,
  2082. !hasName(), TP), TP);
  2083. return MadeChange;
  2084. }
  2085. if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
  2086. assert(Types.size() == 1 && "Invalid IntInit");
  2087. // Int inits are always integers. :)
  2088. bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
  2089. if (!TP.getInfer().isConcrete(Types[0], false))
  2090. return MadeChange;
  2091. ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
  2092. for (auto &P : VVT) {
  2093. MVT::SimpleValueType VT = P.second.SimpleTy;
  2094. if (VT == MVT::iPTR || VT == MVT::iPTRAny)
  2095. continue;
  2096. unsigned Size = MVT(VT).getFixedSizeInBits();
  2097. // Make sure that the value is representable for this type.
  2098. if (Size >= 32)
  2099. continue;
  2100. // Check that the value doesn't use more bits than we have. It must
  2101. // either be a sign- or zero-extended equivalent of the original.
  2102. int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
  2103. if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
  2104. SignBitAndAbove == 1)
  2105. continue;
  2106. TP.error("Integer value '" + Twine(II->getValue()) +
  2107. "' is out of range for type '" + getEnumName(VT) + "'!");
  2108. break;
  2109. }
  2110. return MadeChange;
  2111. }
  2112. return false;
  2113. }
  2114. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
  2115. bool MadeChange = false;
  2116. // Apply the result type to the node.
  2117. unsigned NumRetVTs = Int->IS.RetVTs.size();
  2118. unsigned NumParamVTs = Int->IS.ParamVTs.size();
  2119. for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
  2120. MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
  2121. if (getNumChildren() != NumParamVTs + 1) {
  2122. TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
  2123. " operands, not " + Twine(getNumChildren() - 1) + " operands!");
  2124. return false;
  2125. }
  2126. // Apply type info to the intrinsic ID.
  2127. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
  2128. for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
  2129. MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
  2130. MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
  2131. assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
  2132. MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
  2133. }
  2134. return MadeChange;
  2135. }
  2136. if (getOperator()->isSubClassOf("SDNode")) {
  2137. const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
  2138. // Check that the number of operands is sane. Negative operands -> varargs.
  2139. if (NI.getNumOperands() >= 0 &&
  2140. getNumChildren() != (unsigned)NI.getNumOperands()) {
  2141. TP.error(getOperator()->getName() + " node requires exactly " +
  2142. Twine(NI.getNumOperands()) + " operands!");
  2143. return false;
  2144. }
  2145. bool MadeChange = false;
  2146. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2147. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2148. MadeChange |= NI.ApplyTypeConstraints(this, TP);
  2149. return MadeChange;
  2150. }
  2151. if (getOperator()->isSubClassOf("Instruction")) {
  2152. const DAGInstruction &Inst = CDP.getInstruction(getOperator());
  2153. CodeGenInstruction &InstInfo =
  2154. CDP.getTargetInfo().getInstruction(getOperator());
  2155. bool MadeChange = false;
  2156. // Apply the result types to the node, these come from the things in the
  2157. // (outs) list of the instruction.
  2158. unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
  2159. Inst.getNumResults());
  2160. for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
  2161. MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
  2162. // If the instruction has implicit defs, we apply the first one as a result.
  2163. // FIXME: This sucks, it should apply all implicit defs.
  2164. if (!InstInfo.ImplicitDefs.empty()) {
  2165. unsigned ResNo = NumResultsToAdd;
  2166. // FIXME: Generalize to multiple possible types and multiple possible
  2167. // ImplicitDefs.
  2168. MVT::SimpleValueType VT =
  2169. InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
  2170. if (VT != MVT::Other)
  2171. MadeChange |= UpdateNodeType(ResNo, VT, TP);
  2172. }
  2173. // If this is an INSERT_SUBREG, constrain the source and destination VTs to
  2174. // be the same.
  2175. if (getOperator()->getName() == "INSERT_SUBREG") {
  2176. assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
  2177. MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
  2178. MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
  2179. } else if (getOperator()->getName() == "REG_SEQUENCE") {
  2180. // We need to do extra, custom typechecking for REG_SEQUENCE since it is
  2181. // variadic.
  2182. unsigned NChild = getNumChildren();
  2183. if (NChild < 3) {
  2184. TP.error("REG_SEQUENCE requires at least 3 operands!");
  2185. return false;
  2186. }
  2187. if (NChild % 2 == 0) {
  2188. TP.error("REG_SEQUENCE requires an odd number of operands!");
  2189. return false;
  2190. }
  2191. if (!isOperandClass(getChild(0), "RegisterClass")) {
  2192. TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
  2193. return false;
  2194. }
  2195. for (unsigned I = 1; I < NChild; I += 2) {
  2196. TreePatternNode *SubIdxChild = getChild(I + 1);
  2197. if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
  2198. TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
  2199. Twine(I + 1) + "!");
  2200. return false;
  2201. }
  2202. }
  2203. }
  2204. unsigned NumResults = Inst.getNumResults();
  2205. unsigned NumFixedOperands = InstInfo.Operands.size();
  2206. // If one or more operands with a default value appear at the end of the
  2207. // formal operand list for an instruction, we allow them to be overridden
  2208. // by optional operands provided in the pattern.
  2209. //
  2210. // But if an operand B without a default appears at any point after an
  2211. // operand A with a default, then we don't allow A to be overridden,
  2212. // because there would be no way to specify whether the next operand in
  2213. // the pattern was intended to override A or skip it.
  2214. unsigned NonOverridableOperands = NumFixedOperands;
  2215. while (NonOverridableOperands > NumResults &&
  2216. CDP.operandHasDefault(InstInfo.Operands[NonOverridableOperands-1].Rec))
  2217. --NonOverridableOperands;
  2218. unsigned ChildNo = 0;
  2219. assert(NumResults <= NumFixedOperands);
  2220. for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
  2221. Record *OperandNode = InstInfo.Operands[i].Rec;
  2222. // If the operand has a default value, do we use it? We must use the
  2223. // default if we've run out of children of the pattern DAG to consume,
  2224. // or if the operand is followed by a non-defaulted one.
  2225. if (CDP.operandHasDefault(OperandNode) &&
  2226. (i < NonOverridableOperands || ChildNo >= getNumChildren()))
  2227. continue;
  2228. // If we have run out of child nodes and there _isn't_ a default
  2229. // value we can use for the next operand, give an error.
  2230. if (ChildNo >= getNumChildren()) {
  2231. emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
  2232. return false;
  2233. }
  2234. TreePatternNode *Child = getChild(ChildNo++);
  2235. unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
  2236. // If the operand has sub-operands, they may be provided by distinct
  2237. // child patterns, so attempt to match each sub-operand separately.
  2238. if (OperandNode->isSubClassOf("Operand")) {
  2239. DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
  2240. if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
  2241. // But don't do that if the whole operand is being provided by
  2242. // a single ComplexPattern-related Operand.
  2243. if (Child->getNumMIResults(CDP) < NumArgs) {
  2244. // Match first sub-operand against the child we already have.
  2245. Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
  2246. MadeChange |=
  2247. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  2248. // And the remaining sub-operands against subsequent children.
  2249. for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
  2250. if (ChildNo >= getNumChildren()) {
  2251. emitTooFewOperandsError(TP, getOperator()->getName(),
  2252. getNumChildren());
  2253. return false;
  2254. }
  2255. Child = getChild(ChildNo++);
  2256. SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
  2257. MadeChange |=
  2258. Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
  2259. }
  2260. continue;
  2261. }
  2262. }
  2263. }
  2264. // If we didn't match by pieces above, attempt to match the whole
  2265. // operand now.
  2266. MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
  2267. }
  2268. if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
  2269. emitTooManyOperandsError(TP, getOperator()->getName(),
  2270. ChildNo, getNumChildren());
  2271. return false;
  2272. }
  2273. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2274. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2275. return MadeChange;
  2276. }
  2277. if (getOperator()->isSubClassOf("ComplexPattern")) {
  2278. bool MadeChange = false;
  2279. for (unsigned i = 0; i < getNumChildren(); ++i)
  2280. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  2281. return MadeChange;
  2282. }
  2283. assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
  2284. // Node transforms always take one operand.
  2285. if (getNumChildren() != 1) {
  2286. TP.error("Node transform '" + getOperator()->getName() +
  2287. "' requires one operand!");
  2288. return false;
  2289. }
  2290. bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  2291. return MadeChange;
  2292. }
  2293. /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
  2294. /// RHS of a commutative operation, not the on LHS.
  2295. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
  2296. if (!N->isLeaf() && N->getOperator()->getName() == "imm")
  2297. return true;
  2298. if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
  2299. return true;
  2300. return false;
  2301. }
  2302. /// canPatternMatch - If it is impossible for this pattern to match on this
  2303. /// target, fill in Reason and return false. Otherwise, return true. This is
  2304. /// used as a sanity check for .td files (to prevent people from writing stuff
  2305. /// that can never possibly work), and to prevent the pattern permuter from
  2306. /// generating stuff that is useless.
  2307. bool TreePatternNode::canPatternMatch(std::string &Reason,
  2308. const CodeGenDAGPatterns &CDP) {
  2309. if (isLeaf()) return true;
  2310. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  2311. if (!getChild(i)->canPatternMatch(Reason, CDP))
  2312. return false;
  2313. // If this is an intrinsic, handle cases that would make it not match. For
  2314. // example, if an operand is required to be an immediate.
  2315. if (getOperator()->isSubClassOf("Intrinsic")) {
  2316. // TODO:
  2317. return true;
  2318. }
  2319. if (getOperator()->isSubClassOf("ComplexPattern"))
  2320. return true;
  2321. // If this node is a commutative operator, check that the LHS isn't an
  2322. // immediate.
  2323. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
  2324. bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
  2325. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  2326. // Scan all of the operands of the node and make sure that only the last one
  2327. // is a constant node, unless the RHS also is.
  2328. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
  2329. unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  2330. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
  2331. if (OnlyOnRHSOfCommutative(getChild(i))) {
  2332. Reason="Immediate value must be on the RHS of commutative operators!";
  2333. return false;
  2334. }
  2335. }
  2336. }
  2337. return true;
  2338. }
  2339. //===----------------------------------------------------------------------===//
  2340. // TreePattern implementation
  2341. //
  2342. TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
  2343. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  2344. isInputPattern(isInput), HasError(false),
  2345. Infer(*this) {
  2346. for (Init *I : RawPat->getValues())
  2347. Trees.push_back(ParseTreePattern(I, ""));
  2348. }
  2349. TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
  2350. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  2351. isInputPattern(isInput), HasError(false),
  2352. Infer(*this) {
  2353. Trees.push_back(ParseTreePattern(Pat, ""));
  2354. }
  2355. TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
  2356. CodeGenDAGPatterns &cdp)
  2357. : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
  2358. Infer(*this) {
  2359. Trees.push_back(Pat);
  2360. }
  2361. void TreePattern::error(const Twine &Msg) {
  2362. if (HasError)
  2363. return;
  2364. dump();
  2365. PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
  2366. HasError = true;
  2367. }
  2368. void TreePattern::ComputeNamedNodes() {
  2369. for (TreePatternNodePtr &Tree : Trees)
  2370. ComputeNamedNodes(Tree.get());
  2371. }
  2372. void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
  2373. if (!N->getName().empty())
  2374. NamedNodes[N->getName()].push_back(N);
  2375. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2376. ComputeNamedNodes(N->getChild(i));
  2377. }
  2378. TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
  2379. StringRef OpName) {
  2380. if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
  2381. Record *R = DI->getDef();
  2382. // Direct reference to a leaf DagNode or PatFrag? Turn it into a
  2383. // TreePatternNode of its own. For example:
  2384. /// (foo GPR, imm) -> (foo GPR, (imm))
  2385. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
  2386. return ParseTreePattern(
  2387. DagInit::get(DI, nullptr,
  2388. std::vector<std::pair<Init*, StringInit*> >()),
  2389. OpName);
  2390. // Input argument?
  2391. TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
  2392. if (R->getName() == "node" && !OpName.empty()) {
  2393. if (OpName.empty())
  2394. error("'node' argument requires a name to match with operand list");
  2395. Args.push_back(std::string(OpName));
  2396. }
  2397. Res->setName(OpName);
  2398. return Res;
  2399. }
  2400. // ?:$name or just $name.
  2401. if (isa<UnsetInit>(TheInit)) {
  2402. if (OpName.empty())
  2403. error("'?' argument requires a name to match with operand list");
  2404. TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
  2405. Args.push_back(std::string(OpName));
  2406. Res->setName(OpName);
  2407. return Res;
  2408. }
  2409. if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
  2410. if (!OpName.empty())
  2411. error("Constant int or bit argument should not have a name!");
  2412. if (isa<BitInit>(TheInit))
  2413. TheInit = TheInit->convertInitializerTo(IntRecTy::get());
  2414. return std::make_shared<TreePatternNode>(TheInit, 1);
  2415. }
  2416. if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
  2417. // Turn this into an IntInit.
  2418. Init *II = BI->convertInitializerTo(IntRecTy::get());
  2419. if (!II || !isa<IntInit>(II))
  2420. error("Bits value must be constants!");
  2421. return ParseTreePattern(II, OpName);
  2422. }
  2423. DagInit *Dag = dyn_cast<DagInit>(TheInit);
  2424. if (!Dag) {
  2425. TheInit->print(errs());
  2426. error("Pattern has unexpected init kind!");
  2427. }
  2428. DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
  2429. if (!OpDef) error("Pattern has unexpected operator type!");
  2430. Record *Operator = OpDef->getDef();
  2431. if (Operator->isSubClassOf("ValueType")) {
  2432. // If the operator is a ValueType, then this must be "type cast" of a leaf
  2433. // node.
  2434. if (Dag->getNumArgs() != 1)
  2435. error("Type cast only takes one operand!");
  2436. TreePatternNodePtr New =
  2437. ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
  2438. // Apply the type cast.
  2439. assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
  2440. const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
  2441. New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
  2442. if (!OpName.empty())
  2443. error("ValueType cast should not have a name!");
  2444. return New;
  2445. }
  2446. // Verify that this is something that makes sense for an operator.
  2447. if (!Operator->isSubClassOf("PatFrags") &&
  2448. !Operator->isSubClassOf("SDNode") &&
  2449. !Operator->isSubClassOf("Instruction") &&
  2450. !Operator->isSubClassOf("SDNodeXForm") &&
  2451. !Operator->isSubClassOf("Intrinsic") &&
  2452. !Operator->isSubClassOf("ComplexPattern") &&
  2453. Operator->getName() != "set" &&
  2454. Operator->getName() != "implicit")
  2455. error("Unrecognized node '" + Operator->getName() + "'!");
  2456. // Check to see if this is something that is illegal in an input pattern.
  2457. if (isInputPattern) {
  2458. if (Operator->isSubClassOf("Instruction") ||
  2459. Operator->isSubClassOf("SDNodeXForm"))
  2460. error("Cannot use '" + Operator->getName() + "' in an input pattern!");
  2461. } else {
  2462. if (Operator->isSubClassOf("Intrinsic"))
  2463. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  2464. if (Operator->isSubClassOf("SDNode") &&
  2465. Operator->getName() != "imm" &&
  2466. Operator->getName() != "timm" &&
  2467. Operator->getName() != "fpimm" &&
  2468. Operator->getName() != "tglobaltlsaddr" &&
  2469. Operator->getName() != "tconstpool" &&
  2470. Operator->getName() != "tjumptable" &&
  2471. Operator->getName() != "tframeindex" &&
  2472. Operator->getName() != "texternalsym" &&
  2473. Operator->getName() != "tblockaddress" &&
  2474. Operator->getName() != "tglobaladdr" &&
  2475. Operator->getName() != "bb" &&
  2476. Operator->getName() != "vt" &&
  2477. Operator->getName() != "mcsym")
  2478. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  2479. }
  2480. std::vector<TreePatternNodePtr> Children;
  2481. // Parse all the operands.
  2482. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
  2483. Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
  2484. // Get the actual number of results before Operator is converted to an intrinsic
  2485. // node (which is hard-coded to have either zero or one result).
  2486. unsigned NumResults = GetNumNodeResults(Operator, CDP);
  2487. // If the operator is an intrinsic, then this is just syntactic sugar for
  2488. // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
  2489. // convert the intrinsic name to a number.
  2490. if (Operator->isSubClassOf("Intrinsic")) {
  2491. const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
  2492. unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
  2493. // If this intrinsic returns void, it must have side-effects and thus a
  2494. // chain.
  2495. if (Int.IS.RetVTs.empty())
  2496. Operator = getDAGPatterns().get_intrinsic_void_sdnode();
  2497. else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
  2498. // Has side-effects, requires chain.
  2499. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
  2500. else // Otherwise, no chain.
  2501. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
  2502. Children.insert(Children.begin(),
  2503. std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
  2504. }
  2505. if (Operator->isSubClassOf("ComplexPattern")) {
  2506. for (unsigned i = 0; i < Children.size(); ++i) {
  2507. TreePatternNodePtr Child = Children[i];
  2508. if (Child->getName().empty())
  2509. error("All arguments to a ComplexPattern must be named");
  2510. // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
  2511. // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
  2512. // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
  2513. auto OperandId = std::make_pair(Operator, i);
  2514. auto PrevOp = ComplexPatternOperands.find(Child->getName());
  2515. if (PrevOp != ComplexPatternOperands.end()) {
  2516. if (PrevOp->getValue() != OperandId)
  2517. error("All ComplexPattern operands must appear consistently: "
  2518. "in the same order in just one ComplexPattern instance.");
  2519. } else
  2520. ComplexPatternOperands[Child->getName()] = OperandId;
  2521. }
  2522. }
  2523. TreePatternNodePtr Result =
  2524. std::make_shared<TreePatternNode>(Operator, std::move(Children),
  2525. NumResults);
  2526. Result->setName(OpName);
  2527. if (Dag->getName()) {
  2528. assert(Result->getName().empty());
  2529. Result->setName(Dag->getNameStr());
  2530. }
  2531. return Result;
  2532. }
  2533. /// SimplifyTree - See if we can simplify this tree to eliminate something that
  2534. /// will never match in favor of something obvious that will. This is here
  2535. /// strictly as a convenience to target authors because it allows them to write
  2536. /// more type generic things and have useless type casts fold away.
  2537. ///
  2538. /// This returns true if any change is made.
  2539. static bool SimplifyTree(TreePatternNodePtr &N) {
  2540. if (N->isLeaf())
  2541. return false;
  2542. // If we have a bitconvert with a resolved type and if the source and
  2543. // destination types are the same, then the bitconvert is useless, remove it.
  2544. //
  2545. // We make an exception if the types are completely empty. This can come up
  2546. // when the pattern being simplified is in the Fragments list of a PatFrags,
  2547. // so that the operand is just an untyped "node". In that situation we leave
  2548. // bitconverts unsimplified, and simplify them later once the fragment is
  2549. // expanded into its true context.
  2550. if (N->getOperator()->getName() == "bitconvert" &&
  2551. N->getExtType(0).isValueTypeByHwMode(false) &&
  2552. !N->getExtType(0).empty() &&
  2553. N->getExtType(0) == N->getChild(0)->getExtType(0) &&
  2554. N->getName().empty()) {
  2555. N = N->getChildShared(0);
  2556. SimplifyTree(N);
  2557. return true;
  2558. }
  2559. // Walk all children.
  2560. bool MadeChange = false;
  2561. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  2562. TreePatternNodePtr Child = N->getChildShared(i);
  2563. MadeChange |= SimplifyTree(Child);
  2564. N->setChild(i, std::move(Child));
  2565. }
  2566. return MadeChange;
  2567. }
  2568. /// InferAllTypes - Infer/propagate as many types throughout the expression
  2569. /// patterns as possible. Return true if all types are inferred, false
  2570. /// otherwise. Flags an error if a type contradiction is found.
  2571. bool TreePattern::
  2572. InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
  2573. if (NamedNodes.empty())
  2574. ComputeNamedNodes();
  2575. bool MadeChange = true;
  2576. while (MadeChange) {
  2577. MadeChange = false;
  2578. for (TreePatternNodePtr &Tree : Trees) {
  2579. MadeChange |= Tree->ApplyTypeConstraints(*this, false);
  2580. MadeChange |= SimplifyTree(Tree);
  2581. }
  2582. // If there are constraints on our named nodes, apply them.
  2583. for (auto &Entry : NamedNodes) {
  2584. SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
  2585. // If we have input named node types, propagate their types to the named
  2586. // values here.
  2587. if (InNamedTypes) {
  2588. if (!InNamedTypes->count(Entry.getKey())) {
  2589. error("Node '" + std::string(Entry.getKey()) +
  2590. "' in output pattern but not input pattern");
  2591. return true;
  2592. }
  2593. const SmallVectorImpl<TreePatternNode*> &InNodes =
  2594. InNamedTypes->find(Entry.getKey())->second;
  2595. // The input types should be fully resolved by now.
  2596. for (TreePatternNode *Node : Nodes) {
  2597. // If this node is a register class, and it is the root of the pattern
  2598. // then we're mapping something onto an input register. We allow
  2599. // changing the type of the input register in this case. This allows
  2600. // us to match things like:
  2601. // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
  2602. if (Node == Trees[0].get() && Node->isLeaf()) {
  2603. DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
  2604. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  2605. DI->getDef()->isSubClassOf("RegisterOperand")))
  2606. continue;
  2607. }
  2608. assert(Node->getNumTypes() == 1 &&
  2609. InNodes[0]->getNumTypes() == 1 &&
  2610. "FIXME: cannot name multiple result nodes yet");
  2611. MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
  2612. *this);
  2613. }
  2614. }
  2615. // If there are multiple nodes with the same name, they must all have the
  2616. // same type.
  2617. if (Entry.second.size() > 1) {
  2618. for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
  2619. TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
  2620. assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
  2621. "FIXME: cannot name multiple result nodes yet");
  2622. MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
  2623. MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
  2624. }
  2625. }
  2626. }
  2627. }
  2628. bool HasUnresolvedTypes = false;
  2629. for (const TreePatternNodePtr &Tree : Trees)
  2630. HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
  2631. return !HasUnresolvedTypes;
  2632. }
  2633. void TreePattern::print(raw_ostream &OS) const {
  2634. OS << getRecord()->getName();
  2635. if (!Args.empty()) {
  2636. OS << "(" << Args[0];
  2637. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  2638. OS << ", " << Args[i];
  2639. OS << ")";
  2640. }
  2641. OS << ": ";
  2642. if (Trees.size() > 1)
  2643. OS << "[\n";
  2644. for (const TreePatternNodePtr &Tree : Trees) {
  2645. OS << "\t";
  2646. Tree->print(OS);
  2647. OS << "\n";
  2648. }
  2649. if (Trees.size() > 1)
  2650. OS << "]\n";
  2651. }
  2652. void TreePattern::dump() const { print(errs()); }
  2653. //===----------------------------------------------------------------------===//
  2654. // CodeGenDAGPatterns implementation
  2655. //
  2656. CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
  2657. PatternRewriterFn PatternRewriter)
  2658. : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
  2659. PatternRewriter(PatternRewriter) {
  2660. Intrinsics = CodeGenIntrinsicTable(Records);
  2661. ParseNodeInfo();
  2662. ParseNodeTransforms();
  2663. ParseComplexPatterns();
  2664. ParsePatternFragments();
  2665. ParseDefaultOperands();
  2666. ParseInstructions();
  2667. ParsePatternFragments(/*OutFrags*/true);
  2668. ParsePatterns();
  2669. // Break patterns with parameterized types into a series of patterns,
  2670. // where each one has a fixed type and is predicated on the conditions
  2671. // of the associated HW mode.
  2672. ExpandHwModeBasedTypes();
  2673. // Generate variants. For example, commutative patterns can match
  2674. // multiple ways. Add them to PatternsToMatch as well.
  2675. GenerateVariants();
  2676. // Infer instruction flags. For example, we can detect loads,
  2677. // stores, and side effects in many cases by examining an
  2678. // instruction's pattern.
  2679. InferInstructionFlags();
  2680. // Verify that instruction flags match the patterns.
  2681. VerifyInstructionFlags();
  2682. }
  2683. Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
  2684. Record *N = Records.getDef(Name);
  2685. if (!N || !N->isSubClassOf("SDNode"))
  2686. PrintFatalError("Error getting SDNode '" + Name + "'!");
  2687. return N;
  2688. }
  2689. // Parse all of the SDNode definitions for the target, populating SDNodes.
  2690. void CodeGenDAGPatterns::ParseNodeInfo() {
  2691. std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
  2692. const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
  2693. while (!Nodes.empty()) {
  2694. Record *R = Nodes.back();
  2695. SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
  2696. Nodes.pop_back();
  2697. }
  2698. // Get the builtin intrinsic nodes.
  2699. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
  2700. intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
  2701. intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
  2702. }
  2703. /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
  2704. /// map, and emit them to the file as functions.
  2705. void CodeGenDAGPatterns::ParseNodeTransforms() {
  2706. std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
  2707. while (!Xforms.empty()) {
  2708. Record *XFormNode = Xforms.back();
  2709. Record *SDNode = XFormNode->getValueAsDef("Opcode");
  2710. StringRef Code = XFormNode->getValueAsString("XFormFunction");
  2711. SDNodeXForms.insert(
  2712. std::make_pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
  2713. Xforms.pop_back();
  2714. }
  2715. }
  2716. void CodeGenDAGPatterns::ParseComplexPatterns() {
  2717. std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
  2718. while (!AMs.empty()) {
  2719. ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
  2720. AMs.pop_back();
  2721. }
  2722. }
  2723. /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
  2724. /// file, building up the PatternFragments map. After we've collected them all,
  2725. /// inline fragments together as necessary, so that there are no references left
  2726. /// inside a pattern fragment to a pattern fragment.
  2727. ///
  2728. void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
  2729. std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
  2730. // First step, parse all of the fragments.
  2731. for (Record *Frag : Fragments) {
  2732. if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
  2733. continue;
  2734. ListInit *LI = Frag->getValueAsListInit("Fragments");
  2735. TreePattern *P =
  2736. (PatternFragments[Frag] = std::make_unique<TreePattern>(
  2737. Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
  2738. *this)).get();
  2739. // Validate the argument list, converting it to set, to discard duplicates.
  2740. std::vector<std::string> &Args = P->getArgList();
  2741. // Copy the args so we can take StringRefs to them.
  2742. auto ArgsCopy = Args;
  2743. SmallDenseSet<StringRef, 4> OperandsSet;
  2744. OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
  2745. if (OperandsSet.count(""))
  2746. P->error("Cannot have unnamed 'node' values in pattern fragment!");
  2747. // Parse the operands list.
  2748. DagInit *OpsList = Frag->getValueAsDag("Operands");
  2749. DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
  2750. // Special cases: ops == outs == ins. Different names are used to
  2751. // improve readability.
  2752. if (!OpsOp ||
  2753. (OpsOp->getDef()->getName() != "ops" &&
  2754. OpsOp->getDef()->getName() != "outs" &&
  2755. OpsOp->getDef()->getName() != "ins"))
  2756. P->error("Operands list should start with '(ops ... '!");
  2757. // Copy over the arguments.
  2758. Args.clear();
  2759. for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
  2760. if (!isa<DefInit>(OpsList->getArg(j)) ||
  2761. cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
  2762. P->error("Operands list should all be 'node' values.");
  2763. if (!OpsList->getArgName(j))
  2764. P->error("Operands list should have names for each operand!");
  2765. StringRef ArgNameStr = OpsList->getArgNameStr(j);
  2766. if (!OperandsSet.count(ArgNameStr))
  2767. P->error("'" + ArgNameStr +
  2768. "' does not occur in pattern or was multiply specified!");
  2769. OperandsSet.erase(ArgNameStr);
  2770. Args.push_back(std::string(ArgNameStr));
  2771. }
  2772. if (!OperandsSet.empty())
  2773. P->error("Operands list does not contain an entry for operand '" +
  2774. *OperandsSet.begin() + "'!");
  2775. // If there is a node transformation corresponding to this, keep track of
  2776. // it.
  2777. Record *Transform = Frag->getValueAsDef("OperandTransform");
  2778. if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
  2779. for (auto T : P->getTrees())
  2780. T->setTransformFn(Transform);
  2781. }
  2782. // Now that we've parsed all of the tree fragments, do a closure on them so
  2783. // that there are not references to PatFrags left inside of them.
  2784. for (Record *Frag : Fragments) {
  2785. if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
  2786. continue;
  2787. TreePattern &ThePat = *PatternFragments[Frag];
  2788. ThePat.InlinePatternFragments();
  2789. // Infer as many types as possible. Don't worry about it if we don't infer
  2790. // all of them, some may depend on the inputs of the pattern. Also, don't
  2791. // validate type sets; validation may cause spurious failures e.g. if a
  2792. // fragment needs floating-point types but the current target does not have
  2793. // any (this is only an error if that fragment is ever used!).
  2794. {
  2795. TypeInfer::SuppressValidation SV(ThePat.getInfer());
  2796. ThePat.InferAllTypes();
  2797. ThePat.resetError();
  2798. }
  2799. // If debugging, print out the pattern fragment result.
  2800. LLVM_DEBUG(ThePat.dump());
  2801. }
  2802. }
  2803. void CodeGenDAGPatterns::ParseDefaultOperands() {
  2804. std::vector<Record*> DefaultOps;
  2805. DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
  2806. // Find some SDNode.
  2807. assert(!SDNodes.empty() && "No SDNodes parsed?");
  2808. Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
  2809. for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
  2810. DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
  2811. // Clone the DefaultInfo dag node, changing the operator from 'ops' to
  2812. // SomeSDnode so that we can parse this.
  2813. std::vector<std::pair<Init*, StringInit*> > Ops;
  2814. for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
  2815. Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
  2816. DefaultInfo->getArgName(op)));
  2817. DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
  2818. // Create a TreePattern to parse this.
  2819. TreePattern P(DefaultOps[i], DI, false, *this);
  2820. assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
  2821. // Copy the operands over into a DAGDefaultOperand.
  2822. DAGDefaultOperand DefaultOpInfo;
  2823. const TreePatternNodePtr &T = P.getTree(0);
  2824. for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
  2825. TreePatternNodePtr TPN = T->getChildShared(op);
  2826. while (TPN->ApplyTypeConstraints(P, false))
  2827. /* Resolve all types */;
  2828. if (TPN->ContainsUnresolvedType(P)) {
  2829. PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
  2830. DefaultOps[i]->getName() +
  2831. "' doesn't have a concrete type!");
  2832. }
  2833. DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
  2834. }
  2835. // Insert it into the DefaultOperands map so we can find it later.
  2836. DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
  2837. }
  2838. }
  2839. /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
  2840. /// instruction input. Return true if this is a real use.
  2841. static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
  2842. std::map<std::string, TreePatternNodePtr> &InstInputs) {
  2843. // No name -> not interesting.
  2844. if (Pat->getName().empty()) {
  2845. if (Pat->isLeaf()) {
  2846. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  2847. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  2848. DI->getDef()->isSubClassOf("RegisterOperand")))
  2849. I.error("Input " + DI->getDef()->getName() + " must be named!");
  2850. }
  2851. return false;
  2852. }
  2853. Record *Rec;
  2854. if (Pat->isLeaf()) {
  2855. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  2856. if (!DI)
  2857. I.error("Input $" + Pat->getName() + " must be an identifier!");
  2858. Rec = DI->getDef();
  2859. } else {
  2860. Rec = Pat->getOperator();
  2861. }
  2862. // SRCVALUE nodes are ignored.
  2863. if (Rec->getName() == "srcvalue")
  2864. return false;
  2865. TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
  2866. if (!Slot) {
  2867. Slot = Pat;
  2868. return true;
  2869. }
  2870. Record *SlotRec;
  2871. if (Slot->isLeaf()) {
  2872. SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
  2873. } else {
  2874. assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
  2875. SlotRec = Slot->getOperator();
  2876. }
  2877. // Ensure that the inputs agree if we've already seen this input.
  2878. if (Rec != SlotRec)
  2879. I.error("All $" + Pat->getName() + " inputs must agree with each other");
  2880. // Ensure that the types can agree as well.
  2881. Slot->UpdateNodeType(0, Pat->getExtType(0), I);
  2882. Pat->UpdateNodeType(0, Slot->getExtType(0), I);
  2883. if (Slot->getExtTypes() != Pat->getExtTypes())
  2884. I.error("All $" + Pat->getName() + " inputs must agree with each other");
  2885. return true;
  2886. }
  2887. /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
  2888. /// part of "I", the instruction), computing the set of inputs and outputs of
  2889. /// the pattern. Report errors if we see anything naughty.
  2890. void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
  2891. TreePattern &I, TreePatternNodePtr Pat,
  2892. std::map<std::string, TreePatternNodePtr> &InstInputs,
  2893. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  2894. &InstResults,
  2895. std::vector<Record *> &InstImpResults) {
  2896. // The instruction pattern still has unresolved fragments. For *named*
  2897. // nodes we must resolve those here. This may not result in multiple
  2898. // alternatives.
  2899. if (!Pat->getName().empty()) {
  2900. TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
  2901. SrcPattern.InlinePatternFragments();
  2902. SrcPattern.InferAllTypes();
  2903. Pat = SrcPattern.getOnlyTree();
  2904. }
  2905. if (Pat->isLeaf()) {
  2906. bool isUse = HandleUse(I, Pat, InstInputs);
  2907. if (!isUse && Pat->getTransformFn())
  2908. I.error("Cannot specify a transform function for a non-input value!");
  2909. return;
  2910. }
  2911. if (Pat->getOperator()->getName() == "implicit") {
  2912. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  2913. TreePatternNode *Dest = Pat->getChild(i);
  2914. if (!Dest->isLeaf())
  2915. I.error("implicitly defined value should be a register!");
  2916. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2917. if (!Val || !Val->getDef()->isSubClassOf("Register"))
  2918. I.error("implicitly defined value should be a register!");
  2919. InstImpResults.push_back(Val->getDef());
  2920. }
  2921. return;
  2922. }
  2923. if (Pat->getOperator()->getName() != "set") {
  2924. // If this is not a set, verify that the children nodes are not void typed,
  2925. // and recurse.
  2926. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  2927. if (Pat->getChild(i)->getNumTypes() == 0)
  2928. I.error("Cannot have void nodes inside of patterns!");
  2929. FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
  2930. InstResults, InstImpResults);
  2931. }
  2932. // If this is a non-leaf node with no children, treat it basically as if
  2933. // it were a leaf. This handles nodes like (imm).
  2934. bool isUse = HandleUse(I, Pat, InstInputs);
  2935. if (!isUse && Pat->getTransformFn())
  2936. I.error("Cannot specify a transform function for a non-input value!");
  2937. return;
  2938. }
  2939. // Otherwise, this is a set, validate and collect instruction results.
  2940. if (Pat->getNumChildren() == 0)
  2941. I.error("set requires operands!");
  2942. if (Pat->getTransformFn())
  2943. I.error("Cannot specify a transform function on a set node!");
  2944. // Check the set destinations.
  2945. unsigned NumDests = Pat->getNumChildren()-1;
  2946. for (unsigned i = 0; i != NumDests; ++i) {
  2947. TreePatternNodePtr Dest = Pat->getChildShared(i);
  2948. // For set destinations we also must resolve fragments here.
  2949. TreePattern DestPattern(I.getRecord(), Dest, false, *this);
  2950. DestPattern.InlinePatternFragments();
  2951. DestPattern.InferAllTypes();
  2952. Dest = DestPattern.getOnlyTree();
  2953. if (!Dest->isLeaf())
  2954. I.error("set destination should be a register!");
  2955. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2956. if (!Val) {
  2957. I.error("set destination should be a register!");
  2958. continue;
  2959. }
  2960. if (Val->getDef()->isSubClassOf("RegisterClass") ||
  2961. Val->getDef()->isSubClassOf("ValueType") ||
  2962. Val->getDef()->isSubClassOf("RegisterOperand") ||
  2963. Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
  2964. if (Dest->getName().empty())
  2965. I.error("set destination must have a name!");
  2966. if (InstResults.count(Dest->getName()))
  2967. I.error("cannot set '" + Dest->getName() + "' multiple times");
  2968. InstResults[Dest->getName()] = Dest;
  2969. } else if (Val->getDef()->isSubClassOf("Register")) {
  2970. InstImpResults.push_back(Val->getDef());
  2971. } else {
  2972. I.error("set destination should be a register!");
  2973. }
  2974. }
  2975. // Verify and collect info from the computation.
  2976. FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
  2977. InstResults, InstImpResults);
  2978. }
  2979. //===----------------------------------------------------------------------===//
  2980. // Instruction Analysis
  2981. //===----------------------------------------------------------------------===//
  2982. class InstAnalyzer {
  2983. const CodeGenDAGPatterns &CDP;
  2984. public:
  2985. bool hasSideEffects;
  2986. bool mayStore;
  2987. bool mayLoad;
  2988. bool isBitcast;
  2989. bool isVariadic;
  2990. bool hasChain;
  2991. InstAnalyzer(const CodeGenDAGPatterns &cdp)
  2992. : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
  2993. isBitcast(false), isVariadic(false), hasChain(false) {}
  2994. void Analyze(const PatternToMatch &Pat) {
  2995. const TreePatternNode *N = Pat.getSrcPattern();
  2996. AnalyzeNode(N);
  2997. // These properties are detected only on the root node.
  2998. isBitcast = IsNodeBitcast(N);
  2999. }
  3000. private:
  3001. bool IsNodeBitcast(const TreePatternNode *N) const {
  3002. if (hasSideEffects || mayLoad || mayStore || isVariadic)
  3003. return false;
  3004. if (N->isLeaf())
  3005. return false;
  3006. if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
  3007. return false;
  3008. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
  3009. if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
  3010. return false;
  3011. return OpInfo.getEnumName() == "ISD::BITCAST";
  3012. }
  3013. public:
  3014. void AnalyzeNode(const TreePatternNode *N) {
  3015. if (N->isLeaf()) {
  3016. if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
  3017. Record *LeafRec = DI->getDef();
  3018. // Handle ComplexPattern leaves.
  3019. if (LeafRec->isSubClassOf("ComplexPattern")) {
  3020. const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
  3021. if (CP.hasProperty(SDNPMayStore)) mayStore = true;
  3022. if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
  3023. if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  3024. }
  3025. }
  3026. return;
  3027. }
  3028. // Analyze children.
  3029. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3030. AnalyzeNode(N->getChild(i));
  3031. // Notice properties of the node.
  3032. if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
  3033. if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
  3034. if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
  3035. if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
  3036. if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
  3037. if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
  3038. // If this is an intrinsic, analyze it.
  3039. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
  3040. mayLoad = true;// These may load memory.
  3041. if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
  3042. mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
  3043. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
  3044. IntInfo->hasSideEffects)
  3045. // ReadWriteMem intrinsics can have other strange effects.
  3046. hasSideEffects = true;
  3047. }
  3048. }
  3049. };
  3050. static bool InferFromPattern(CodeGenInstruction &InstInfo,
  3051. const InstAnalyzer &PatInfo,
  3052. Record *PatDef) {
  3053. bool Error = false;
  3054. // Remember where InstInfo got its flags.
  3055. if (InstInfo.hasUndefFlags())
  3056. InstInfo.InferredFrom = PatDef;
  3057. // Check explicitly set flags for consistency.
  3058. if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
  3059. !InstInfo.hasSideEffects_Unset) {
  3060. // Allow explicitly setting hasSideEffects = 1 on instructions, even when
  3061. // the pattern has no side effects. That could be useful for div/rem
  3062. // instructions that may trap.
  3063. if (!InstInfo.hasSideEffects) {
  3064. Error = true;
  3065. PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
  3066. Twine(InstInfo.hasSideEffects));
  3067. }
  3068. }
  3069. if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
  3070. Error = true;
  3071. PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
  3072. Twine(InstInfo.mayStore));
  3073. }
  3074. if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
  3075. // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
  3076. // Some targets translate immediates to loads.
  3077. if (!InstInfo.mayLoad) {
  3078. Error = true;
  3079. PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
  3080. Twine(InstInfo.mayLoad));
  3081. }
  3082. }
  3083. // Transfer inferred flags.
  3084. InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
  3085. InstInfo.mayStore |= PatInfo.mayStore;
  3086. InstInfo.mayLoad |= PatInfo.mayLoad;
  3087. // These flags are silently added without any verification.
  3088. // FIXME: To match historical behavior of TableGen, for now add those flags
  3089. // only when we're inferring from the primary instruction pattern.
  3090. if (PatDef->isSubClassOf("Instruction")) {
  3091. InstInfo.isBitcast |= PatInfo.isBitcast;
  3092. InstInfo.hasChain |= PatInfo.hasChain;
  3093. InstInfo.hasChain_Inferred = true;
  3094. }
  3095. // Don't infer isVariadic. This flag means something different on SDNodes and
  3096. // instructions. For example, a CALL SDNode is variadic because it has the
  3097. // call arguments as operands, but a CALL instruction is not variadic - it
  3098. // has argument registers as implicit, not explicit uses.
  3099. return Error;
  3100. }
  3101. /// hasNullFragReference - Return true if the DAG has any reference to the
  3102. /// null_frag operator.
  3103. static bool hasNullFragReference(DagInit *DI) {
  3104. DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
  3105. if (!OpDef) return false;
  3106. Record *Operator = OpDef->getDef();
  3107. // If this is the null fragment, return true.
  3108. if (Operator->getName() == "null_frag") return true;
  3109. // If any of the arguments reference the null fragment, return true.
  3110. for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
  3111. if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))
  3112. if (Arg->getDef()->getName() == "null_frag")
  3113. return true;
  3114. DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
  3115. if (Arg && hasNullFragReference(Arg))
  3116. return true;
  3117. }
  3118. return false;
  3119. }
  3120. /// hasNullFragReference - Return true if any DAG in the list references
  3121. /// the null_frag operator.
  3122. static bool hasNullFragReference(ListInit *LI) {
  3123. for (Init *I : LI->getValues()) {
  3124. DagInit *DI = dyn_cast<DagInit>(I);
  3125. assert(DI && "non-dag in an instruction Pattern list?!");
  3126. if (hasNullFragReference(DI))
  3127. return true;
  3128. }
  3129. return false;
  3130. }
  3131. /// Get all the instructions in a tree.
  3132. static void
  3133. getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
  3134. if (Tree->isLeaf())
  3135. return;
  3136. if (Tree->getOperator()->isSubClassOf("Instruction"))
  3137. Instrs.push_back(Tree->getOperator());
  3138. for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
  3139. getInstructionsInTree(Tree->getChild(i), Instrs);
  3140. }
  3141. /// Check the class of a pattern leaf node against the instruction operand it
  3142. /// represents.
  3143. static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
  3144. Record *Leaf) {
  3145. if (OI.Rec == Leaf)
  3146. return true;
  3147. // Allow direct value types to be used in instruction set patterns.
  3148. // The type will be checked later.
  3149. if (Leaf->isSubClassOf("ValueType"))
  3150. return true;
  3151. // Patterns can also be ComplexPattern instances.
  3152. if (Leaf->isSubClassOf("ComplexPattern"))
  3153. return true;
  3154. return false;
  3155. }
  3156. void CodeGenDAGPatterns::parseInstructionPattern(
  3157. CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
  3158. assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
  3159. // Parse the instruction.
  3160. TreePattern I(CGI.TheDef, Pat, true, *this);
  3161. // InstInputs - Keep track of all of the inputs of the instruction, along
  3162. // with the record they are declared as.
  3163. std::map<std::string, TreePatternNodePtr> InstInputs;
  3164. // InstResults - Keep track of all the virtual registers that are 'set'
  3165. // in the instruction, including what reg class they are.
  3166. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  3167. InstResults;
  3168. std::vector<Record*> InstImpResults;
  3169. // Verify that the top-level forms in the instruction are of void type, and
  3170. // fill in the InstResults map.
  3171. SmallString<32> TypesString;
  3172. for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
  3173. TypesString.clear();
  3174. TreePatternNodePtr Pat = I.getTree(j);
  3175. if (Pat->getNumTypes() != 0) {
  3176. raw_svector_ostream OS(TypesString);
  3177. for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
  3178. if (k > 0)
  3179. OS << ", ";
  3180. Pat->getExtType(k).writeToStream(OS);
  3181. }
  3182. I.error("Top-level forms in instruction pattern should have"
  3183. " void types, has types " +
  3184. OS.str());
  3185. }
  3186. // Find inputs and outputs, and verify the structure of the uses/defs.
  3187. FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
  3188. InstImpResults);
  3189. }
  3190. // Now that we have inputs and outputs of the pattern, inspect the operands
  3191. // list for the instruction. This determines the order that operands are
  3192. // added to the machine instruction the node corresponds to.
  3193. unsigned NumResults = InstResults.size();
  3194. // Parse the operands list from the (ops) list, validating it.
  3195. assert(I.getArgList().empty() && "Args list should still be empty here!");
  3196. // Check that all of the results occur first in the list.
  3197. std::vector<Record*> Results;
  3198. std::vector<unsigned> ResultIndices;
  3199. SmallVector<TreePatternNodePtr, 2> ResNodes;
  3200. for (unsigned i = 0; i != NumResults; ++i) {
  3201. if (i == CGI.Operands.size()) {
  3202. const std::string &OpName =
  3203. llvm::find_if(
  3204. InstResults,
  3205. [](const std::pair<std::string, TreePatternNodePtr> &P) {
  3206. return P.second;
  3207. })
  3208. ->first;
  3209. I.error("'" + OpName + "' set but does not appear in operand list!");
  3210. }
  3211. const std::string &OpName = CGI.Operands[i].Name;
  3212. // Check that it exists in InstResults.
  3213. auto InstResultIter = InstResults.find(OpName);
  3214. if (InstResultIter == InstResults.end() || !InstResultIter->second)
  3215. I.error("Operand $" + OpName + " does not exist in operand list!");
  3216. TreePatternNodePtr RNode = InstResultIter->second;
  3217. Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
  3218. ResNodes.push_back(std::move(RNode));
  3219. if (!R)
  3220. I.error("Operand $" + OpName + " should be a set destination: all "
  3221. "outputs must occur before inputs in operand list!");
  3222. if (!checkOperandClass(CGI.Operands[i], R))
  3223. I.error("Operand $" + OpName + " class mismatch!");
  3224. // Remember the return type.
  3225. Results.push_back(CGI.Operands[i].Rec);
  3226. // Remember the result index.
  3227. ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
  3228. // Okay, this one checks out.
  3229. InstResultIter->second = nullptr;
  3230. }
  3231. // Loop over the inputs next.
  3232. std::vector<TreePatternNodePtr> ResultNodeOperands;
  3233. std::vector<Record*> Operands;
  3234. for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
  3235. CGIOperandList::OperandInfo &Op = CGI.Operands[i];
  3236. const std::string &OpName = Op.Name;
  3237. if (OpName.empty())
  3238. I.error("Operand #" + Twine(i) + " in operands list has no name!");
  3239. if (!InstInputs.count(OpName)) {
  3240. // If this is an operand with a DefaultOps set filled in, we can ignore
  3241. // this. When we codegen it, we will do so as always executed.
  3242. if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
  3243. // Does it have a non-empty DefaultOps field? If so, ignore this
  3244. // operand.
  3245. if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
  3246. continue;
  3247. }
  3248. I.error("Operand $" + OpName +
  3249. " does not appear in the instruction pattern");
  3250. }
  3251. TreePatternNodePtr InVal = InstInputs[OpName];
  3252. InstInputs.erase(OpName); // It occurred, remove from map.
  3253. if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
  3254. Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
  3255. if (!checkOperandClass(Op, InRec))
  3256. I.error("Operand $" + OpName + "'s register class disagrees"
  3257. " between the operand and pattern");
  3258. }
  3259. Operands.push_back(Op.Rec);
  3260. // Construct the result for the dest-pattern operand list.
  3261. TreePatternNodePtr OpNode = InVal->clone();
  3262. // No predicate is useful on the result.
  3263. OpNode->clearPredicateCalls();
  3264. // Promote the xform function to be an explicit node if set.
  3265. if (Record *Xform = OpNode->getTransformFn()) {
  3266. OpNode->setTransformFn(nullptr);
  3267. std::vector<TreePatternNodePtr> Children;
  3268. Children.push_back(OpNode);
  3269. OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
  3270. OpNode->getNumTypes());
  3271. }
  3272. ResultNodeOperands.push_back(std::move(OpNode));
  3273. }
  3274. if (!InstInputs.empty())
  3275. I.error("Input operand $" + InstInputs.begin()->first +
  3276. " occurs in pattern but not in operands list!");
  3277. TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
  3278. I.getRecord(), std::move(ResultNodeOperands),
  3279. GetNumNodeResults(I.getRecord(), *this));
  3280. // Copy fully inferred output node types to instruction result pattern.
  3281. for (unsigned i = 0; i != NumResults; ++i) {
  3282. assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
  3283. ResultPattern->setType(i, ResNodes[i]->getExtType(0));
  3284. ResultPattern->setResultIndex(i, ResultIndices[i]);
  3285. }
  3286. // FIXME: Assume only the first tree is the pattern. The others are clobber
  3287. // nodes.
  3288. TreePatternNodePtr Pattern = I.getTree(0);
  3289. TreePatternNodePtr SrcPattern;
  3290. if (Pattern->getOperator()->getName() == "set") {
  3291. SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
  3292. } else{
  3293. // Not a set (store or something?)
  3294. SrcPattern = Pattern;
  3295. }
  3296. // Create and insert the instruction.
  3297. // FIXME: InstImpResults should not be part of DAGInstruction.
  3298. Record *R = I.getRecord();
  3299. DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
  3300. std::forward_as_tuple(Results, Operands, InstImpResults,
  3301. SrcPattern, ResultPattern));
  3302. LLVM_DEBUG(I.dump());
  3303. }
  3304. /// ParseInstructions - Parse all of the instructions, inlining and resolving
  3305. /// any fragments involved. This populates the Instructions list with fully
  3306. /// resolved instructions.
  3307. void CodeGenDAGPatterns::ParseInstructions() {
  3308. std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
  3309. for (Record *Instr : Instrs) {
  3310. ListInit *LI = nullptr;
  3311. if (isa<ListInit>(Instr->getValueInit("Pattern")))
  3312. LI = Instr->getValueAsListInit("Pattern");
  3313. // If there is no pattern, only collect minimal information about the
  3314. // instruction for its operand list. We have to assume that there is one
  3315. // result, as we have no detailed info. A pattern which references the
  3316. // null_frag operator is as-if no pattern were specified. Normally this
  3317. // is from a multiclass expansion w/ a SDPatternOperator passed in as
  3318. // null_frag.
  3319. if (!LI || LI->empty() || hasNullFragReference(LI)) {
  3320. std::vector<Record*> Results;
  3321. std::vector<Record*> Operands;
  3322. CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3323. if (InstInfo.Operands.size() != 0) {
  3324. for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
  3325. Results.push_back(InstInfo.Operands[j].Rec);
  3326. // The rest are inputs.
  3327. for (unsigned j = InstInfo.Operands.NumDefs,
  3328. e = InstInfo.Operands.size(); j < e; ++j)
  3329. Operands.push_back(InstInfo.Operands[j].Rec);
  3330. }
  3331. // Create and insert the instruction.
  3332. std::vector<Record*> ImpResults;
  3333. Instructions.insert(std::make_pair(Instr,
  3334. DAGInstruction(Results, Operands, ImpResults)));
  3335. continue; // no pattern.
  3336. }
  3337. CodeGenInstruction &CGI = Target.getInstruction(Instr);
  3338. parseInstructionPattern(CGI, LI, Instructions);
  3339. }
  3340. // If we can, convert the instructions to be patterns that are matched!
  3341. for (auto &Entry : Instructions) {
  3342. Record *Instr = Entry.first;
  3343. DAGInstruction &TheInst = Entry.second;
  3344. TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
  3345. TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
  3346. if (SrcPattern && ResultPattern) {
  3347. TreePattern Pattern(Instr, SrcPattern, true, *this);
  3348. TreePattern Result(Instr, ResultPattern, false, *this);
  3349. ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
  3350. }
  3351. }
  3352. }
  3353. typedef std::pair<TreePatternNode *, unsigned> NameRecord;
  3354. static void FindNames(TreePatternNode *P,
  3355. std::map<std::string, NameRecord> &Names,
  3356. TreePattern *PatternTop) {
  3357. if (!P->getName().empty()) {
  3358. NameRecord &Rec = Names[P->getName()];
  3359. // If this is the first instance of the name, remember the node.
  3360. if (Rec.second++ == 0)
  3361. Rec.first = P;
  3362. else if (Rec.first->getExtTypes() != P->getExtTypes())
  3363. PatternTop->error("repetition of value: $" + P->getName() +
  3364. " where different uses have different types!");
  3365. }
  3366. if (!P->isLeaf()) {
  3367. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
  3368. FindNames(P->getChild(i), Names, PatternTop);
  3369. }
  3370. }
  3371. std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
  3372. std::vector<Predicate> Preds;
  3373. for (Init *I : L->getValues()) {
  3374. if (DefInit *Pred = dyn_cast<DefInit>(I))
  3375. Preds.push_back(Pred->getDef());
  3376. else
  3377. llvm_unreachable("Non-def on the list");
  3378. }
  3379. // Sort so that different orders get canonicalized to the same string.
  3380. llvm::sort(Preds);
  3381. return Preds;
  3382. }
  3383. void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
  3384. PatternToMatch &&PTM) {
  3385. // Do some sanity checking on the pattern we're about to match.
  3386. std::string Reason;
  3387. if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
  3388. PrintWarning(Pattern->getRecord()->getLoc(),
  3389. Twine("Pattern can never match: ") + Reason);
  3390. return;
  3391. }
  3392. // If the source pattern's root is a complex pattern, that complex pattern
  3393. // must specify the nodes it can potentially match.
  3394. if (const ComplexPattern *CP =
  3395. PTM.getSrcPattern()->getComplexPatternInfo(*this))
  3396. if (CP->getRootNodes().empty())
  3397. Pattern->error("ComplexPattern at root must specify list of opcodes it"
  3398. " could match");
  3399. // Find all of the named values in the input and output, ensure they have the
  3400. // same type.
  3401. std::map<std::string, NameRecord> SrcNames, DstNames;
  3402. FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
  3403. FindNames(PTM.getDstPattern(), DstNames, Pattern);
  3404. // Scan all of the named values in the destination pattern, rejecting them if
  3405. // they don't exist in the input pattern.
  3406. for (const auto &Entry : DstNames) {
  3407. if (SrcNames[Entry.first].first == nullptr)
  3408. Pattern->error("Pattern has input without matching name in output: $" +
  3409. Entry.first);
  3410. }
  3411. // Scan all of the named values in the source pattern, rejecting them if the
  3412. // name isn't used in the dest, and isn't used to tie two values together.
  3413. for (const auto &Entry : SrcNames)
  3414. if (DstNames[Entry.first].first == nullptr &&
  3415. SrcNames[Entry.first].second == 1)
  3416. Pattern->error("Pattern has dead named input: $" + Entry.first);
  3417. PatternsToMatch.push_back(PTM);
  3418. }
  3419. void CodeGenDAGPatterns::InferInstructionFlags() {
  3420. ArrayRef<const CodeGenInstruction*> Instructions =
  3421. Target.getInstructionsByEnumValue();
  3422. unsigned Errors = 0;
  3423. // Try to infer flags from all patterns in PatternToMatch. These include
  3424. // both the primary instruction patterns (which always come first) and
  3425. // patterns defined outside the instruction.
  3426. for (const PatternToMatch &PTM : ptms()) {
  3427. // We can only infer from single-instruction patterns, otherwise we won't
  3428. // know which instruction should get the flags.
  3429. SmallVector<Record*, 8> PatInstrs;
  3430. getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
  3431. if (PatInstrs.size() != 1)
  3432. continue;
  3433. // Get the single instruction.
  3434. CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
  3435. // Only infer properties from the first pattern. We'll verify the others.
  3436. if (InstInfo.InferredFrom)
  3437. continue;
  3438. InstAnalyzer PatInfo(*this);
  3439. PatInfo.Analyze(PTM);
  3440. Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
  3441. }
  3442. if (Errors)
  3443. PrintFatalError("pattern conflicts");
  3444. // If requested by the target, guess any undefined properties.
  3445. if (Target.guessInstructionProperties()) {
  3446. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  3447. CodeGenInstruction *InstInfo =
  3448. const_cast<CodeGenInstruction *>(Instructions[i]);
  3449. if (InstInfo->InferredFrom)
  3450. continue;
  3451. // The mayLoad and mayStore flags default to false.
  3452. // Conservatively assume hasSideEffects if it wasn't explicit.
  3453. if (InstInfo->hasSideEffects_Unset)
  3454. InstInfo->hasSideEffects = true;
  3455. }
  3456. return;
  3457. }
  3458. // Complain about any flags that are still undefined.
  3459. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  3460. CodeGenInstruction *InstInfo =
  3461. const_cast<CodeGenInstruction *>(Instructions[i]);
  3462. if (InstInfo->InferredFrom)
  3463. continue;
  3464. if (InstInfo->hasSideEffects_Unset)
  3465. PrintError(InstInfo->TheDef->getLoc(),
  3466. "Can't infer hasSideEffects from patterns");
  3467. if (InstInfo->mayStore_Unset)
  3468. PrintError(InstInfo->TheDef->getLoc(),
  3469. "Can't infer mayStore from patterns");
  3470. if (InstInfo->mayLoad_Unset)
  3471. PrintError(InstInfo->TheDef->getLoc(),
  3472. "Can't infer mayLoad from patterns");
  3473. }
  3474. }
  3475. /// Verify instruction flags against pattern node properties.
  3476. void CodeGenDAGPatterns::VerifyInstructionFlags() {
  3477. unsigned Errors = 0;
  3478. for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
  3479. const PatternToMatch &PTM = *I;
  3480. SmallVector<Record*, 8> Instrs;
  3481. getInstructionsInTree(PTM.getDstPattern(), Instrs);
  3482. if (Instrs.empty())
  3483. continue;
  3484. // Count the number of instructions with each flag set.
  3485. unsigned NumSideEffects = 0;
  3486. unsigned NumStores = 0;
  3487. unsigned NumLoads = 0;
  3488. for (const Record *Instr : Instrs) {
  3489. const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3490. NumSideEffects += InstInfo.hasSideEffects;
  3491. NumStores += InstInfo.mayStore;
  3492. NumLoads += InstInfo.mayLoad;
  3493. }
  3494. // Analyze the source pattern.
  3495. InstAnalyzer PatInfo(*this);
  3496. PatInfo.Analyze(PTM);
  3497. // Collect error messages.
  3498. SmallVector<std::string, 4> Msgs;
  3499. // Check for missing flags in the output.
  3500. // Permit extra flags for now at least.
  3501. if (PatInfo.hasSideEffects && !NumSideEffects)
  3502. Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
  3503. // Don't verify store flags on instructions with side effects. At least for
  3504. // intrinsics, side effects implies mayStore.
  3505. if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
  3506. Msgs.push_back("pattern may store, but mayStore isn't set");
  3507. // Similarly, mayStore implies mayLoad on intrinsics.
  3508. if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
  3509. Msgs.push_back("pattern may load, but mayLoad isn't set");
  3510. // Print error messages.
  3511. if (Msgs.empty())
  3512. continue;
  3513. ++Errors;
  3514. for (const std::string &Msg : Msgs)
  3515. PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
  3516. (Instrs.size() == 1 ?
  3517. "instruction" : "output instructions"));
  3518. // Provide the location of the relevant instruction definitions.
  3519. for (const Record *Instr : Instrs) {
  3520. if (Instr != PTM.getSrcRecord())
  3521. PrintError(Instr->getLoc(), "defined here");
  3522. const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
  3523. if (InstInfo.InferredFrom &&
  3524. InstInfo.InferredFrom != InstInfo.TheDef &&
  3525. InstInfo.InferredFrom != PTM.getSrcRecord())
  3526. PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
  3527. }
  3528. }
  3529. if (Errors)
  3530. PrintFatalError("Errors in DAG patterns");
  3531. }
  3532. /// Given a pattern result with an unresolved type, see if we can find one
  3533. /// instruction with an unresolved result type. Force this result type to an
  3534. /// arbitrary element if it's possible types to converge results.
  3535. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
  3536. if (N->isLeaf())
  3537. return false;
  3538. // Analyze children.
  3539. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3540. if (ForceArbitraryInstResultType(N->getChild(i), TP))
  3541. return true;
  3542. if (!N->getOperator()->isSubClassOf("Instruction"))
  3543. return false;
  3544. // If this type is already concrete or completely unknown we can't do
  3545. // anything.
  3546. TypeInfer &TI = TP.getInfer();
  3547. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
  3548. if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
  3549. continue;
  3550. // Otherwise, force its type to an arbitrary choice.
  3551. if (TI.forceArbitrary(N->getExtType(i)))
  3552. return true;
  3553. }
  3554. return false;
  3555. }
  3556. // Promote xform function to be an explicit node wherever set.
  3557. static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
  3558. if (Record *Xform = N->getTransformFn()) {
  3559. N->setTransformFn(nullptr);
  3560. std::vector<TreePatternNodePtr> Children;
  3561. Children.push_back(PromoteXForms(N));
  3562. return std::make_shared<TreePatternNode>(Xform, std::move(Children),
  3563. N->getNumTypes());
  3564. }
  3565. if (!N->isLeaf())
  3566. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  3567. TreePatternNodePtr Child = N->getChildShared(i);
  3568. N->setChild(i, PromoteXForms(Child));
  3569. }
  3570. return N;
  3571. }
  3572. void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
  3573. TreePattern &Pattern, TreePattern &Result,
  3574. const std::vector<Record *> &InstImpResults) {
  3575. // Inline pattern fragments and expand multiple alternatives.
  3576. Pattern.InlinePatternFragments();
  3577. Result.InlinePatternFragments();
  3578. if (Result.getNumTrees() != 1)
  3579. Result.error("Cannot use multi-alternative fragments in result pattern!");
  3580. // Infer types.
  3581. bool IterateInference;
  3582. bool InferredAllPatternTypes, InferredAllResultTypes;
  3583. do {
  3584. // Infer as many types as possible. If we cannot infer all of them, we
  3585. // can never do anything with this pattern: report it to the user.
  3586. InferredAllPatternTypes =
  3587. Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
  3588. // Infer as many types as possible. If we cannot infer all of them, we
  3589. // can never do anything with this pattern: report it to the user.
  3590. InferredAllResultTypes =
  3591. Result.InferAllTypes(&Pattern.getNamedNodesMap());
  3592. IterateInference = false;
  3593. // Apply the type of the result to the source pattern. This helps us
  3594. // resolve cases where the input type is known to be a pointer type (which
  3595. // is considered resolved), but the result knows it needs to be 32- or
  3596. // 64-bits. Infer the other way for good measure.
  3597. for (auto T : Pattern.getTrees())
  3598. for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
  3599. T->getNumTypes());
  3600. i != e; ++i) {
  3601. IterateInference |= T->UpdateNodeType(
  3602. i, Result.getOnlyTree()->getExtType(i), Result);
  3603. IterateInference |= Result.getOnlyTree()->UpdateNodeType(
  3604. i, T->getExtType(i), Result);
  3605. }
  3606. // If our iteration has converged and the input pattern's types are fully
  3607. // resolved but the result pattern is not fully resolved, we may have a
  3608. // situation where we have two instructions in the result pattern and
  3609. // the instructions require a common register class, but don't care about
  3610. // what actual MVT is used. This is actually a bug in our modelling:
  3611. // output patterns should have register classes, not MVTs.
  3612. //
  3613. // In any case, to handle this, we just go through and disambiguate some
  3614. // arbitrary types to the result pattern's nodes.
  3615. if (!IterateInference && InferredAllPatternTypes &&
  3616. !InferredAllResultTypes)
  3617. IterateInference =
  3618. ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
  3619. } while (IterateInference);
  3620. // Verify that we inferred enough types that we can do something with the
  3621. // pattern and result. If these fire the user has to add type casts.
  3622. if (!InferredAllPatternTypes)
  3623. Pattern.error("Could not infer all types in pattern!");
  3624. if (!InferredAllResultTypes) {
  3625. Pattern.dump();
  3626. Result.error("Could not infer all types in pattern result!");
  3627. }
  3628. // Promote xform function to be an explicit node wherever set.
  3629. TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
  3630. TreePattern Temp(Result.getRecord(), DstShared, false, *this);
  3631. Temp.InferAllTypes();
  3632. ListInit *Preds = TheDef->getValueAsListInit("Predicates");
  3633. int Complexity = TheDef->getValueAsInt("AddedComplexity");
  3634. if (PatternRewriter)
  3635. PatternRewriter(&Pattern);
  3636. // A pattern may end up with an "impossible" type, i.e. a situation
  3637. // where all types have been eliminated for some node in this pattern.
  3638. // This could occur for intrinsics that only make sense for a specific
  3639. // value type, and use a specific register class. If, for some mode,
  3640. // that register class does not accept that type, the type inference
  3641. // will lead to a contradiction, which is not an error however, but
  3642. // a sign that this pattern will simply never match.
  3643. if (Temp.getOnlyTree()->hasPossibleType())
  3644. for (auto T : Pattern.getTrees())
  3645. if (T->hasPossibleType())
  3646. AddPatternToMatch(&Pattern,
  3647. PatternToMatch(TheDef, makePredList(Preds),
  3648. T, Temp.getOnlyTree(),
  3649. InstImpResults, Complexity,
  3650. TheDef->getID()));
  3651. }
  3652. void CodeGenDAGPatterns::ParsePatterns() {
  3653. std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
  3654. for (Record *CurPattern : Patterns) {
  3655. DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
  3656. // If the pattern references the null_frag, there's nothing to do.
  3657. if (hasNullFragReference(Tree))
  3658. continue;
  3659. TreePattern Pattern(CurPattern, Tree, true, *this);
  3660. ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
  3661. if (LI->empty()) continue; // no pattern.
  3662. // Parse the instruction.
  3663. TreePattern Result(CurPattern, LI, false, *this);
  3664. if (Result.getNumTrees() != 1)
  3665. Result.error("Cannot handle instructions producing instructions "
  3666. "with temporaries yet!");
  3667. // Validate that the input pattern is correct.
  3668. std::map<std::string, TreePatternNodePtr> InstInputs;
  3669. MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
  3670. InstResults;
  3671. std::vector<Record*> InstImpResults;
  3672. for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
  3673. FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
  3674. InstResults, InstImpResults);
  3675. ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
  3676. }
  3677. }
  3678. static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
  3679. for (const TypeSetByHwMode &VTS : N->getExtTypes())
  3680. for (const auto &I : VTS)
  3681. Modes.insert(I.first);
  3682. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3683. collectModes(Modes, N->getChild(i));
  3684. }
  3685. void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
  3686. const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
  3687. std::map<unsigned,std::vector<Predicate>> ModeChecks;
  3688. std::vector<PatternToMatch> Copy = PatternsToMatch;
  3689. PatternsToMatch.clear();
  3690. auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
  3691. TreePatternNodePtr NewSrc = P.SrcPattern->clone();
  3692. TreePatternNodePtr NewDst = P.DstPattern->clone();
  3693. if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
  3694. return;
  3695. }
  3696. std::vector<Predicate> Preds = P.Predicates;
  3697. const std::vector<Predicate> &MC = ModeChecks[Mode];
  3698. llvm::append_range(Preds, MC);
  3699. PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
  3700. std::move(NewDst), P.getDstRegs(),
  3701. P.getAddedComplexity(), Record::getNewUID(),
  3702. Mode);
  3703. };
  3704. for (PatternToMatch &P : Copy) {
  3705. TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
  3706. if (P.SrcPattern->hasProperTypeByHwMode())
  3707. SrcP = P.SrcPattern;
  3708. if (P.DstPattern->hasProperTypeByHwMode())
  3709. DstP = P.DstPattern;
  3710. if (!SrcP && !DstP) {
  3711. PatternsToMatch.push_back(P);
  3712. continue;
  3713. }
  3714. std::set<unsigned> Modes;
  3715. if (SrcP)
  3716. collectModes(Modes, SrcP.get());
  3717. if (DstP)
  3718. collectModes(Modes, DstP.get());
  3719. // The predicate for the default mode needs to be constructed for each
  3720. // pattern separately.
  3721. // Since not all modes must be present in each pattern, if a mode m is
  3722. // absent, then there is no point in constructing a check for m. If such
  3723. // a check was created, it would be equivalent to checking the default
  3724. // mode, except not all modes' predicates would be a part of the checking
  3725. // code. The subsequently generated check for the default mode would then
  3726. // have the exact same patterns, but a different predicate code. To avoid
  3727. // duplicated patterns with different predicate checks, construct the
  3728. // default check as a negation of all predicates that are actually present
  3729. // in the source/destination patterns.
  3730. std::vector<Predicate> DefaultPred;
  3731. for (unsigned M : Modes) {
  3732. if (M == DefaultMode)
  3733. continue;
  3734. if (ModeChecks.find(M) != ModeChecks.end())
  3735. continue;
  3736. // Fill the map entry for this mode.
  3737. const HwMode &HM = CGH.getMode(M);
  3738. ModeChecks[M].emplace_back(Predicate(HM.Features, true));
  3739. // Add negations of the HM's predicates to the default predicate.
  3740. DefaultPred.emplace_back(Predicate(HM.Features, false));
  3741. }
  3742. for (unsigned M : Modes) {
  3743. if (M == DefaultMode)
  3744. continue;
  3745. AppendPattern(P, M);
  3746. }
  3747. bool HasDefault = Modes.count(DefaultMode);
  3748. if (HasDefault)
  3749. AppendPattern(P, DefaultMode);
  3750. }
  3751. }
  3752. /// Dependent variable map for CodeGenDAGPattern variant generation
  3753. typedef StringMap<int> DepVarMap;
  3754. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  3755. if (N->isLeaf()) {
  3756. if (N->hasName() && isa<DefInit>(N->getLeafValue()))
  3757. DepMap[N->getName()]++;
  3758. } else {
  3759. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  3760. FindDepVarsOf(N->getChild(i), DepMap);
  3761. }
  3762. }
  3763. /// Find dependent variables within child patterns
  3764. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  3765. DepVarMap depcounts;
  3766. FindDepVarsOf(N, depcounts);
  3767. for (const auto &Pair : depcounts) {
  3768. if (Pair.getValue() > 1)
  3769. DepVars.insert(Pair.getKey());
  3770. }
  3771. }
  3772. #ifndef NDEBUG
  3773. /// Dump the dependent variable set:
  3774. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  3775. if (DepVars.empty()) {
  3776. LLVM_DEBUG(errs() << "<empty set>");
  3777. } else {
  3778. LLVM_DEBUG(errs() << "[ ");
  3779. for (const auto &DepVar : DepVars) {
  3780. LLVM_DEBUG(errs() << DepVar.getKey() << " ");
  3781. }
  3782. LLVM_DEBUG(errs() << "]");
  3783. }
  3784. }
  3785. #endif
  3786. /// CombineChildVariants - Given a bunch of permutations of each child of the
  3787. /// 'operator' node, put them together in all possible ways.
  3788. static void CombineChildVariants(
  3789. TreePatternNodePtr Orig,
  3790. const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
  3791. std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
  3792. const MultipleUseVarSet &DepVars) {
  3793. // Make sure that each operand has at least one variant to choose from.
  3794. for (const auto &Variants : ChildVariants)
  3795. if (Variants.empty())
  3796. return;
  3797. // The end result is an all-pairs construction of the resultant pattern.
  3798. std::vector<unsigned> Idxs;
  3799. Idxs.resize(ChildVariants.size());
  3800. bool NotDone;
  3801. do {
  3802. #ifndef NDEBUG
  3803. LLVM_DEBUG(if (!Idxs.empty()) {
  3804. errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
  3805. for (unsigned Idx : Idxs) {
  3806. errs() << Idx << " ";
  3807. }
  3808. errs() << "]\n";
  3809. });
  3810. #endif
  3811. // Create the variant and add it to the output list.
  3812. std::vector<TreePatternNodePtr> NewChildren;
  3813. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  3814. NewChildren.push_back(ChildVariants[i][Idxs[i]]);
  3815. TreePatternNodePtr R = std::make_shared<TreePatternNode>(
  3816. Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
  3817. // Copy over properties.
  3818. R->setName(Orig->getName());
  3819. R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
  3820. R->setPredicateCalls(Orig->getPredicateCalls());
  3821. R->setTransformFn(Orig->getTransformFn());
  3822. for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
  3823. R->setType(i, Orig->getExtType(i));
  3824. // If this pattern cannot match, do not include it as a variant.
  3825. std::string ErrString;
  3826. // Scan to see if this pattern has already been emitted. We can get
  3827. // duplication due to things like commuting:
  3828. // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
  3829. // which are the same pattern. Ignore the dups.
  3830. if (R->canPatternMatch(ErrString, CDP) &&
  3831. none_of(OutVariants, [&](TreePatternNodePtr Variant) {
  3832. return R->isIsomorphicTo(Variant.get(), DepVars);
  3833. }))
  3834. OutVariants.push_back(R);
  3835. // Increment indices to the next permutation by incrementing the
  3836. // indices from last index backward, e.g., generate the sequence
  3837. // [0, 0], [0, 1], [1, 0], [1, 1].
  3838. int IdxsIdx;
  3839. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  3840. if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
  3841. Idxs[IdxsIdx] = 0;
  3842. else
  3843. break;
  3844. }
  3845. NotDone = (IdxsIdx >= 0);
  3846. } while (NotDone);
  3847. }
  3848. /// CombineChildVariants - A helper function for binary operators.
  3849. ///
  3850. static void CombineChildVariants(TreePatternNodePtr Orig,
  3851. const std::vector<TreePatternNodePtr> &LHS,
  3852. const std::vector<TreePatternNodePtr> &RHS,
  3853. std::vector<TreePatternNodePtr> &OutVariants,
  3854. CodeGenDAGPatterns &CDP,
  3855. const MultipleUseVarSet &DepVars) {
  3856. std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
  3857. ChildVariants.push_back(LHS);
  3858. ChildVariants.push_back(RHS);
  3859. CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
  3860. }
  3861. static void
  3862. GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
  3863. std::vector<TreePatternNodePtr> &Children) {
  3864. assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
  3865. Record *Operator = N->getOperator();
  3866. // Only permit raw nodes.
  3867. if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
  3868. N->getTransformFn()) {
  3869. Children.push_back(N);
  3870. return;
  3871. }
  3872. if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
  3873. Children.push_back(N->getChildShared(0));
  3874. else
  3875. GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
  3876. if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
  3877. Children.push_back(N->getChildShared(1));
  3878. else
  3879. GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
  3880. }
  3881. /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
  3882. /// the (potentially recursive) pattern by using algebraic laws.
  3883. ///
  3884. static void GenerateVariantsOf(TreePatternNodePtr N,
  3885. std::vector<TreePatternNodePtr> &OutVariants,
  3886. CodeGenDAGPatterns &CDP,
  3887. const MultipleUseVarSet &DepVars) {
  3888. // We cannot permute leaves or ComplexPattern uses.
  3889. if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
  3890. OutVariants.push_back(N);
  3891. return;
  3892. }
  3893. // Look up interesting info about the node.
  3894. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
  3895. // If this node is associative, re-associate.
  3896. if (NodeInfo.hasProperty(SDNPAssociative)) {
  3897. // Re-associate by pulling together all of the linked operators
  3898. std::vector<TreePatternNodePtr> MaximalChildren;
  3899. GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
  3900. // Only handle child sizes of 3. Otherwise we'll end up trying too many
  3901. // permutations.
  3902. if (MaximalChildren.size() == 3) {
  3903. // Find the variants of all of our maximal children.
  3904. std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
  3905. GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
  3906. GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
  3907. GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
  3908. // There are only two ways we can permute the tree:
  3909. // (A op B) op C and A op (B op C)
  3910. // Within these forms, we can also permute A/B/C.
  3911. // Generate legal pair permutations of A/B/C.
  3912. std::vector<TreePatternNodePtr> ABVariants;
  3913. std::vector<TreePatternNodePtr> BAVariants;
  3914. std::vector<TreePatternNodePtr> ACVariants;
  3915. std::vector<TreePatternNodePtr> CAVariants;
  3916. std::vector<TreePatternNodePtr> BCVariants;
  3917. std::vector<TreePatternNodePtr> CBVariants;
  3918. CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
  3919. CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
  3920. CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
  3921. CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
  3922. CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
  3923. CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
  3924. // Combine those into the result: (x op x) op x
  3925. CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
  3926. CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
  3927. CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
  3928. CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
  3929. CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
  3930. CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
  3931. // Combine those into the result: x op (x op x)
  3932. CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
  3933. CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
  3934. CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
  3935. CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
  3936. CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
  3937. CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
  3938. return;
  3939. }
  3940. }
  3941. // Compute permutations of all children.
  3942. std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
  3943. ChildVariants.resize(N->getNumChildren());
  3944. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  3945. GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
  3946. // Build all permutations based on how the children were formed.
  3947. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
  3948. // If this node is commutative, consider the commuted order.
  3949. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
  3950. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  3951. assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
  3952. "Commutative but doesn't have 2 children!");
  3953. // Don't count children which are actually register references.
  3954. unsigned NC = 0;
  3955. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  3956. TreePatternNode *Child = N->getChild(i);
  3957. if (Child->isLeaf())
  3958. if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
  3959. Record *RR = DI->getDef();
  3960. if (RR->isSubClassOf("Register"))
  3961. continue;
  3962. }
  3963. NC++;
  3964. }
  3965. // Consider the commuted order.
  3966. if (isCommIntrinsic) {
  3967. // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
  3968. // operands are the commutative operands, and there might be more operands
  3969. // after those.
  3970. assert(NC >= 3 &&
  3971. "Commutative intrinsic should have at least 3 children!");
  3972. std::vector<std::vector<TreePatternNodePtr>> Variants;
  3973. Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
  3974. Variants.push_back(std::move(ChildVariants[2]));
  3975. Variants.push_back(std::move(ChildVariants[1]));
  3976. for (unsigned i = 3; i != NC; ++i)
  3977. Variants.push_back(std::move(ChildVariants[i]));
  3978. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  3979. } else if (NC == N->getNumChildren()) {
  3980. std::vector<std::vector<TreePatternNodePtr>> Variants;
  3981. Variants.push_back(std::move(ChildVariants[1]));
  3982. Variants.push_back(std::move(ChildVariants[0]));
  3983. for (unsigned i = 2; i != NC; ++i)
  3984. Variants.push_back(std::move(ChildVariants[i]));
  3985. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  3986. }
  3987. }
  3988. }
  3989. // GenerateVariants - Generate variants. For example, commutative patterns can
  3990. // match multiple ways. Add them to PatternsToMatch as well.
  3991. void CodeGenDAGPatterns::GenerateVariants() {
  3992. LLVM_DEBUG(errs() << "Generating instruction variants.\n");
  3993. // Loop over all of the patterns we've collected, checking to see if we can
  3994. // generate variants of the instruction, through the exploitation of
  3995. // identities. This permits the target to provide aggressive matching without
  3996. // the .td file having to contain tons of variants of instructions.
  3997. //
  3998. // Note that this loop adds new patterns to the PatternsToMatch list, but we
  3999. // intentionally do not reconsider these. Any variants of added patterns have
  4000. // already been added.
  4001. //
  4002. const unsigned NumOriginalPatterns = PatternsToMatch.size();
  4003. BitVector MatchedPatterns(NumOriginalPatterns);
  4004. std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
  4005. BitVector(NumOriginalPatterns));
  4006. typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
  4007. DepsAndVariants;
  4008. std::map<unsigned, DepsAndVariants> PatternsWithVariants;
  4009. // Collect patterns with more than one variant.
  4010. for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
  4011. MultipleUseVarSet DepVars;
  4012. std::vector<TreePatternNodePtr> Variants;
  4013. FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
  4014. LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
  4015. LLVM_DEBUG(DumpDepVars(DepVars));
  4016. LLVM_DEBUG(errs() << "\n");
  4017. GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
  4018. *this, DepVars);
  4019. assert(!Variants.empty() && "Must create at least original variant!");
  4020. if (Variants.size() == 1) // No additional variants for this pattern.
  4021. continue;
  4022. LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
  4023. PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
  4024. PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
  4025. // Cache matching predicates.
  4026. if (MatchedPatterns[i])
  4027. continue;
  4028. const std::vector<Predicate> &Predicates =
  4029. PatternsToMatch[i].getPredicates();
  4030. BitVector &Matches = MatchedPredicates[i];
  4031. MatchedPatterns.set(i);
  4032. Matches.set(i);
  4033. // Don't test patterns that have already been cached - it won't match.
  4034. for (unsigned p = 0; p != NumOriginalPatterns; ++p)
  4035. if (!MatchedPatterns[p])
  4036. Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
  4037. // Copy this to all the matching patterns.
  4038. for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
  4039. if (p != (int)i) {
  4040. MatchedPatterns.set(p);
  4041. MatchedPredicates[p] = Matches;
  4042. }
  4043. }
  4044. for (auto it : PatternsWithVariants) {
  4045. unsigned i = it.first;
  4046. const MultipleUseVarSet &DepVars = it.second.first;
  4047. const std::vector<TreePatternNodePtr> &Variants = it.second.second;
  4048. for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
  4049. TreePatternNodePtr Variant = Variants[v];
  4050. BitVector &Matches = MatchedPredicates[i];
  4051. LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
  4052. errs() << "\n");
  4053. // Scan to see if an instruction or explicit pattern already matches this.
  4054. bool AlreadyExists = false;
  4055. for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
  4056. // Skip if the top level predicates do not match.
  4057. if (!Matches[p])
  4058. continue;
  4059. // Check to see if this variant already exists.
  4060. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
  4061. DepVars)) {
  4062. LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
  4063. AlreadyExists = true;
  4064. break;
  4065. }
  4066. }
  4067. // If we already have it, ignore the variant.
  4068. if (AlreadyExists) continue;
  4069. // Otherwise, add it to the list of patterns we have.
  4070. PatternsToMatch.push_back(PatternToMatch(
  4071. PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
  4072. Variant, PatternsToMatch[i].getDstPatternShared(),
  4073. PatternsToMatch[i].getDstRegs(),
  4074. PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
  4075. MatchedPredicates.push_back(Matches);
  4076. // Add a new match the same as this pattern.
  4077. for (auto &P : MatchedPredicates)
  4078. P.push_back(P[i]);
  4079. }
  4080. LLVM_DEBUG(errs() << "\n");
  4081. }
  4082. }