hqlresource.cpp 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jlib.hpp"
  16. #include "hqlexpr.hpp"
  17. #include "hqlattr.hpp"
  18. #include "hqlmeta.hpp"
  19. #include "hqlutil.hpp"
  20. #include "hqlcpputil.hpp"
  21. #include "hqlthql.hpp"
  22. #include "hqlcatom.hpp"
  23. #include "hqlfold.hpp"
  24. #include "hqlcerrors.hpp"
  25. #include "hqltrans.ipp"
  26. #include "hqlpmap.hpp"
  27. #include "hqltcppc.ipp"
  28. #include "hqlttcpp.ipp"
  29. #include "hqlresource.ipp"
  30. #include "../../thorlcr/thorutil/thbufdef.hpp"
  31. #define MINIMAL_CHANGES
  32. #define MAX_INLINE_COMMON_COUNT 5
  33. //#define TRACE_RESOURCING
  34. //#define VERIFY_RESOURCING
  35. //#define SPOT_UNCONDITIONAL_CONDITIONS
  36. #define DEFAULT_LARGEMEM_BUFFER_SIZE (0x58000000) // ~ 1.4GB
  37. #define DEFAULT_MAX_SOCKETS 2000 // configurable by setting max_sockets in .ini
  38. #define DEFAULT_TOTAL_MEMORY ((1024*1024*1800)-DEFAULT_LARGEMEM_BUFFER_SIZE)
  39. #define FIXED_CLUSTER_SIZE 400
  40. #define MEM_Const_Minimal (1*1024*1024)
  41. #define DEFAULT_MAX_ACTIVITIES 100
  42. //=== The following provides information about how each kind of activity is resourced ====
  43. static void setHashResources(IHqlExpression * expr, CResources & resources, const CResourceOptions & options)
  44. {
  45. if (options.useMpForDistribute)
  46. {
  47. unsigned memneeded = MEM_Const_Minimal+resources.clusterSize*4*DISTRIBUTE_SINGLE_BUFFER_SIZE+DISTRIBUTE_PULL_BUFFER_SIZE;
  48. resources.set(RESslavememory, memneeded).set(REShashdist, 1);
  49. }
  50. else
  51. {
  52. resources.set(RESslavememory, MEM_Const_Minimal+DISTRIBUTE_PULL_BUFFER_SIZE).set(REShashdist, 1);
  53. resources.setManyToManySockets(2);
  54. }
  55. }
  56. //MORE: Use a single function to map an hqlexpression to an activity kind.
  57. void getResources(IHqlExpression * expr, CResources & resources, const CResourceOptions & options)
  58. {
  59. //MORE: What effect should a child query have? Definitely the following, but what about other resourcing?
  60. if (options.isChildQuery || queryHint(expr, lightweightAtom))
  61. {
  62. resources.setLightweight();
  63. return;
  64. }
  65. bool isLocal = isLocalActivity(expr);
  66. bool isGrouped = isGroupedActivity(expr);
  67. switch (expr->getOperator())
  68. {
  69. case no_join:
  70. case no_selfjoin:
  71. case no_denormalize:
  72. case no_denormalizegroup:
  73. if (isKeyedJoin(expr) || expr->hasProperty(_lightweight_Atom))
  74. resources.setLightweight();
  75. else if (expr->hasProperty(lookupAtom))
  76. {
  77. if (expr->hasProperty(fewAtom))
  78. {
  79. resources.setLightweight().set(RESslavememory, MEM_Const_Minimal+LOOKUPJOINL_SMART_BUFFER_SIZE);
  80. resources.setManyToMasterSockets(1);
  81. }
  82. else
  83. {
  84. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+LOOKUPJOINL_SMART_BUFFER_SIZE);
  85. resources.setManyToMasterSockets(1);
  86. }
  87. }
  88. else if (expr->hasProperty(hashAtom))
  89. {
  90. resources.setHeavyweight();
  91. setHashResources(expr, resources, options);
  92. }
  93. else
  94. {
  95. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+SORT_BUFFER_TOTAL+JOINR_SMART_BUFFER_SIZE);
  96. if (!isLocal)
  97. {
  98. #ifndef SORT_USING_MP
  99. resources.setManyToManySockets(2);
  100. #endif
  101. }
  102. }
  103. break;
  104. case no_dedup:
  105. if (isGrouped || (!expr->hasProperty(allAtom) && !expr->hasProperty(hashAtom)))
  106. {
  107. resources.setLightweight();
  108. if (!isGrouped && !isLocal)
  109. {
  110. resources.set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  111. resources.setManyToMasterSockets(1);
  112. }
  113. }
  114. else if (isLocal)
  115. {
  116. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  117. //This can't be right....
  118. //resources.setManyToMasterSockets(1);
  119. }
  120. else
  121. {
  122. //hash dedup.
  123. resources.setHeavyweight();
  124. setHashResources(expr, resources, options);
  125. }
  126. break;
  127. case no_rollup:
  128. resources.setLightweight();
  129. if (!isGrouped && !isLocal)
  130. {
  131. resources.set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  132. //MORE: Is this still correct?
  133. resources.setManyToMasterSockets(1);
  134. }
  135. break;
  136. case no_distribute:
  137. case no_keyeddistribute:
  138. resources.setLightweight();
  139. setHashResources(expr, resources, options);
  140. break;
  141. case no_shuffle:
  142. if (expr->hasProperty(manyAtom))
  143. resources.setHeavyweight();
  144. else
  145. resources.setLightweight();
  146. break;
  147. case no_sort:
  148. if (isGrouped)
  149. {
  150. if (expr->hasProperty(manyAtom))
  151. resources.setHeavyweight();
  152. else
  153. resources.setLightweight();
  154. }
  155. else if (expr->hasProperty(fewAtom) && isLocal)
  156. resources.setLightweight();
  157. else if (isLocal)
  158. resources.setHeavyweight();
  159. else
  160. {
  161. resources.setHeavyweight();
  162. #ifndef SORT_USING_MP
  163. resources.setManyToManySockets(2);
  164. #endif
  165. }
  166. break;
  167. case no_topn:
  168. resources.setLightweight();
  169. break;
  170. case no_pipe:
  171. //surely it should be something like this.
  172. resources.setLightweight().set(RESslavesocket, 1);
  173. break;
  174. case no_table:
  175. {
  176. IHqlExpression * mode = expr->queryChild(2);
  177. if (mode && mode->getOperator() == no_pipe)
  178. {
  179. resources.setLightweight().set(RESslavesocket, 1);
  180. }
  181. else
  182. {
  183. resources.setLightweight();
  184. if (expr->hasProperty(_workflowPersist_Atom) && expr->hasProperty(distributedAtom))
  185. setHashResources(expr, resources, options); // may require a hash distribute
  186. }
  187. break;
  188. }
  189. case no_output:
  190. {
  191. IHqlExpression * filename = expr->queryChild(1);
  192. if (expr->hasProperty(_spill_Atom))
  193. {
  194. //resources.setLightweight(); // assume no resources(!)
  195. }
  196. else if (filename && filename->getOperator() == no_pipe)
  197. {
  198. resources.setLightweight().set(RESslavesocket, 1);
  199. }
  200. else if (filename && !filename->isAttribute())
  201. {
  202. resources.setLightweight();
  203. }
  204. else
  205. {
  206. resources.setLightweight().set(RESslavememory, WORKUNITWRITE_SMART_BUFFER_SIZE);
  207. }
  208. break;
  209. }
  210. case no_distribution:
  211. resources.setLightweight().set(RESmastersocket, 16).set(RESslavesocket, 1);
  212. break;
  213. case no_aggregate:
  214. case no_newaggregate:
  215. {
  216. IHqlExpression * grouping = queryRealChild(expr, 3);
  217. if (grouping)
  218. {
  219. //Is this really correct???
  220. resources.setLightweight();
  221. setHashResources(expr, resources, options);
  222. }
  223. else
  224. {
  225. resources.setLightweight();
  226. //if (!isGrouped)
  227. // resources.set(RESmastersocket, 16).set(RESslavesocket, 1);
  228. }
  229. }
  230. break;
  231. case no_hqlproject:
  232. resources.setLightweight();
  233. //Add a flag onto count project to indicate it is a different variety.
  234. if (expr->hasProperty(_countProject_Atom) && !isLocal)
  235. resources.set(RESslavememory, COUNTPROJECT_SMART_BUFFER_SIZE);
  236. break;
  237. case no_enth:
  238. resources.setLightweight();
  239. if (!isLocal)
  240. resources.set(RESslavememory, CHOOSESETS_SMART_BUFFER_SIZE);
  241. break;
  242. case no_metaactivity:
  243. if (expr->hasProperty(pullAtom))
  244. resources.setLightweight().set(RESslavememory, PULL_SMART_BUFFER_SIZE);
  245. break;
  246. case no_setresult:
  247. case no_extractresult:
  248. case no_outputscalar:
  249. resources.setLightweight();//.set(RESmastersocket, 1).set(RESslavesocket, 1);
  250. break;
  251. case no_choosesets:
  252. resources.setLightweight();
  253. if (!isLocal || expr->hasProperty(enthAtom) || expr->hasProperty(lastAtom))
  254. resources.set(RESslavememory, CHOOSESETS_SMART_BUFFER_SIZE);
  255. break;
  256. case no_iterate:
  257. resources.setLightweight();
  258. if (!isGrouped && !isLocal)
  259. resources.setManyToMasterSockets(1).set(RESslavememory, ITERATE_SMART_BUFFER_SIZE);
  260. break;
  261. case no_choosen:
  262. resources.setLightweight().set(RESslavememory, FIRSTN_SMART_BUFFER_SIZE);
  263. break;
  264. case no_spill:
  265. case no_spillgraphresult:
  266. //assumed to take no resources;
  267. break;
  268. case no_addfiles:
  269. case no_merge:
  270. {
  271. resources.setLightweight();
  272. unsigned bufSize = FUNNEL_PERINPUT_BUFF_SIZE*expr->numChildren();
  273. if (bufSize < FUNNEL_MIN_BUFF_SIZE) bufSize = FUNNEL_MIN_BUFF_SIZE;
  274. resources.set(RESslavememory, MEM_Const_Minimal+bufSize);
  275. break;
  276. }
  277. case no_compound:
  278. //MORE: Should really be the total resources for the lhs... Really needs more thought.
  279. break;
  280. case no_libraryselect:
  281. //Do not allocate any resources for this, we don't want it to cause a spill under any circumstances
  282. break;
  283. case no_split:
  284. //Should really be included in the cost....
  285. default:
  286. resources.setLightweight();
  287. break;
  288. }
  289. }
  290. CResources & CResources::setLightweight()
  291. {
  292. return set(RESslavememory, 0x10000).set(RESactivities, 1);
  293. }
  294. CResources & CResources::setHeavyweight()
  295. {
  296. return set(RESslavememory, 0x100000).set(RESheavy, 1).set(RESactivities, 1);
  297. }
  298. //-------------------------------------------------------------------------------------------
  299. const char * queryResourceName(ResourceType kind)
  300. {
  301. switch (kind)
  302. {
  303. case RESslavememory: return "Slave Memory";
  304. case RESslavesocket: return "Slave Sockets";
  305. case RESmastermemory: return "Master Memory";
  306. case RESmastersocket: return "Master Sockets";
  307. case REShashdist: return "Hash Distributes";
  308. case RESheavy: return "Heavyweight";
  309. case RESactivities: return "Activities";
  310. }
  311. return "Unknown";
  312. }
  313. inline ResourcerInfo * queryResourceInfo(IHqlExpression * expr) { return (ResourcerInfo *)expr->queryBody()->queryTransformExtra(); }
  314. inline bool isResourcedActivity(IHqlExpression * expr)
  315. {
  316. ResourcerInfo * extra = queryResourceInfo(expr);
  317. return (extra && (extra->isActivity || extra->containsActivity));
  318. }
  319. bool isWorthForcingHoist(IHqlExpression * expr)
  320. {
  321. loop
  322. {
  323. switch (expr->getOperator())
  324. {
  325. case no_selectnth:
  326. case no_filter:
  327. case no_newaggregate:
  328. if (isResourcedActivity(expr->queryChild(0)))
  329. return true;
  330. break;
  331. default:
  332. return false;
  333. }
  334. expr = expr->queryChild(0);
  335. }
  336. }
  337. void CResources::add(const CResources & other)
  338. {
  339. for (unsigned i = 0; i < RESmax; i++)
  340. resource[i] += other.resource[i];
  341. }
  342. bool CResources::addExceeds(const CResources & other, const CResources & limit) const
  343. {
  344. for (unsigned i = 0; i < RESmax; i++)
  345. {
  346. if (resource[i] + other.resource[i] > limit.resource[i])
  347. {
  348. //DBGLOG("Cannot merge because limit for %s exceeded (%d cf %d)", queryResourceName((ResourceType)i), resource[i] + other.resource[i], limit.resource[i]);
  349. return true;
  350. }
  351. }
  352. return false;
  353. }
  354. StringBuffer & CResources::getExceedsReason(StringBuffer & reasonText, const CResources & other, const CResources & limit) const
  355. {
  356. bool first = true;
  357. for (unsigned i = 0; i < RESmax; i++)
  358. {
  359. if (resource[i] + other.resource[i] > limit.resource[i])
  360. {
  361. if (!first) reasonText.append(", ");
  362. first = false;
  363. reasonText.appendf("%s (%d>%d)", queryResourceName((ResourceType)i), resource[i] + other.resource[i], limit.resource[i]);
  364. }
  365. }
  366. return reasonText;
  367. }
  368. bool CResources::exceeds(const CResources & limit) const
  369. {
  370. for (unsigned i = 0; i < RESmax; i++)
  371. {
  372. if (resource[i] > limit.resource[i])
  373. return true;
  374. }
  375. return false;
  376. }
  377. void CResources::maximize(const CResources & other)
  378. {
  379. for (unsigned i = 0; i < RESmax; i++)
  380. {
  381. if (resource[i] < other.resource[i])
  382. resource[i] = other.resource[i];
  383. }
  384. }
  385. CResources & CResources::setManyToMasterSockets(unsigned numSockets)
  386. {
  387. set(RESslavesocket, numSockets);
  388. set(RESmastersocket, numSockets * clusterSize);
  389. return *this;
  390. }
  391. CResources & CResources::setManyToManySockets(unsigned numSockets)
  392. {
  393. return set(RESslavesocket, numSockets * clusterSize);
  394. }
  395. void CResources::sub(const CResources & other)
  396. {
  397. for (unsigned i = 0; i < RESmax; i++)
  398. resource[i] -= other.resource[i];
  399. }
  400. //===========================================================================
  401. inline bool isAffectedByResourcing(IHqlExpression * expr)
  402. {
  403. switch (expr->getOperator())
  404. {
  405. case no_record:
  406. case no_constant:
  407. case no_attr:
  408. return false;
  409. }
  410. return true;
  411. }
  412. bool isSimpleAggregateResult(IHqlExpression * expr)
  413. {
  414. //MORE: no_extractresult is really what is meant
  415. if (expr->getOperator() != no_extractresult)
  416. return false;
  417. IHqlExpression * value = expr->queryChild(0);
  418. if (value->getOperator() != no_datasetfromrow)
  419. return false;
  420. //MORE: This currently doesn't hoist selects from nested records, but not sure there is a syntax to do that either.
  421. IHqlExpression * ds = value->queryChild(0);
  422. if (!isSelectFirstRow(ds))
  423. return false;
  424. ds = ds->queryChild(0);
  425. if (ds->getOperator() != no_newaggregate)
  426. return false;
  427. return true;
  428. }
  429. bool lightweightAndReducesDatasetSize(IHqlExpression * expr)
  430. {
  431. switch (expr->getOperator())
  432. {
  433. case no_hqlproject:
  434. case no_newusertable:
  435. return reducesRowSize(expr);
  436. case no_dedup:
  437. if (isGroupedActivity(expr) || (!expr->hasProperty(allAtom) && !expr->hasProperty(hashAtom)))
  438. return true;
  439. break;
  440. case no_aggregate:
  441. case no_newaggregate:
  442. {
  443. IHqlExpression * grouping = queryRealChild(expr, 3);
  444. if (grouping)
  445. return false;
  446. return true;
  447. }
  448. case no_rollupgroup:
  449. case no_rollup:
  450. case no_choosen:
  451. case no_choosesets:
  452. case no_enth:
  453. case no_sample:
  454. case no_filter:
  455. case no_limit:
  456. case no_filtergroup:
  457. return true;
  458. case no_group:
  459. //removing grouping will reduce size of the spill file.
  460. if (expr->queryType()->queryGroupInfo() == NULL)
  461. return true;
  462. break;
  463. }
  464. return false;
  465. }
  466. bool heavyweightAndReducesSizeOrSkew(IHqlExpression * expr)
  467. {
  468. switch (expr->getOperator())
  469. {
  470. case no_aggregate:
  471. case no_newaggregate:
  472. {
  473. //more; hash aggregate?
  474. break;
  475. }
  476. case no_distribute:
  477. return true;
  478. }
  479. return false;
  480. }
  481. //---------------------------------------------------------------------------
  482. IHqlExpression * CResourceOptions::createSpillName(bool isGraphResult)
  483. {
  484. if (isGraphResult)
  485. return getSizetConstant(nextResult++);
  486. StringBuffer s;
  487. s.append("~spill::");
  488. getUniqueId(s);
  489. if (!mangleSpillNameWithWuid)
  490. return createConstant(s.str());
  491. s.append("_");
  492. if (filenameMangler)
  493. {
  494. s.append(filenameMangler);
  495. return createConstant(s.str());
  496. }
  497. ITypeInfo * type = makeStringType(UNKNOWN_LENGTH, NULL, NULL);
  498. return createValue(no_concat, type, createConstant(s.str()), createValue(no_wuid, LINK(type)));
  499. }
  500. //---------------------------------------------------------------------------
  501. IHqlExpression * appendUniqueAttr(IHqlExpression * expr)
  502. {
  503. return replaceOwnedProperty(expr, createUniqueId());
  504. }
  505. bool queryAddUniqueToActivity(IHqlExpression * expr)
  506. {
  507. if (!isSourceActivity(expr))
  508. return false;
  509. switch (expr->getOperator())
  510. {
  511. case no_workunit_dataset:
  512. case no_getgraphresult:
  513. case no_getgraphloopresult:
  514. case no_xmlproject:
  515. case no_datasetfromrow:
  516. case no_rows:
  517. case no_allnodes:
  518. case no_thisnode:
  519. case no_select: // it can get lost, and that then causes inconsistent trees.
  520. return false;
  521. }
  522. return true;
  523. }
  524. //---------------------------------------------------------------------------
  525. ResourceGraphLink::ResourceGraphLink(ResourceGraphInfo * _sourceGraph, IHqlExpression * _sourceNode, ResourceGraphInfo * _sinkGraph, IHqlExpression * _sinkNode, LinkKind _linkKind)
  526. {
  527. assertex(_sourceGraph);
  528. sourceGraph.set(_sourceGraph);
  529. sourceNode.set(_sourceNode);
  530. sinkGraph.set(_sinkGraph);
  531. sinkNode.set(_sinkNode);
  532. assertex(!sinkGraph || sinkNode);
  533. linkKind = _linkKind;
  534. trace("create");
  535. }
  536. ResourceGraphLink::~ResourceGraphLink()
  537. {
  538. trace("delete");
  539. }
  540. void ResourceGraphLink::changeSourceGraph(ResourceGraphInfo * newGraph)
  541. {
  542. sourceGraph->sinks.zap(*this);
  543. sourceGraph.set(newGraph);
  544. newGraph->sinks.append(*this);
  545. trace("change source");
  546. }
  547. void ResourceGraphLink::changeSinkGraph(ResourceGraphInfo * newGraph)
  548. {
  549. sinkGraph->sources.zap(*this);
  550. sinkGraph.set(newGraph);
  551. newGraph->sources.append(*this);
  552. trace("change sink");
  553. }
  554. bool ResourceGraphLink::isRedundantLink()
  555. {
  556. ResourcerInfo * info = queryResourceInfo(sourceNode);
  557. return info->expandRatherThanSpill(false);
  558. }
  559. void ResourceGraphLink::trace(const char * name)
  560. {
  561. #ifdef TRACE_RESOURCING
  562. PrintLog("%s: %lx source(%lx,%lx) sink(%lx,%lx) %s", name, this, sourceGraph.get(), sourceNode->queryBody(), sinkGraph.get(), sinkNode ? sinkNode->queryBody() : NULL,
  563. linkKind == ConditionalLink ? "conditional" : linkKind == SequenceLink ? "sequence" : "");
  564. #endif
  565. }
  566. ResourceGraphDependencyLink::ResourceGraphDependencyLink(ResourceGraphInfo * _sourceGraph, IHqlExpression * _sourceNode, ResourceGraphInfo * _sinkGraph, IHqlExpression * _sinkNode)
  567. : ResourceGraphLink(_sourceGraph, _sourceNode, _sinkGraph, _sinkNode, UnconditionalLink)
  568. {
  569. }
  570. void ResourceGraphDependencyLink::changeSourceGraph(ResourceGraphInfo * newGraph)
  571. {
  572. sourceGraph.set(newGraph);
  573. trace("change source");
  574. }
  575. void ResourceGraphDependencyLink::changeSinkGraph(ResourceGraphInfo * newGraph)
  576. {
  577. sinkGraph.set(newGraph);
  578. newGraph->dependsOn.append(*this);
  579. trace("change sink");
  580. }
  581. //---------------------------------------------------------------------------
  582. ResourceGraphInfo::ResourceGraphInfo(CResourceOptions * _options) : resources(_options->clusterSize)
  583. {
  584. options = _options;
  585. depth = 0;
  586. depthSequence = -1;
  587. beenResourced = false;
  588. isUnconditional = false;
  589. mergedConditionSource = false;
  590. hasConditionSource = false;
  591. isDead = false;
  592. startedGeneratingResourced = false;
  593. inheritedExpandedDependencies = false;
  594. cachedDependent.other = NULL;
  595. }
  596. ResourceGraphInfo::~ResourceGraphInfo()
  597. {
  598. }
  599. bool ResourceGraphInfo::addCondition(IHqlExpression * condition)
  600. {
  601. if (conditions.find(*condition) == NotFound)
  602. {
  603. conditions.append(*LINK(condition));
  604. #ifdef SPOT_UNCONDITIONAL_CONDITIONS
  605. _ATOM name = condition->queryName();
  606. _ATOM invName = NULL;
  607. if (name == trueAtom)
  608. invName = falseAtom;
  609. else if (name == falseAtom)
  610. invName = trueAtom;
  611. if (invName)
  612. {
  613. IHqlExpression * parent = condition->queryChild(1);
  614. OwnedHqlExpr invTag = createAttribute(invName, LINK(condition->queryChild(0)), LINK(parent));
  615. if (conditions.find(*invTag) != NotFound)
  616. {
  617. if (!parent)
  618. return true;
  619. return addCondition(parent);
  620. }
  621. }
  622. #endif
  623. }
  624. return false;
  625. }
  626. bool ResourceGraphInfo::isSharedInput(IHqlExpression * expr)
  627. {
  628. IHqlExpression * body = expr->queryBody();
  629. if (unbalancedExternalSources.contains(*body))
  630. return false;
  631. if (queryResourceInfo(expr)->expandRatherThanSplit())
  632. return false;
  633. unsigned numUses = 0;
  634. ForEachItemIn(i, balancedExternalSources)
  635. {
  636. if (body == &balancedExternalSources.item(i))
  637. numUses++;
  638. }
  639. //NumUses could be zero if an input should be expanded, and that input is shared by another graph which also expands
  640. //the input. E.g. project(meta(diskread).
  641. return numUses > 1;
  642. }
  643. void ResourceGraphInfo::addSharedInput(IHqlExpression * expr, IHqlExpression * mapped)
  644. {
  645. sharedInputs.append(*LINK(expr));
  646. sharedInputs.append(*LINK(mapped));
  647. }
  648. IHqlExpression * ResourceGraphInfo::queryMappedSharedInput(IHqlExpression * expr)
  649. {
  650. unsigned max = sharedInputs.ordinality();
  651. for (unsigned i=0; i < max; i+= 2)
  652. {
  653. if (expr == &sharedInputs.item(i))
  654. return &sharedInputs.item(i+1);
  655. }
  656. return NULL;
  657. }
  658. bool ResourceGraphInfo::allocateResources(const CResources & value, const CResources & limit)
  659. {
  660. if (resources.addExceeds(value, limit))
  661. return false;
  662. resources.add(value);
  663. return true;
  664. }
  665. bool ResourceGraphInfo::containsActiveSinks()
  666. {
  667. ForEachItemIn(idx, sinks)
  668. {
  669. ResourcerInfo * info = queryResourceInfo(sinks.item(idx).sourceNode);
  670. if (!info->expandRatherThanSpill(false))
  671. return true;
  672. }
  673. return false;
  674. }
  675. void ResourceGraphInfo::display()
  676. {
  677. StringBuffer s;
  678. s.appendf("graph %p src(", this);
  679. ForEachItemIn(idxs, sources)
  680. s.appendf("%p ", sources.item(idxs).sourceGraph.get());
  681. s.append(") dep(");
  682. ForEachItemIn(idxd, dependsOn)
  683. s.appendf("%p ", dependsOn.item(idxd).sourceGraph.get());
  684. s.append(")");
  685. if (isUnconditional)
  686. s.append(" <unconditional>");
  687. DBGLOG("%s", s.str());
  688. }
  689. void ResourceGraphInfo::getMergeFailReason(StringBuffer & reasonText, ResourceGraphInfo * otherGraph, const CResources & limit)
  690. {
  691. resources.getExceedsReason(reasonText, otherGraph->resources, limit);
  692. }
  693. unsigned ResourceGraphInfo::getDepth()
  694. {
  695. //If no graphs have been merged since this was last called it is still valid.
  696. if (depthSequence == options->state.updateSequence)
  697. return depth;
  698. depthSequence = options->state.updateSequence;
  699. depth = 0;
  700. ForEachItemIn(idx, dependsOn)
  701. {
  702. ResourceGraphInfo * source = dependsOn.item(idx).sourceGraph;
  703. if (source->getDepth() >= depth)
  704. depth = source->getDepth() + 1;
  705. }
  706. ForEachItemIn(idx2, sources)
  707. {
  708. ResourceGraphInfo * source = sources.item(idx2).sourceGraph;
  709. if (source->getDepth() >= depth)
  710. depth = source->getDepth() + 1;
  711. }
  712. return depth;
  713. }
  714. bool ResourceGraphInfo::hasSameConditions(ResourceGraphInfo & other)
  715. {
  716. if (conditions.ordinality() != other.conditions.ordinality())
  717. return false;
  718. ForEachItemIn(i, conditions)
  719. if (other.conditions.find(conditions.item(i)) == NotFound)
  720. return false;
  721. return true;
  722. }
  723. bool ResourceGraphInfo::evalDependentOn(ResourceGraphInfo & other, bool ignoreSources)
  724. {
  725. ForEachItemIn(idx, dependsOn)
  726. {
  727. ResourceGraphInfo * cur = dependsOn.item(idx).sourceGraph;
  728. if (cur == &other)
  729. return true;
  730. if (cur->isDependentOn(other, false))
  731. return true;
  732. }
  733. ForEachItemIn(idx2, sources)
  734. {
  735. ResourceGraphInfo * cur = sources.item(idx2).sourceGraph;
  736. if ((cur == &other) && !ignoreSources)
  737. return true;
  738. if (cur->isDependentOn(other, false))
  739. return true;
  740. }
  741. return false;
  742. }
  743. bool ResourceGraphInfo::isDependentOn(ResourceGraphInfo & other, bool ignoreSources)
  744. {
  745. //Cache the last query so that traversal doesn't convert a graph into a tree walk
  746. if ((cachedDependent.other == &other) && (cachedDependent.ignoreSources == ignoreSources) &&
  747. (cachedDependent.updateSequence == options->state.updateSequence))
  748. return cachedDependent.value;
  749. if (getDepth() <= other.getDepth())
  750. return false;
  751. cachedDependent.other = &other;
  752. cachedDependent.ignoreSources = ignoreSources;
  753. cachedDependent.updateSequence = options->state.updateSequence;
  754. cachedDependent.value = evalDependentOn(other, ignoreSources);
  755. return cachedDependent.value;
  756. }
  757. bool ResourceGraphInfo::isVeryCheap()
  758. {
  759. if (sinks.ordinality() != 1)
  760. return false;
  761. IHqlExpression * sourceNode = sinks.item(0).sourceNode;
  762. if (isSimpleAggregateResult(sourceNode))
  763. return true;
  764. // Not sure about the following....
  765. // if (sourceNode->getOperator() == no_setresult)
  766. // return true;
  767. //Could be other examples...
  768. return false;
  769. }
  770. bool ResourceGraphInfo::mergeInSource(ResourceGraphInfo & other, const CResources & limit, bool isConditionalLink)
  771. {
  772. bool mergeConditions = false;
  773. if (!isUnconditional)
  774. {
  775. //if it is conditional and it is very cheap then it is still more efficient to merge
  776. //rather than read from a spill file.
  777. if (other.isUnconditional || !hasSameConditions(other))
  778. {
  779. if ((hasConditionSource || !isVeryCheap()) && (other.sinks.ordinality() != 1))
  780. return false;
  781. mergeConditions = true;
  782. }
  783. }
  784. if (isDependentOn(other, true))
  785. return false;
  786. if (!options->canSplit())
  787. {
  788. //Don't merge two graphs that will cause a splitter to be created
  789. //Either already used internally, or an output will be merged twice
  790. HqlExprArray mergeNodes;
  791. ForEachItemIn(idx, sources)
  792. {
  793. ResourceGraphLink & cur = sources.item(idx);
  794. if (cur.sourceGraph == &other)
  795. {
  796. IHqlExpression * sourceNode = cur.sourceNode->queryBody();
  797. ResourcerInfo * info = queryResourceInfo(sourceNode);
  798. if ((info->numInternalUses() != 0) || (mergeNodes.find(*sourceNode) != NotFound) || info->preventMerge())
  799. return false;
  800. mergeNodes.append(*LINK(sourceNode));
  801. }
  802. }
  803. }
  804. if (options->checkResources() && !allocateResources(other.resources, limit))
  805. return false;
  806. mergeGraph(other, isConditionalLink, mergeConditions);
  807. return true;
  808. }
  809. void ResourceGraphInfo::mergeGraph(ResourceGraphInfo & other, bool isConditionalLink, bool mergeConditions)
  810. {
  811. #ifdef TRACE_RESOURCING
  812. DBGLOG("Merging%s source into%s sink", other.isUnconditional ? "" : " conditional", isUnconditional ? "" : " conditional");
  813. other.display();
  814. display();
  815. PrintLog("Merge %p into %p", &other, this);
  816. #endif
  817. if (other.hasConditionSource)
  818. hasConditionSource = true;
  819. //Recalculate the dependents, because sources of the source merged in may no longer be indirect
  820. //although they may be via another path.
  821. options->noteGraphsChanged();
  822. //If was very cheap and merged into an unconditional graph, make sure this is now tagged as
  823. //unconditional...
  824. if (other.isUnconditional)
  825. isUnconditional = true;
  826. //We need to stop spills being an arm of a conditional branch - otherwise they won't get executed.
  827. //so see if we have merged any conditional branches in
  828. if (isConditionalLink || other.mergedConditionSource)
  829. mergedConditionSource = true;
  830. if (mergeConditions)
  831. {
  832. //Replace conditions with those of parent. Only called when a very simple graph is
  833. //merged in, so replace conditions instead of merging
  834. conditions.kill();
  835. ForEachItemIn(i, other.conditions)
  836. conditions.append(OLINK(other.conditions.item(i)));
  837. }
  838. //sources and sinks are updated elsewhere...
  839. }
  840. bool ResourceGraphInfo::mergeInSibling(ResourceGraphInfo & other, const CResources & limit)
  841. {
  842. if ((!isUnconditional || !other.isUnconditional) && !hasSameConditions(other))
  843. return false;
  844. if (isDependentOn(other, false) || other.isDependentOn(*this, false))
  845. return false;
  846. if (options->checkResources() && !allocateResources(other.resources, limit))
  847. return false;
  848. mergeGraph(other, false, false);
  849. return true;
  850. }
  851. void ResourceGraphInfo::removeResources(const CResources & value)
  852. {
  853. resources.sub(value);
  854. }
  855. //---------------------------------------------------------------------------
  856. ResourcerInfo::ResourcerInfo(IHqlExpression * _original, CResourceOptions * _options)
  857. {
  858. original.set(_original);
  859. numUses = 0;
  860. numExternalUses = 0;
  861. gatheredDependencies = false;
  862. containsActivity = false;
  863. isActivity = false;
  864. transformed = NULL;
  865. conditionSourceCount = 0;
  866. pathToExpr = PathUnknown;
  867. outputToUseForSpill = NULL;
  868. isAlreadyInScope = false;
  869. isSpillPoint = false;
  870. options = _options;
  871. balanced = true;
  872. currentSource = 0;
  873. linkedFromChild = false;
  874. neverSplit = false;
  875. }
  876. void ResourcerInfo::setConditionSource(IHqlExpression * condition, bool isFirst)
  877. {
  878. if (isFirst)
  879. {
  880. conditionSourceCount++;
  881. graph->hasConditionSource = true;
  882. }
  883. }
  884. bool ResourcerInfo::addCondition(IHqlExpression * condition)
  885. {
  886. conditions.append(*LINK(condition));
  887. return graph->addCondition(condition);
  888. }
  889. void ResourcerInfo::addSpillFlags(HqlExprArray & args, bool isRead)
  890. {
  891. IHqlExpression * grouping = (IHqlExpression *)original->queryType()->queryGroupInfo();
  892. if (grouping)
  893. args.append(*createAttribute(groupedAtom));
  894. if (outputToUseForSpill)
  895. {
  896. assertex(isRead);
  897. if (outputToUseForSpill->hasProperty(__compressed__Atom))
  898. args.append(*createAttribute(__compressed__Atom));
  899. }
  900. else
  901. {
  902. args.append(*createAttribute(__compressed__Atom));
  903. args.append(*createAttribute(_spill_Atom));
  904. args.append(*createAttribute(_noReplicate_Atom));
  905. if (options->targetRoxie())
  906. args.append(*createAttribute(_noAccess_Atom));
  907. }
  908. if (isRead)
  909. {
  910. args.append(*createAttribute(_noVirtual_Atom)); // Don't interpret virtual fields as virtual...
  911. if (!original->isDataset() || hasSingleRow(original))
  912. args.append(*createAttribute(rowAtom)); // add a flag so the selectnth[1] can be removed later...
  913. }
  914. else
  915. {
  916. unsigned numUses = numExternalUses;
  917. if (false) // options->cloneConditionals)
  918. {
  919. //Remove all the links from conditional graphs...
  920. ForEachItemIn(i1, graph->sinks)
  921. {
  922. ResourceGraphLink & cur = graph->sinks.item(i1);
  923. if ((cur.sourceNode == original) && (cur.linkKind == ConditionalLink || !cur.sinkGraph->isUnconditional))
  924. numUses--;
  925. }
  926. numUses += calcNumConditionalUses();
  927. }
  928. args.append(*createAttribute(_tempCount_Atom, getSizetConstant(numUses)));
  929. }
  930. }
  931. bool ResourcerInfo::alwaysExpand()
  932. {
  933. return (original->getOperator() == no_mapto);
  934. }
  935. static IHqlExpression * stripTrueFalse(IHqlExpression * expr)
  936. {
  937. if (expr->queryName() == instanceAtom)
  938. {
  939. IHqlExpression * parent = expr->queryChild(2);
  940. if (parent)
  941. parent = stripTrueFalse(parent);
  942. return createAttribute(instanceAtom, LINK(expr->queryChild(0)), LINK(expr->queryChild(1)), parent);
  943. }
  944. else
  945. {
  946. IHqlExpression * parent = expr->queryChild(1);
  947. if (parent && parent->isAttribute())
  948. parent = stripTrueFalse(parent);
  949. return createAttribute(tempAtom, LINK(expr->queryChild(0)), parent);
  950. }
  951. }
  952. unsigned ResourcerInfo::calcNumConditionalUses()
  953. {
  954. //for thor and hthor, where the conditional graph is cloned, the maximum number of times it can be read
  955. //is 1 for a shared conditional graph, or once for each combination of conditions it is used as the
  956. //input for. However if it is used more than once in a single branch of a condition it needs to be counted
  957. //several times.
  958. //It is always better to overestimate than underestimate. (But even better to get it right.)
  959. HqlExprArray uniqueConditions;
  960. UnsignedArray uniqueCounts;
  961. ForEachItemIn(idx, conditions)
  962. {
  963. IHqlExpression & cur = conditions.item(idx);
  964. OwnedHqlExpr unique = stripTrueFalse(&cur);
  965. unsigned numOccurences = 0;
  966. ForEachItemIn(j, conditions)
  967. if (&conditions.item(j) == &cur)
  968. numOccurences++;
  969. unsigned match = uniqueConditions.find(*unique);
  970. if (match == NotFound)
  971. {
  972. uniqueConditions.append(*unique.getClear());
  973. uniqueCounts.append(numOccurences);
  974. }
  975. else
  976. {
  977. if (uniqueCounts.item(match) < numOccurences)
  978. uniqueCounts.replace(numOccurences, match);
  979. }
  980. }
  981. unsigned condUses = 0;
  982. ForEachItemIn(k, uniqueCounts)
  983. condUses += uniqueCounts.item(k);
  984. return condUses;
  985. }
  986. // Each aggregate has form. Setresult(select(selectnth(aggregate...,1),field),name,seq)
  987. IHqlExpression * ResourcerInfo::createAggregation(IHqlExpression * expr)
  988. {
  989. LinkedHqlExpr transformed = expr;
  990. ForEachItemIn(idx, aggregates)
  991. {
  992. IHqlExpression & cur = aggregates.item(idx);
  993. IHqlExpression * row2ds = cur.queryChild(0);
  994. IHqlExpression * selectnth = row2ds->queryChild(0);
  995. IHqlExpression * aggregate = selectnth->queryChild(0);
  996. IHqlExpression * aggregateRecord = aggregate->queryChild(1);
  997. assertex(aggregate->getOperator() == no_newaggregate);
  998. HqlExprArray aggargs, setargs;
  999. //Through aggregate has form (dataset, record, transform, list of set results);
  1000. aggargs.append(*LINK(transformed));
  1001. aggargs.append(*LINK(aggregateRecord));
  1002. IHqlExpression * mapped = replaceSelector(aggregate->queryChild(2), original, expr->queryNormalizedSelector());
  1003. aggargs.append(*mapped);
  1004. OwnedHqlExpr active = createDataset(no_anon, LINK(aggregateRecord), NULL);
  1005. OwnedHqlExpr mappedSelect = replaceSelector(cur.queryChild(1), row2ds, active);
  1006. setargs.append(*LINK(active));
  1007. setargs.append(*LINK(mappedSelect));
  1008. unwindChildren(setargs, &cur, 1);
  1009. aggargs.append(*createValue(no_extractresult, makeVoidType(), setargs));
  1010. transformed.setown(createDataset(no_throughaggregate, aggargs));
  1011. }
  1012. return transformed.getClear();
  1013. }
  1014. bool ResourcerInfo::useGraphResult()
  1015. {
  1016. if (!options->useGraphResults)
  1017. return false;
  1018. if (linkedFromChild)
  1019. return true;
  1020. //Roxie converts spills into splitters, so best to retain them
  1021. if (options->targetClusterType == RoxieCluster)
  1022. return false;
  1023. return true;
  1024. }
  1025. bool ResourcerInfo::useGlobalResult()
  1026. {
  1027. return (linkedFromChild && !useGraphResult());
  1028. }
  1029. IHqlExpression * ResourcerInfo::createSpillName()
  1030. {
  1031. if (outputToUseForSpill)
  1032. return LINK(outputToUseForSpill->queryChild(1));
  1033. if (!spillName)
  1034. {
  1035. if (useGraphResult())
  1036. spillName.setown(options->createSpillName(true));
  1037. else if (useGlobalResult())
  1038. {
  1039. StringBuffer valueText;
  1040. getUniqueId(valueText.append("spill"));
  1041. spillName.setown(createConstant(valueText.str()));
  1042. }
  1043. else
  1044. spillName.setown(options->createSpillName(false));
  1045. }
  1046. return LINK(spillName);
  1047. }
  1048. IHqlExpression * ResourcerInfo::createSpilledRead(IHqlExpression * spillReason)
  1049. {
  1050. OwnedHqlExpr dataset;
  1051. HqlExprArray args;
  1052. IHqlExpression * record = original->queryRecord();
  1053. bool loseDistribution = true;
  1054. if (useGraphResult())
  1055. {
  1056. args.append(*LINK(record));
  1057. args.append(*LINK(options->graphIdExpr));
  1058. args.append(*createSpillName());
  1059. if (isGrouped(original))
  1060. args.append(*createAttribute(groupedAtom));
  1061. if (!original->isDataset())
  1062. args.append(*createAttribute(rowAtom));
  1063. args.append(*createAttribute(_spill_Atom));
  1064. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1065. if (recordCountAttr)
  1066. args.append(*LINK(recordCountAttr));
  1067. if (options->targetThor() && original->isDataset() && !options->isChildQuery)
  1068. args.append(*createAttribute(_distributed_Atom));
  1069. dataset.setown(createDataset(no_getgraphresult, args));
  1070. loseDistribution = false;
  1071. }
  1072. else if (useGlobalResult())
  1073. {
  1074. args.append(*LINK(record));
  1075. args.append(*createAttribute(nameAtom, createSpillName()));
  1076. args.append(*createAttribute(sequenceAtom, getLocalSequenceNumber()));
  1077. addSpillFlags(args, true);
  1078. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1079. if (recordCountAttr)
  1080. args.append(*LINK(recordCountAttr));
  1081. dataset.setown(createDataset(no_workunit_dataset, args));
  1082. }
  1083. else
  1084. {
  1085. if (spilledDataset)
  1086. {
  1087. args.append(*LINK(spilledDataset));
  1088. args.append(*createSpillName());
  1089. }
  1090. else
  1091. {
  1092. args.append(*createSpillName());
  1093. args.append(*LINK(record));
  1094. }
  1095. args.append(*createValue(no_thor));
  1096. addSpillFlags(args, true);
  1097. args.append(*createUniqueId());
  1098. if (options->isChildQuery && options->targetRoxie())
  1099. {
  1100. args.append(*createAttribute(_colocal_Atom));
  1101. args.append(*createLocalAttribute());
  1102. }
  1103. if (spillReason)
  1104. args.append(*LINK(spillReason));
  1105. if (spilledDataset)
  1106. dataset.setown(createDataset(no_readspill, args));
  1107. else
  1108. {
  1109. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1110. if (recordCountAttr)
  1111. args.append(*LINK(recordCountAttr));
  1112. dataset.setown(createDataset(no_table, args));
  1113. }
  1114. loseDistribution = false;
  1115. }
  1116. dataset.setown(preserveTableInfo(dataset, original, loseDistribution, NULL));
  1117. return wrapRowOwn(dataset.getClear());
  1118. }
  1119. IHqlExpression * ResourcerInfo::createSpilledWrite(IHqlExpression * transformed)
  1120. {
  1121. assertex(!outputToUseForSpill);
  1122. HqlExprArray args;
  1123. if (useGraphResult())
  1124. {
  1125. assertex(options->graphIdExpr);
  1126. args.append(*LINK(transformed));
  1127. args.append(*LINK(options->graphIdExpr));
  1128. args.append(*createSpillName());
  1129. args.append(*createAttribute(_spill_Atom));
  1130. return createValue(no_setgraphresult, makeVoidType(), args);
  1131. }
  1132. else if (useGlobalResult())
  1133. {
  1134. args.append(*LINK(transformed));
  1135. args.append(*createAttribute(sequenceAtom, getLocalSequenceNumber()));
  1136. args.append(*createAttribute(namedAtom, createSpillName()));
  1137. addSpillFlags(args, false);
  1138. return createValue(no_output, makeVoidType(), args);
  1139. }
  1140. else
  1141. {
  1142. if (options->createSpillAsDataset)
  1143. {
  1144. IHqlExpression * value = LINK(transformed);
  1145. if (value->isDatarow())
  1146. value = createDatasetFromRow(value);
  1147. spilledDataset.setown(createDataset(no_commonspill, value));
  1148. args.append(*LINK(spilledDataset));
  1149. }
  1150. else
  1151. args.append(*LINK(transformed));
  1152. args.append(*createSpillName());
  1153. addSpillFlags(args, false);
  1154. if (options->createSpillAsDataset)
  1155. return createValue(no_writespill, makeVoidType(), args);
  1156. return createValue(no_output, makeVoidType(), args);
  1157. }
  1158. }
  1159. bool ResourcerInfo::okToSpillThrough()
  1160. {
  1161. bool isGraphResult = useGraphResult();
  1162. if (isGraphResult)
  1163. return options->allowThroughResult;
  1164. if (useGlobalResult())
  1165. return false;
  1166. return (options->allowThroughSpill && !options->createSpillAsDataset);
  1167. }
  1168. bool ResourcerInfo::spillSharesSplitter()
  1169. {
  1170. if (outputToUseForSpill || useGraphResult() || useGlobalResult())
  1171. return false;
  1172. if (okToSpillThrough())
  1173. return false;
  1174. if (!isSplit() || !balanced)
  1175. return false;
  1176. return true;
  1177. }
  1178. IHqlExpression * ResourcerInfo::createSpiller(IHqlExpression * transformed, bool reuseSplitter)
  1179. {
  1180. if (outputToUseForSpill)
  1181. return LINK(transformed);
  1182. if (!okToSpillThrough())
  1183. {
  1184. OwnedHqlExpr split;
  1185. if (reuseSplitter)
  1186. {
  1187. assertex(transformed->getOperator() == no_split);
  1188. split.set(transformed);
  1189. }
  1190. else
  1191. {
  1192. if (transformed->isDataset())
  1193. split.setown(createDataset(no_split, LINK(transformed), createComma(createAttribute(balancedAtom), createUniqueId())));
  1194. else
  1195. split.setown(createRow(no_split, LINK(transformed), createComma(createAttribute(balancedAtom), createUniqueId())));
  1196. split.setown(cloneInheritedAnnotations(original, split));
  1197. }
  1198. splitterOutput.setown(createSpilledWrite(split));
  1199. return split.getClear();
  1200. }
  1201. HqlExprArray args;
  1202. node_operator op;
  1203. args.append(*LINK(transformed));
  1204. if (useGraphResult())
  1205. {
  1206. op = no_spillgraphresult;
  1207. args.append(*LINK(options->graphIdExpr));
  1208. args.append(*createSpillName());
  1209. args.append(*createAttribute(_spill_Atom));
  1210. }
  1211. else
  1212. {
  1213. op = no_spill;
  1214. args.append(*createSpillName());
  1215. addSpillFlags(args, false);
  1216. }
  1217. OwnedHqlExpr spill;
  1218. if (original->isDatarow())
  1219. spill.setown(createRow(op, args));
  1220. else
  1221. spill.setown(createDataset(op, args));
  1222. return cloneInheritedAnnotations(original, spill);
  1223. }
  1224. IHqlExpression * ResourcerInfo::createSplitter(IHqlExpression * transformed)
  1225. {
  1226. if (transformed->getOperator() == no_libraryscopeinstance)
  1227. return LINK(transformed);
  1228. IHqlExpression * attr = createUniqueId();
  1229. if (balanced)
  1230. attr = createComma(attr, createAttribute(balancedAtom));
  1231. OwnedHqlExpr split;
  1232. if (transformed->isDataset())
  1233. split.setown(createDataset(no_split, LINK(transformed), attr));
  1234. else
  1235. split.setown(createRow(no_split, LINK(transformed), attr));
  1236. return cloneInheritedAnnotations(original, split);
  1237. }
  1238. IHqlExpression * ResourcerInfo::createTransformedExpr(IHqlExpression * expr)
  1239. {
  1240. LinkedHqlExpr transformed = expr;
  1241. if (aggregates.ordinality())
  1242. transformed.setown(createAggregation(transformed));
  1243. if (spillSharesSplitter())
  1244. {
  1245. transformed.setown(createSplitter(transformed));
  1246. if (isExternalSpill())
  1247. transformed.setown(createSpiller(transformed, true));
  1248. }
  1249. else
  1250. {
  1251. if (isExternalSpill())
  1252. transformed.setown(createSpiller(transformed, false));
  1253. if (isSplit())
  1254. transformed.setown(createSplitter(transformed));
  1255. else if (isSpilledWrite())
  1256. transformed.setown(createSpilledWrite(transformed));
  1257. }
  1258. return transformed.getClear();
  1259. }
  1260. bool ResourcerInfo::expandRatherThanSpill(bool noteOtherSpills)
  1261. {
  1262. if (options->shareDontExpand)
  1263. return expandRatherThanSplit();
  1264. IHqlExpression * expr = original;
  1265. if (!options->minimiseSpills || linkedFromChild)
  1266. noteOtherSpills = false;
  1267. if (noteOtherSpills)
  1268. {
  1269. ResourcerInfo * info = queryResourceInfo(expr);
  1270. if (info && info->isSpilledWrite())
  1271. return (info->transformed == NULL);
  1272. }
  1273. bool isFiltered = false;
  1274. bool isProcessed = false;
  1275. loop
  1276. {
  1277. ResourcerInfo * info = queryResourceInfo(expr);
  1278. if (info && info->neverSplit)
  1279. return true;
  1280. node_operator op = expr->getOperator();
  1281. switch (op)
  1282. {
  1283. case no_table:
  1284. {
  1285. //This is only executed for hthor/thor. Roxie has used expandRatherThanSplit().
  1286. //We need to balance the saving from reading reduced data in the other branches with the cost of
  1287. //writing the spill file to disk.
  1288. if (isFiltered && (numExternalUses >= options->filteredSpillThreshold))
  1289. return false;
  1290. IHqlExpression * mode = expr->queryChild(2);
  1291. switch (mode->getOperator())
  1292. {
  1293. case no_thor: case no_flat:
  1294. //MORE: The following is possibly better - but roxie should be able to read from non spill data files in child queries fine
  1295. //if ((options->targetClusterType == RoxieCluster) && linkedFromChild)) return false;
  1296. return true;
  1297. default:
  1298. return false;
  1299. }
  1300. }
  1301. case no_stepped:
  1302. return true;
  1303. case no_inlinetable:
  1304. {
  1305. IHqlExpression * transforms = expr->queryChild(0);
  1306. //The inline table code means this should generate smaller code, and more efficient
  1307. if (!isFiltered && !isProcessed && transforms->isConstant())
  1308. return true;
  1309. if (transforms->numChildren() > MAX_INLINE_COMMON_COUNT)
  1310. return false;
  1311. return true;
  1312. }
  1313. case no_getresult:
  1314. case no_temptable:
  1315. case no_rows:
  1316. case no_xmlproject:
  1317. case no_workunit_dataset:
  1318. return !isProcessed && !isFiltered;
  1319. case no_getgraphresult:
  1320. return !expr->hasProperty(_streaming_Atom); // we must not duplicate streaming inputs!
  1321. case no_keyindex:
  1322. case no_newkeyindex:
  1323. if (!isFiltered)
  1324. return true;
  1325. return options->cloneFilteredIndex;
  1326. case no_datasetfromrow:
  1327. if (getNumActivityArguments(expr) == 0)
  1328. return true;
  1329. return false;
  1330. case no_fail:
  1331. case no_null:
  1332. return !expr->isAction();
  1333. case no_assertsorted:
  1334. case no_sorted:
  1335. case no_grouped:
  1336. case no_distributed:
  1337. case no_preservemeta:
  1338. case no_nofold:
  1339. case no_nohoist:
  1340. case no_section:
  1341. case no_sectioninput:
  1342. case no_dataset_alias:
  1343. expr = expr->queryChild(0);
  1344. break;
  1345. case no_newusertable:
  1346. case no_limit:
  1347. case no_keyedlimit:
  1348. expr = expr->queryChild(0);
  1349. isProcessed = true;
  1350. break;
  1351. case no_hqlproject:
  1352. if (expr->hasProperty(_countProject_Atom) || expr->hasProperty(prefetchAtom))
  1353. return false;
  1354. expr = expr->queryChild(0);
  1355. isProcessed = true;
  1356. break;
  1357. //MORE: Not so sure about all the following, include them so behaviour doesn't change
  1358. case no_compound_diskread:
  1359. case no_compound_disknormalize:
  1360. case no_compound_diskaggregate:
  1361. case no_compound_diskcount:
  1362. case no_compound_diskgroupaggregate:
  1363. case no_compound_indexread:
  1364. case no_compound_indexnormalize:
  1365. case no_compound_indexaggregate:
  1366. case no_compound_indexcount:
  1367. case no_compound_indexgroupaggregate:
  1368. case no_compound_childread:
  1369. case no_compound_childnormalize:
  1370. case no_compound_childaggregate:
  1371. case no_compound_childcount:
  1372. case no_compound_childgroupaggregate:
  1373. case no_compound_selectnew:
  1374. case no_compound_inline:
  1375. expr = expr->queryChild(0);
  1376. break;
  1377. case no_filter:
  1378. isFiltered = true;
  1379. expr = expr->queryChild(0);
  1380. break;
  1381. case no_select:
  1382. {
  1383. if (options->targetClusterType == RoxieCluster)
  1384. return false;
  1385. if (!isNewSelector(expr))
  1386. return true;
  1387. expr = expr->queryChild(0);
  1388. break;
  1389. }
  1390. default:
  1391. return false;
  1392. }
  1393. //The following reduces the number of spills by taking into account other spills.
  1394. if (noteOtherSpills)
  1395. {
  1396. ResourcerInfo * info = queryResourceInfo(expr);
  1397. if (info)
  1398. {
  1399. if (info->isSpilledWrite())
  1400. return (info->transformed == NULL);
  1401. if (info->numExternalUses)
  1402. {
  1403. if (isFiltered && (numExternalUses >= options->filteredSpillThreshold))
  1404. return false;
  1405. return true;
  1406. }
  1407. }
  1408. }
  1409. }
  1410. }
  1411. bool ResourcerInfo::expandRatherThanSplit()
  1412. {
  1413. //MORE: This doesn't really work - should do indexMatching first.
  1414. //should only expand if one side that uses this is also filtered
  1415. IHqlExpression * expr = original;
  1416. loop
  1417. {
  1418. ResourcerInfo * info = queryResourceInfo(expr);
  1419. if (info && info->neverSplit)
  1420. return true;
  1421. switch (expr->getOperator())
  1422. {
  1423. case no_keyindex:
  1424. case no_newkeyindex:
  1425. case no_rowset:
  1426. case no_getgraphloopresultset:
  1427. return true;
  1428. case no_null:
  1429. return !expr->isAction();
  1430. case no_inlinetable:
  1431. if (options->expandSingleConstRow && hasSingleRow(expr))
  1432. {
  1433. IHqlExpression * values = expr->queryChild(0);
  1434. if (values->queryChild(0)->isConstant())
  1435. return true;
  1436. }
  1437. return false;
  1438. case no_stepped:
  1439. case no_rowsetrange:
  1440. case no_rowsetindex:
  1441. return true;
  1442. case no_sorted:
  1443. case no_grouped:
  1444. case no_distributed:
  1445. case no_preservemeta:
  1446. case no_compound_diskread:
  1447. case no_compound_disknormalize:
  1448. case no_compound_diskaggregate:
  1449. case no_compound_diskcount:
  1450. case no_compound_diskgroupaggregate:
  1451. case no_compound_indexread:
  1452. case no_compound_indexnormalize:
  1453. case no_compound_indexaggregate:
  1454. case no_compound_indexcount:
  1455. case no_compound_indexgroupaggregate:
  1456. case no_compound_childread:
  1457. case no_compound_childnormalize:
  1458. case no_compound_childaggregate:
  1459. case no_compound_childcount:
  1460. case no_compound_childgroupaggregate:
  1461. case no_compound_selectnew:
  1462. case no_compound_inline:
  1463. case no_section:
  1464. case no_sectioninput:
  1465. case no_dataset_alias:
  1466. break;
  1467. case no_select:
  1468. if (options->targetClusterType == RoxieCluster)
  1469. return false;
  1470. if (!isNewSelector(expr))
  1471. {
  1472. if (!options->useLinkedRawIterator || !hasLinkCountedModifier(expr))
  1473. return false;
  1474. return true;
  1475. }
  1476. break;
  1477. case no_rows:
  1478. //If executing in a child query then you'll have less thread contention if the iterator is duplicated
  1479. //So should probably uncomment the following.
  1480. //return true;
  1481. return false;
  1482. default:
  1483. return false;
  1484. }
  1485. expr = expr->queryChild(0);
  1486. }
  1487. }
  1488. bool neverCommonUp(IHqlExpression * expr)
  1489. {
  1490. loop
  1491. {
  1492. node_operator op = expr->getOperator();
  1493. switch (op)
  1494. {
  1495. case no_keyindex:
  1496. case no_newkeyindex:
  1497. return true;
  1498. case no_filter:
  1499. expr = expr->queryChild(0);
  1500. break;
  1501. default:
  1502. return false;
  1503. }
  1504. }
  1505. }
  1506. bool ResourcerInfo::neverCommonUp()
  1507. {
  1508. return ::neverCommonUp(original);
  1509. }
  1510. bool ResourcerInfo::isExternalSpill()
  1511. {
  1512. if (expandRatherThanSpill(true) || (numInternalUses() == 0))
  1513. return false;
  1514. return (numExternalUses != 0);
  1515. }
  1516. bool ResourcerInfo::isSplit()
  1517. {
  1518. return numSplitPaths() > 1;
  1519. }
  1520. unsigned ResourcerInfo::numSplitPaths()
  1521. {
  1522. unsigned internal = numInternalUses();
  1523. if ((internal == 0) || !options->allowSplitBetweenSubGraphs)
  1524. return internal;
  1525. //MORE
  1526. return internal;
  1527. }
  1528. bool ResourcerInfo::isSpilledWrite()
  1529. {
  1530. if (numInternalUses() == 0)
  1531. return true;
  1532. return false;
  1533. }
  1534. IHqlExpression * ResourcerInfo::wrapRowOwn(IHqlExpression * expr)
  1535. {
  1536. if (!original->isDataset())
  1537. expr = createRow(no_selectnth, expr, getSizetConstant(1));
  1538. return expr;
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. EclResourcer::EclResourcer(IErrorReceiver * _errors, IConstWorkUnit * _wu, ClusterType _targetClusterType, unsigned _clusterSize, const HqlCppOptions & _translatorOptions)
  1542. {
  1543. wu.set(_wu);
  1544. errors = _errors;
  1545. lockTransformMutex();
  1546. targetClusterType = _targetClusterType;
  1547. clusterSize = _clusterSize ? _clusterSize : FIXED_CLUSTER_SIZE;
  1548. insideNeverSplit = false;
  1549. options.mangleSpillNameWithWuid = false;
  1550. options.minimizeSpillSize = _translatorOptions.minimizeSpillSize;
  1551. bool wuidIsConstant = (targetClusterType == RoxieCluster) || !wu->getCloneable();
  1552. if (wuidIsConstant)
  1553. {
  1554. SCMStringBuffer wuNameText;
  1555. wu->getWuid(wuNameText);
  1556. options.filenameMangler.set(wuNameText.str());
  1557. }
  1558. unsigned totalMemory = _translatorOptions.resourceMaxMemory ? _translatorOptions.resourceMaxMemory : DEFAULT_TOTAL_MEMORY;
  1559. unsigned maxSockets = _translatorOptions.resourceMaxSockets ? _translatorOptions.resourceMaxSockets : DEFAULT_MAX_SOCKETS;
  1560. unsigned maxActivities = _translatorOptions.resourceMaxActivities ? _translatorOptions.resourceMaxActivities : DEFAULT_MAX_ACTIVITIES;
  1561. unsigned maxHeavy = _translatorOptions.resourceMaxHeavy;
  1562. unsigned maxDistribute = _translatorOptions.resourceMaxDistribute;
  1563. resourceLimit = new CResources(0);
  1564. resourceLimit->set(RESactivities, maxActivities);
  1565. switch (targetClusterType)
  1566. {
  1567. case ThorCluster:
  1568. case ThorLCRCluster:
  1569. resourceLimit->set(RESheavy, maxHeavy).set(REShashdist, maxDistribute);
  1570. resourceLimit->set(RESmastersocket, maxSockets).set(RESslavememory,totalMemory);
  1571. resourceLimit->set(RESslavesocket, maxSockets).set(RESmastermemory, totalMemory);
  1572. break;
  1573. default:
  1574. resourceLimit->set(RESheavy, 0xffffffff).set(REShashdist, 0xffffffff);
  1575. resourceLimit->set(RESmastersocket, 0xffffffff).set(RESslavememory, 0xffffffff);
  1576. resourceLimit->set(RESslavesocket, 0xffffffff).set(RESmastermemory, 0xffffffff);
  1577. clusterSize = 1;
  1578. break;
  1579. }
  1580. if (_translatorOptions.unlimitedResources)
  1581. {
  1582. resourceLimit->set(RESheavy, 0xffffffff).set(REShashdist, 0xffffffff);
  1583. resourceLimit->set(RESmastersocket, 0xffffffff).set(RESslavememory,0xffffffff);
  1584. resourceLimit->set(RESslavesocket, 0xffffffff).set(RESmastermemory,0xffffffff);
  1585. }
  1586. options.useMpForDistribute = (targetClusterType == ThorLCRCluster);
  1587. if (_translatorOptions.hasResourceUseMpForDistribute)
  1588. options.useMpForDistribute = _translatorOptions.resourceUseMpForDistribute;
  1589. options.isChildQuery = false;
  1590. options.targetClusterType = targetClusterType;
  1591. options.filteredSpillThreshold = _translatorOptions.filteredReadSpillThreshold;
  1592. options.allowThroughSpill = _translatorOptions.allowThroughSpill;
  1593. options.allowThroughResult = (targetClusterType != RoxieCluster) && (targetClusterType != ThorLCRCluster);
  1594. options.cloneFilteredIndex = (targetClusterType != RoxieCluster);
  1595. options.spillSharedConditionals = (targetClusterType == RoxieCluster);
  1596. options.shareDontExpand = (targetClusterType == RoxieCluster);
  1597. options.graphIdExpr = NULL;
  1598. //MORE The following doesn't always work - it gets sometimes confused about spill files - see latestheaderbuild for an example.
  1599. //Try again once cloneConditionals is false for thor
  1600. options.minimiseSpills = _translatorOptions.minimiseSpills;
  1601. spillMultiCondition = _translatorOptions.spillMultiCondition;
  1602. spotThroughAggregate = _translatorOptions.spotThroughAggregate && (targetClusterType != RoxieCluster) && (targetClusterType != ThorLCRCluster);
  1603. options.noConditionalLinks = (targetClusterType == RoxieCluster);
  1604. options.hoistResourced = _translatorOptions.hoistResourced;
  1605. options.useGraphResults = false; // modified by later call
  1606. options.groupedChildIterators = _translatorOptions.groupedChildIterators;
  1607. options.allowSplitBetweenSubGraphs = false;//(targetClusterType == RoxieCluster);
  1608. options.supportsChildQueries = (targetClusterType != ThorCluster);
  1609. options.clusterSize = clusterSize;
  1610. options.preventKeyedSplit = _translatorOptions.preventKeyedSplit;
  1611. options.preventSteppedSplit = _translatorOptions.preventSteppedSplit;
  1612. options.minimizeSkewBeforeSpill = _translatorOptions.minimizeSkewBeforeSpill;
  1613. options.expandSingleConstRow = true;
  1614. options.createSpillAsDataset = _translatorOptions.optimizeSpillProject && (targetClusterType != HThorCluster);
  1615. options.useLinkedRawIterator = _translatorOptions.useLinkedRawIterator;
  1616. options.combineSiblings = _translatorOptions.combineSiblingGraphs && (targetClusterType != HThorCluster) && (targetClusterType != RoxieCluster);
  1617. options.optimizeSharedInputs = _translatorOptions.optimizeSharedGraphInputs && options.combineSiblings;
  1618. }
  1619. EclResourcer::~EclResourcer()
  1620. {
  1621. delete resourceLimit;
  1622. unlockTransformMutex();
  1623. }
  1624. void EclResourcer::setChildQuery(bool value)
  1625. {
  1626. options.isChildQuery = value;
  1627. if (value)
  1628. options.createSpillAsDataset = false;
  1629. }
  1630. void EclResourcer::setNewChildQuery(IHqlExpression * graphIdExpr, unsigned numResults)
  1631. {
  1632. options.graphIdExpr = graphIdExpr;
  1633. options.nextResult = numResults;
  1634. }
  1635. void EclResourcer::changeGraph(IHqlExpression * expr, ResourceGraphInfo * newGraph)
  1636. {
  1637. ResourcerInfo * info = queryResourceInfo(expr);
  1638. info->graph.set(newGraph);
  1639. ForEachItemInRev(idx, links)
  1640. {
  1641. ResourceGraphLink & cur = links.item(idx);
  1642. if (cur.sourceNode == expr)
  1643. cur.changeSourceGraph(newGraph);
  1644. else if (cur.sinkNode == expr)
  1645. cur.changeSinkGraph(newGraph);
  1646. assertex(cur.sinkGraph != cur.sourceGraph);
  1647. }
  1648. }
  1649. ResourceGraphInfo * EclResourcer::createGraph()
  1650. {
  1651. ResourceGraphInfo * graph = new ResourceGraphInfo(&options);
  1652. graphs.append(*LINK(graph));
  1653. //PrintLog("Create graph %p", graph);
  1654. return graph;
  1655. }
  1656. void EclResourcer::connectGraphs(ResourceGraphInfo * sourceGraph, IHqlExpression * sourceNode, ResourceGraphInfo * sinkGraph, IHqlExpression * sinkNode, LinkKind kind)
  1657. {
  1658. ResourceGraphLink * link = new ResourceGraphLink(sourceGraph, sourceNode, sinkGraph, sinkNode, kind);
  1659. links.append(*link);
  1660. if (sourceGraph)
  1661. sourceGraph->sinks.append(*link);
  1662. if (sinkGraph)
  1663. sinkGraph->sources.append(*link);
  1664. }
  1665. ResourcerInfo * EclResourcer::queryCreateResourceInfo(IHqlExpression * expr)
  1666. {
  1667. IHqlExpression * body = expr->queryBody();
  1668. ResourcerInfo * info = (ResourcerInfo *)body->queryTransformExtra();
  1669. if (!info)
  1670. {
  1671. info = new ResourcerInfo(expr, &options);
  1672. body->setTransformExtraOwned(info);
  1673. }
  1674. return info;
  1675. }
  1676. void EclResourcer::replaceGraphReferences(IHqlExpression * expr, ResourceGraphInfo * oldGraph, ResourceGraphInfo * newGraph)
  1677. {
  1678. ResourcerInfo * info = queryResourceInfo(expr);
  1679. if (!info || !info->containsActivity)
  1680. return;
  1681. if (info->isActivity && info->graph != oldGraph)
  1682. return;
  1683. info->graph.set(newGraph);
  1684. unsigned first = getFirstActivityArgument(expr);
  1685. unsigned last = first + getNumActivityArguments(expr);
  1686. for (unsigned idx=first; idx < last; idx++)
  1687. replaceGraphReferences(expr->queryChild(idx), oldGraph, newGraph);
  1688. }
  1689. void EclResourcer::removeLink(ResourceGraphLink & link, bool keepExternalUses)
  1690. {
  1691. ResourcerInfo * info = (ResourcerInfo *)queryResourceInfo(link.sourceNode);
  1692. assertex(info && info->numExternalUses > 0);
  1693. if (!keepExternalUses)
  1694. info->numExternalUses--;
  1695. if (link.sinkGraph)
  1696. link.sinkGraph->sources.zap(link);
  1697. link.sourceGraph->sinks.zap(link);
  1698. links.zap(link);
  1699. }
  1700. void EclResourcer::replaceGraphReferences(ResourceGraphInfo * oldGraph, ResourceGraphInfo * newGraph)
  1701. {
  1702. ForEachItemIn(idx1, oldGraph->sinks)
  1703. {
  1704. ResourceGraphLink & sink = oldGraph->sinks.item(idx1);
  1705. replaceGraphReferences(sink.sourceNode, oldGraph, newGraph);
  1706. }
  1707. ForEachItemInRev(idx2, links)
  1708. {
  1709. ResourceGraphLink & cur = links.item(idx2);
  1710. if (cur.sourceGraph == oldGraph)
  1711. {
  1712. if (cur.sinkGraph == newGraph)
  1713. removeLink(cur, false);
  1714. else
  1715. cur.changeSourceGraph(newGraph);
  1716. }
  1717. else if (cur.sinkGraph == oldGraph)
  1718. {
  1719. if (cur.sourceGraph == newGraph)
  1720. removeLink(cur, false);
  1721. else
  1722. cur.changeSinkGraph(newGraph);
  1723. }
  1724. }
  1725. }
  1726. //------------------------------------------------------------------------------------------
  1727. // PASS1: Gather information about splitter locations..
  1728. void EclResourcer::tagActiveCursors(HqlExprCopyArray & activeRows)
  1729. {
  1730. ForEachItemIn(i, activeRows)
  1731. {
  1732. IHqlExpression & cur = activeRows.item(i);
  1733. activeSelectors.append(cur);
  1734. queryCreateResourceInfo(&cur)->isAlreadyInScope = true;
  1735. }
  1736. }
  1737. inline bool projectSelectorDatasetToField(IHqlExpression * row)
  1738. {
  1739. return ((row->getOperator() == no_selectnth) && getFieldCount(row->queryRecord()) > 1);
  1740. }
  1741. static HqlTransformerInfo eclHoistLocatorInfo("EclHoistLocator");
  1742. class EclHoistLocator : public NewHqlTransformer
  1743. {
  1744. public:
  1745. EclHoistLocator(HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches)
  1746. : NewHqlTransformer(eclHoistLocatorInfo), originalMatched(_originalMatches), matched(_matches), alwaysHoistMatches(_alwaysHoistMatches)
  1747. {
  1748. }
  1749. void noteDataset(IHqlExpression * expr, IHqlExpression * hoisted, bool alwaysHoist)
  1750. {
  1751. unsigned match = originalMatched.find(*expr);
  1752. if (match == NotFound)
  1753. {
  1754. if (!hoisted)
  1755. hoisted = expr;
  1756. originalMatched.append(*expr);
  1757. matched.append(*LINK(hoisted));
  1758. alwaysHoistMatches.append(alwaysHoist);
  1759. }
  1760. else if (alwaysHoist && !alwaysHoistMatches.item(match))
  1761. alwaysHoistMatches.replace(true, match);
  1762. }
  1763. void noteScalar(IHqlExpression * expr, IHqlExpression * value)
  1764. {
  1765. if (!originalMatched.contains(*expr))
  1766. {
  1767. OwnedHqlExpr hoisted;
  1768. if (value->getOperator() == no_select)
  1769. {
  1770. bool isNew;
  1771. IHqlExpression * row = querySelectorDataset(value, isNew);
  1772. if(isNew || row->isDatarow())
  1773. {
  1774. if (projectSelectorDatasetToField(row))
  1775. {
  1776. IHqlExpression * ds = row->queryChild(0);
  1777. //Project down to a single field.so implicit fields can still be optimized
  1778. IHqlExpression * field = value->queryChild(1);
  1779. OwnedHqlExpr record = createRecord(field);
  1780. OwnedHqlExpr self = getSelf(record);
  1781. OwnedHqlExpr activeDs = createRow(no_activetable, LINK(ds->queryNormalizedSelector()));
  1782. OwnedHqlExpr selected = replaceSelector(value, row, activeDs);
  1783. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), selected.getClear());
  1784. OwnedHqlExpr transform = createValue(no_newtransform, makeTransformType(record->getType()), LINK(assign));
  1785. OwnedHqlExpr projectedDs = createDataset(no_newusertable, LINK(ds), createComma(LINK(record), LINK(transform)));
  1786. hoisted.setown(replaceChild(row, 0, projectedDs));
  1787. }
  1788. if (!hoisted)
  1789. hoisted.set(row);
  1790. }
  1791. }
  1792. else if (value->getOperator() == no_createset)
  1793. {
  1794. IHqlExpression * ds = value->queryChild(0);
  1795. IHqlExpression * selected = value->queryChild(1);
  1796. OwnedHqlExpr field;
  1797. //Project down to a single field.so implicit fields can still be optimized
  1798. if (selected->getOperator() == no_select)
  1799. field.set(selected->queryChild(1));
  1800. else
  1801. field.setown(createField(valueAtom, selected->getType(), NULL));
  1802. OwnedHqlExpr record = createRecord(field);
  1803. OwnedHqlExpr self = getSelf(record);
  1804. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), LINK(selected));
  1805. OwnedHqlExpr transform = createValue(no_newtransform, makeTransformType(record->getType()), LINK(assign));
  1806. hoisted.setown(createDataset(no_newusertable, LINK(ds), createComma(LINK(record), LINK(transform))));
  1807. }
  1808. if (!hoisted)
  1809. {
  1810. OwnedHqlExpr field = createField(valueAtom, value->getType(), NULL);
  1811. OwnedHqlExpr record = createRecord(field);
  1812. OwnedHqlExpr self = getSelf(record);
  1813. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), LINK(value));
  1814. OwnedHqlExpr transform = createValue(no_transform, makeTransformType(record->getType()), LINK(assign));
  1815. hoisted.setown(createRow(no_createrow, LINK(transform)));
  1816. }
  1817. originalMatched.append(*expr);
  1818. matched.append(*hoisted.getClear());
  1819. alwaysHoistMatches.append(true);
  1820. }
  1821. }
  1822. protected:
  1823. HqlExprCopyArray & originalMatched;
  1824. HqlExprArray & matched;
  1825. BoolArray & alwaysHoistMatches;
  1826. };
  1827. class EclChildSplitPointLocator : public EclHoistLocator
  1828. {
  1829. public:
  1830. EclChildSplitPointLocator(IHqlExpression * _original, HqlExprCopyArray & _selectors, HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches, bool _groupedChildIterators, bool _supportsChildQueries)
  1831. : EclHoistLocator(_originalMatches, _matches, _alwaysHoistMatches), selectors(_selectors), groupedChildIterators(_groupedChildIterators), supportsChildQueries(_supportsChildQueries)
  1832. {
  1833. original = _original;
  1834. okToSelect = false;
  1835. gathered = false;
  1836. conditionalDepth = 0;
  1837. executedOnce = false;
  1838. switch (original->getOperator())
  1839. {
  1840. case no_call:
  1841. case no_externalcall:
  1842. case no_libraryscopeinstance:
  1843. okToSelect = true;
  1844. break;
  1845. }
  1846. }
  1847. void findSplitPoints(IHqlExpression * expr, unsigned from, unsigned to, bool _executedOnce)
  1848. {
  1849. for (unsigned i=from; i < to; i++)
  1850. {
  1851. IHqlExpression * cur = expr->queryChild(i);
  1852. executedOnce = _executedOnce || cur->isAttribute(); // assume attributes are only executed once.
  1853. findSplitPoints(cur);
  1854. }
  1855. }
  1856. protected:
  1857. void findSplitPoints(IHqlExpression * expr)
  1858. {
  1859. //containsNonActiveDataset() would be nice - but that isn't percolated outside assigns etc.
  1860. if (containsAnyDataset(expr) || containsMustHoist(expr))
  1861. {
  1862. if (!gathered)
  1863. {
  1864. gatherAmbiguousSelectors(original);
  1865. gathered = true;
  1866. }
  1867. analyse(expr, 0);
  1868. }
  1869. }
  1870. bool queryHoistDataset(IHqlExpression * ds)
  1871. {
  1872. bool alwaysHoist = true;
  1873. if (executedOnce)
  1874. {
  1875. if (conditionalDepth != 0)
  1876. {
  1877. if (supportsChildQueries || canProcessInline(NULL, ds))
  1878. alwaysHoist = false;
  1879. }
  1880. }
  1881. return alwaysHoist;
  1882. }
  1883. bool queryNoteDataset(IHqlExpression * ds)
  1884. {
  1885. bool alwaysHoist = queryHoistDataset(ds);
  1886. //MORE: It should be possible to remove this condition, but it causes problems with resourcing hsss.xhql amongst others -> disable for the moment
  1887. if (alwaysHoist)
  1888. noteDataset(ds, ds, alwaysHoist);
  1889. return alwaysHoist;
  1890. }
  1891. virtual void analyseExpr(IHqlExpression * expr)
  1892. {
  1893. if (alreadyVisited(expr))
  1894. return;
  1895. node_operator op = expr->getOperator();
  1896. switch (op)
  1897. {
  1898. case no_select:
  1899. //Only interested in the leftmost no_select
  1900. if (expr->hasProperty(newAtom))
  1901. {
  1902. IHqlExpression * ds = expr->queryChild(0);
  1903. if (isEvaluateable(ds))
  1904. {
  1905. //MORE: Following isn't a very nice test - stops implicit denormalize getting messed up
  1906. if (expr->isDataset())
  1907. break;
  1908. //Debtable.....
  1909. //Don't hoist counts on indexes or dataset - it may mean they are evaluated more frequently than need be.
  1910. //If dependencies and root graphs are handled correctly this could be deleted.
  1911. if (isCompoundAggregate(ds))
  1912. break;
  1913. if (!expr->isDatarow() && !expr->isDataset())
  1914. {
  1915. if (queryHoistDataset(ds))
  1916. {
  1917. noteScalar(expr, expr);
  1918. return;
  1919. }
  1920. }
  1921. else
  1922. {
  1923. if (queryNoteDataset(ds))
  1924. return;
  1925. }
  1926. }
  1927. }
  1928. break;
  1929. case no_createset:
  1930. {
  1931. IHqlExpression * ds = expr->queryChild(0);
  1932. if (isEvaluateable(ds))
  1933. {
  1934. if (queryHoistDataset(ds))
  1935. {
  1936. noteScalar(expr, expr);
  1937. //?? queryNoteDataset(ds);
  1938. return;
  1939. }
  1940. }
  1941. break;
  1942. }
  1943. case no_assign:
  1944. {
  1945. IHqlExpression * rhs = expr->queryChild(1);
  1946. //if rhs is a new, evaluatable, dataset then we want to add it
  1947. if (rhs->isDataset() && isEvaluateable(rhs))
  1948. {
  1949. if (queryNoteDataset(rhs))
  1950. return;
  1951. }
  1952. break;
  1953. }
  1954. case no_sizeof:
  1955. case no_allnodes:
  1956. case no_nohoist:
  1957. return;
  1958. case no_globalscope:
  1959. case no_evalonce:
  1960. if (expr->isDataset() || expr->isDatarow())
  1961. noteDataset(expr, expr->queryChild(0), true);
  1962. else
  1963. noteScalar(expr, expr->queryChild(0));
  1964. return;
  1965. case no_thisnode:
  1966. throwUnexpected();
  1967. case no_getgraphresult:
  1968. if (expr->hasProperty(_streaming_Atom) || expr->hasProperty(_distributed_Atom))
  1969. {
  1970. noteDataset(expr, expr, true);
  1971. return;
  1972. }
  1973. break;
  1974. case no_getgraphloopresult:
  1975. noteDataset(expr, expr, true);
  1976. return;
  1977. case no_selectnth:
  1978. if (expr->queryChild(1)->isConstant())
  1979. {
  1980. IHqlExpression * ds = expr->queryChild(0);
  1981. switch (ds->getOperator())
  1982. {
  1983. case no_getgraphresult:
  1984. if (!expr->hasProperty(_streaming_Atom) && !expr->hasProperty(_distributed_Atom))
  1985. break;
  1986. //fallthrough
  1987. case no_getgraphloopresult:
  1988. noteDataset(expr, expr, true);
  1989. return;
  1990. }
  1991. }
  1992. break;
  1993. }
  1994. bool wasOkToSelect = okToSelect;
  1995. if (expr->isDataset())
  1996. {
  1997. switch (expr->getOperator())
  1998. {
  1999. case no_compound_diskread:
  2000. case no_compound_disknormalize:
  2001. case no_compound_diskaggregate:
  2002. case no_compound_diskcount:
  2003. case no_compound_diskgroupaggregate:
  2004. case no_compound_indexread:
  2005. case no_compound_indexnormalize:
  2006. case no_compound_indexaggregate:
  2007. case no_compound_indexcount:
  2008. case no_compound_indexgroupaggregate:
  2009. case no_compound_childread:
  2010. case no_compound_childnormalize:
  2011. case no_compound_childaggregate:
  2012. case no_compound_childcount:
  2013. case no_compound_childgroupaggregate:
  2014. case no_compound_selectnew:
  2015. case no_compound_inline:
  2016. case no_newkeyindex:
  2017. case no_keyindex:
  2018. case no_table:
  2019. okToSelect = false;
  2020. break;
  2021. }
  2022. if (okToSelect && isEvaluateable(expr))
  2023. {
  2024. if (queryNoteDataset(expr))
  2025. return;
  2026. }
  2027. }
  2028. else
  2029. okToSelect = true;
  2030. switch (op)
  2031. {
  2032. case no_if:
  2033. {
  2034. IHqlExpression * cond = expr->queryChild(0);
  2035. // bool condCanBeEvaluated = isEvaluateable(cond, true);
  2036. analyseExpr(cond);
  2037. if (expr->isDataset() || expr->isDatarow())
  2038. conditionalDepth++;
  2039. doAnalyseChildren(expr, 1);
  2040. if (expr->isDataset() || expr->isDatarow())
  2041. conditionalDepth--;
  2042. break;
  2043. }
  2044. case no_mapto:
  2045. {
  2046. analyseExpr(expr->queryChild(0));
  2047. if (expr->isDataset() || expr->isDatarow())
  2048. conditionalDepth++;
  2049. analyseExpr(expr->queryChild(1));
  2050. if (expr->isDataset() || expr->isDatarow())
  2051. conditionalDepth--;
  2052. break;
  2053. }
  2054. default:
  2055. NewHqlTransformer::analyseExpr(expr);
  2056. break;
  2057. }
  2058. okToSelect = wasOkToSelect;
  2059. }
  2060. bool isCompoundAggregate(IHqlExpression * ds)
  2061. {
  2062. return false;
  2063. //Generates worse code unless we take into account whether or not the newDisk operation flags are enabled.
  2064. if (!isTrivialSelectN(ds))
  2065. return false;
  2066. IHqlExpression * agg = ds->queryChild(0);
  2067. if (isSimpleCountAggregate(agg, true))
  2068. return true;
  2069. return false;
  2070. }
  2071. void gatherAmbiguousSelectors(IHqlExpression * expr)
  2072. {
  2073. #ifndef ENSURE_SELSEQ_UID
  2074. //Horrible code to try and cope with ambiguous left selectors.
  2075. //o Tree is ambiguous so same child expression can occur in different contexts - so can't depend on the context it is found in to work out if can hoist
  2076. //o If any selector that is hidden within child expressions matches one in scope then can't hoist it.
  2077. //If the current expression creates a selector, then can't hoist anything that depends on it [only add to hidden if in selectors to reduce searching]
  2078. //o Want to hoist as much as possible.
  2079. if (selectors.empty())
  2080. return;
  2081. unsigned first = getFirstActivityArgument(expr);
  2082. unsigned last = first + getNumActivityArguments(expr);
  2083. unsigned max = expr->numChildren();
  2084. unsigned i;
  2085. HqlExprCopyArray hiddenSelectors;
  2086. for (i = 0; i < first; i++)
  2087. expr->queryChild(i)->gatherTablesUsed(&hiddenSelectors, NULL);
  2088. for (i = last; i < max; i++)
  2089. expr->queryChild(i)->gatherTablesUsed(&hiddenSelectors, NULL);
  2090. ForEachItemIn(iSel, selectors)
  2091. {
  2092. IHqlExpression & cur = selectors.item(iSel);
  2093. if (hiddenSelectors.contains(cur))
  2094. ambiguousSelectors.append(cur);
  2095. }
  2096. switch (getChildDatasetType(expr))
  2097. {
  2098. case childdataset_datasetleft:
  2099. case childdataset_left:
  2100. {
  2101. IHqlExpression * ds = expr->queryChild(0);
  2102. IHqlExpression * selSeq = querySelSeq(expr);
  2103. OwnedHqlExpr left = createSelector(no_left, ds, selSeq);
  2104. if (selectors.contains(*left))
  2105. ambiguousSelectors.append(*left);
  2106. break;
  2107. }
  2108. case childdataset_same_left_right:
  2109. case childdataset_top_left_right:
  2110. case childdataset_nway_left_right:
  2111. {
  2112. IHqlExpression * ds = expr->queryChild(0);
  2113. IHqlExpression * selSeq = querySelSeq(expr);
  2114. OwnedHqlExpr left = createSelector(no_left, ds, selSeq);
  2115. OwnedHqlExpr right = createSelector(no_right, ds, selSeq);
  2116. if (selectors.contains(*left))
  2117. ambiguousSelectors.append(*left);
  2118. if (selectors.contains(*right))
  2119. ambiguousSelectors.append(*right);
  2120. break;
  2121. }
  2122. case childdataset_leftright:
  2123. {
  2124. IHqlExpression * leftDs = expr->queryChild(0);
  2125. IHqlExpression * rightDs = expr->queryChild(1);
  2126. IHqlExpression * selSeq = querySelSeq(expr);
  2127. OwnedHqlExpr left = createSelector(no_left, leftDs, selSeq);
  2128. OwnedHqlExpr right = createSelector(no_right, rightDs, selSeq);
  2129. if (selectors.contains(*left))
  2130. ambiguousSelectors.append(*left);
  2131. if (selectors.contains(*right))
  2132. ambiguousSelectors.append(*right);
  2133. break;
  2134. }
  2135. }
  2136. #endif
  2137. }
  2138. bool isEvaluateable(IHqlExpression * ds, bool ignoreInline = false)
  2139. {
  2140. //Don't hoist an alias - it could create unnecessary duplicate spills - hoist its input
  2141. if (ds->getOperator() == no_dataset_alias)
  2142. return false;
  2143. //Not allowed to hoist
  2144. if (isContextDependent(ds, (conditionalDepth == 0), true))
  2145. return false;
  2146. //MORE: Needs more work for child queries - need a GroupedChildIterator activity
  2147. if (isGrouped(ds) && selectors.ordinality() && !groupedChildIterators)
  2148. return false;
  2149. //Check datasets are available
  2150. HqlExprCopyArray scopeUsed;
  2151. ds->gatherTablesUsed(NULL, &scopeUsed);
  2152. ForEachItemIn(i, scopeUsed)
  2153. {
  2154. IHqlExpression & cur = scopeUsed.item(i);
  2155. if (!selectors.contains(cur))
  2156. return false;
  2157. if (ambiguousSelectors.contains(cur))
  2158. return false;
  2159. }
  2160. #ifdef MINIMAL_CHANGES
  2161. if (isInlineTrivialDataset(ds) || (!ignoreInline && canProcessInline(NULL, ds)))
  2162. // if (isInlineTrivialDataset(ds))// || (!ignoreInline && canProcessInline(NULL, ds)))
  2163. return false;
  2164. #else
  2165. //Not worth hoisting...
  2166. if (isTrivialDataset(ds))
  2167. return false;
  2168. #endif
  2169. return true;
  2170. }
  2171. protected:
  2172. IHqlExpression * original;
  2173. HqlExprCopyArray & selectors;
  2174. HqlExprCopyArray ambiguousSelectors;
  2175. unsigned conditionalDepth;
  2176. bool okToSelect;
  2177. bool gathered;
  2178. bool groupedChildIterators;
  2179. bool executedOnce;
  2180. bool supportsChildQueries;
  2181. };
  2182. void EclResourcer::gatherChildSplitPoints(IHqlExpression * expr, BoolArray & alwaysHoistChild, ResourcerInfo * info, unsigned first, unsigned last)
  2183. {
  2184. //NB: Don't call member functions to ensure correct nesting of transform mutexes.
  2185. EclChildSplitPointLocator locator(expr, activeSelectors, info->originalChildDependents, info->childDependents, alwaysHoistChild, options.groupedChildIterators, options.supportsChildQueries);
  2186. unsigned max = expr->numChildren();
  2187. //If child queries are supported then don't hoist the expressions if they might only be evaluated once
  2188. //because they may be conditional
  2189. switch (expr->getOperator())
  2190. {
  2191. case no_setresult:
  2192. case no_selectnth:
  2193. //set results, only done once=>don't hoist conditionals
  2194. locator.findSplitPoints(expr, last, max, true);
  2195. return;
  2196. }
  2197. locator.findSplitPoints(expr, 0, first, true); // IF() conditions only evaluated once... => don't force
  2198. locator.findSplitPoints(expr, last, max, false);
  2199. }
  2200. class EclThisNodeLocator : public EclHoistLocator
  2201. {
  2202. public:
  2203. EclThisNodeLocator(HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches) : EclHoistLocator(_originalMatches, _matches, _alwaysHoistMatches)
  2204. {
  2205. allNodesDepth = 0;
  2206. }
  2207. protected:
  2208. virtual void analyseExpr(IHqlExpression * expr)
  2209. {
  2210. //NB: This doesn't really work for no_thisnode occurring in multiple contexts. We should probably hoist it from everywhere if it is hoistable from anywhere,
  2211. // although theoretically that gives us problems with ambiguous selectors.
  2212. if (alreadyVisited(expr) || !containsThisNode(expr))
  2213. return;
  2214. node_operator op = expr->getOperator();
  2215. switch (op)
  2216. {
  2217. case no_allnodes:
  2218. allNodesDepth++;
  2219. NewHqlTransformer::analyseExpr(expr);
  2220. allNodesDepth--;
  2221. return;
  2222. case no_thisnode:
  2223. if (allNodesDepth == 0)
  2224. {
  2225. if (expr->isDataset() || expr->isDatarow())
  2226. noteDataset(expr, expr->queryChild(0), true);
  2227. else
  2228. noteScalar(expr, expr->queryChild(0));
  2229. return;
  2230. }
  2231. allNodesDepth--;
  2232. NewHqlTransformer::analyseExpr(expr);
  2233. allNodesDepth++;
  2234. return;
  2235. }
  2236. NewHqlTransformer::analyseExpr(expr);
  2237. }
  2238. protected:
  2239. unsigned allNodesDepth;
  2240. };
  2241. bool EclResourcer::findSplitPoints(IHqlExpression * expr)
  2242. {
  2243. ResourcerInfo * info = queryResourceInfo(expr);
  2244. bool savedInsideNeverSplit = insideNeverSplit;
  2245. if (info && info->numUses)
  2246. {
  2247. if (insideNeverSplit)
  2248. info->neverSplit = true;
  2249. if (info->isAlreadyInScope && (info->numUses == 0) && expr->isDatarow())
  2250. {
  2251. // A row is already bound to a temporary
  2252. info->isActivity = true;
  2253. info->containsActivity = true;
  2254. info->numUses++;
  2255. //More: May need to force child activities to not be resourced (e.g., if somehow visited via another path)
  2256. //info->preserve = true;
  2257. return info->containsActivity;
  2258. }
  2259. if (info->isAlreadyInScope || info->isActivity || !info->containsActivity)
  2260. {
  2261. info->numUses++;
  2262. return info->containsActivity;
  2263. }
  2264. }
  2265. else
  2266. {
  2267. info = queryCreateResourceInfo(expr);
  2268. info->numUses++;
  2269. if (insideNeverSplit)
  2270. info->neverSplit = true;
  2271. bool isActivity = true;
  2272. switch (expr->getOperator())
  2273. {
  2274. case no_select:
  2275. //either a select from a setresult or use of a child-dataset
  2276. if (isNewSelector(expr))
  2277. {
  2278. info->containsActivity = findSplitPoints(expr->queryChild(0));
  2279. assertex(queryResourceInfo(expr->queryChild(0))->isActivity);
  2280. }
  2281. if (expr->isDataset() || expr->isDatarow())
  2282. {
  2283. info->isActivity = true;
  2284. info->containsActivity = true;
  2285. }
  2286. return info->containsActivity;
  2287. case no_mapto:
  2288. throwUnexpected();
  2289. info->containsActivity = findSplitPoints(expr->queryChild(1));
  2290. return info->containsActivity;
  2291. case no_activerow:
  2292. info->isActivity = true;
  2293. info->containsActivity = false;
  2294. return false;
  2295. case no_attr:
  2296. case no_attr_expr:
  2297. case no_attr_link:
  2298. case no_rowset: // don't resource this as an activity
  2299. case no_getgraphloopresultset:
  2300. info->isActivity = false;
  2301. info->containsActivity = false;
  2302. return false;
  2303. case no_datasetlist:
  2304. isActivity = false;
  2305. break;
  2306. case no_rowsetrange:
  2307. {
  2308. //Don't resource this as an activity if it is a function of the input graph rows,
  2309. //however we do want to if it is coming from a dataset list.
  2310. IHqlExpression * ds = expr->queryChild(0);
  2311. //MORE: Should walk further down the tree to allow for nested rowsetranges etc.
  2312. if (ds->getOperator() == no_rowset || ds->getOperator() == no_getgraphloopresultset)
  2313. {
  2314. info->isActivity = false;
  2315. info->containsActivity = false;
  2316. return false;
  2317. }
  2318. isActivity = false;
  2319. break;
  2320. }
  2321. case no_keyedlimit:
  2322. if (options.preventKeyedSplit)
  2323. insideNeverSplit = true;
  2324. break;
  2325. case no_filter:
  2326. if (options.preventKeyedSplit && filterIsKeyed(expr))
  2327. insideNeverSplit = true;
  2328. break;
  2329. case no_hqlproject:
  2330. case no_newusertable:
  2331. case no_aggregate:
  2332. case no_newaggregate:
  2333. if (options.preventKeyedSplit && expr->hasProperty(keyedAtom))
  2334. insideNeverSplit = true;
  2335. break;
  2336. case no_stepped:
  2337. case no_mergejoin:
  2338. case no_nwayjoin:
  2339. if (options.preventSteppedSplit)
  2340. insideNeverSplit = true;
  2341. break;
  2342. case no_compound_diskread:
  2343. case no_compound_disknormalize:
  2344. case no_compound_diskaggregate:
  2345. case no_compound_diskcount:
  2346. case no_compound_diskgroupaggregate:
  2347. case no_compound_indexread:
  2348. case no_compound_indexnormalize:
  2349. case no_compound_indexaggregate:
  2350. case no_compound_indexcount:
  2351. case no_compound_indexgroupaggregate:
  2352. case no_compound_childread:
  2353. case no_compound_childnormalize:
  2354. case no_compound_childaggregate:
  2355. case no_compound_childcount:
  2356. case no_compound_childgroupaggregate:
  2357. case no_compound_selectnew:
  2358. case no_compound_inline:
  2359. insideNeverSplit = true;
  2360. break;
  2361. }
  2362. ITypeInfo * type = expr->queryType();
  2363. if (!type || type->isScalar())
  2364. {
  2365. insideNeverSplit = savedInsideNeverSplit;
  2366. return false;
  2367. }
  2368. info->isActivity = isActivity;
  2369. info->containsActivity = true;
  2370. }
  2371. unsigned first = getFirstActivityArgument(expr);
  2372. unsigned last = first + getNumActivityArguments(expr);
  2373. if (options.hoistResourced)
  2374. {
  2375. BoolArray alwaysHoistChild;
  2376. switch (expr->getOperator())
  2377. {
  2378. case no_allnodes:
  2379. {
  2380. //MORE: This needs to recursively walk and lift any contained no_selfnode, but don't go past another nested no_allnodes;
  2381. EclThisNodeLocator locator(info->originalChildDependents, info->childDependents, alwaysHoistChild);
  2382. locator.analyse(expr->queryChild(0), 0);
  2383. break;
  2384. }
  2385. default:
  2386. {
  2387. for (unsigned idx=first; idx < last; idx++)
  2388. {
  2389. IHqlExpression * cur = expr->queryChild(idx);
  2390. findSplitPoints(cur);
  2391. }
  2392. insideNeverSplit = savedInsideNeverSplit;
  2393. gatherChildSplitPoints(expr, alwaysHoistChild, info, first, last);
  2394. break;
  2395. }
  2396. }
  2397. insideNeverSplit = false;
  2398. ForEachItemIn(i2, info->childDependents)
  2399. {
  2400. IHqlExpression & cur = info->childDependents.item(i2);
  2401. if (alwaysHoistChild.item(i2))
  2402. findSplitPoints(&cur);
  2403. else
  2404. conditionalChildren.append(cur);
  2405. }
  2406. }
  2407. else
  2408. {
  2409. for (unsigned idx=first; idx < last; idx++)
  2410. findSplitPoints(expr->queryChild(idx));
  2411. }
  2412. insideNeverSplit = savedInsideNeverSplit;
  2413. return info->containsActivity;
  2414. }
  2415. void EclResourcer::findSplitPoints(HqlExprArray & exprs)
  2416. {
  2417. ForEachItemIn(idx, exprs)
  2418. findSplitPoints(&exprs.item(idx));
  2419. extendSplitPoints();
  2420. }
  2421. void EclResourcer::extendSplitPoints()
  2422. {
  2423. for (unsigned i=0; i < conditionalChildren.ordinality(); i++)
  2424. {
  2425. IHqlExpression & cur = conditionalChildren.item(i);
  2426. if (isWorthForcingHoist(&cur))
  2427. findSplitPoints(&cur);
  2428. }
  2429. }
  2430. //------------------------------------------------------------------------------------------
  2431. // PASS2: Actually create the subgraphs based on splitters.
  2432. void EclResourcer::createInitialGraph(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerGraph, LinkKind linkKind, bool forceNewGraph)
  2433. {
  2434. ResourcerInfo * info = queryResourceInfo(expr);
  2435. if (!info || !info->containsActivity)
  2436. return;
  2437. LinkKind childLinkKind = UnconditionalLink;
  2438. Linked<ResourceGraphInfo> thisGraph = ownerGraph;
  2439. bool forceNewChildGraph = false;
  2440. if (info->isActivity)
  2441. {
  2442. //Need to ensure no_libraryselects are not separated from the no_libraryscopeinstance
  2443. //so ensure they are placed in the same graph.
  2444. node_operator op = expr->getOperator();
  2445. if (op == no_libraryselect)
  2446. {
  2447. ResourcerInfo * moduleInfo = queryResourceInfo(expr->queryChild(1));
  2448. if (!info->graph && moduleInfo->graph)
  2449. info->graph.set(moduleInfo->graph);
  2450. }
  2451. if (info->graph)
  2452. {
  2453. connectGraphs(info->graph, expr, ownerGraph, owner, linkKind);
  2454. info->numExternalUses++;
  2455. return;
  2456. }
  2457. unsigned numUses = info->numUses;
  2458. switch (op)
  2459. {
  2460. case no_libraryscopeinstance:
  2461. numUses = 1;
  2462. break;
  2463. case no_libraryselect:
  2464. forceNewGraph = true;
  2465. break;
  2466. }
  2467. if (!ownerGraph || numUses > 1 || (linkKind != UnconditionalLink) || forceNewGraph)
  2468. {
  2469. thisGraph.setown(createGraph());
  2470. connectGraphs(thisGraph, expr, ownerGraph, owner, linkKind);
  2471. info->numExternalUses++;
  2472. }
  2473. info->graph.set(thisGraph);
  2474. switch (expr->getOperator())
  2475. {
  2476. case no_compound:
  2477. //NB: First argument is forced into a separate graph
  2478. createInitialGraph(expr->queryChild(0), expr, NULL, UnconditionalLink, true);
  2479. createInitialGraph(expr->queryChild(1), expr, thisGraph, UnconditionalLink, false);
  2480. return;
  2481. case no_executewhen:
  2482. {
  2483. bool newGraph = expr->isAction() && (options.targetClusterType == HThorCluster);
  2484. createInitialGraph(expr->queryChild(0), expr, thisGraph, UnconditionalLink, newGraph);
  2485. createInitialGraph(expr->queryChild(1), expr, thisGraph, UnconditionalLink, true);
  2486. return;
  2487. }
  2488. case no_keyindex:
  2489. case no_newkeyindex:
  2490. return;
  2491. case no_parallel:
  2492. {
  2493. ForEachChild(i, expr)
  2494. createInitialGraph(expr->queryChild(i), expr, thisGraph, UnconditionalLink, true);
  2495. return;
  2496. }
  2497. case no_if:
  2498. //conditional nodes, the child branches are marked as conditional
  2499. childLinkKind = UnconditionalLink;
  2500. thisGraph->mergedConditionSource = true;
  2501. if (!options.noConditionalLinks || expr->isAction())
  2502. forceNewChildGraph = true;
  2503. break;
  2504. // case no_nonempty:
  2505. case no_sequential:
  2506. {
  2507. unsigned first = getFirstActivityArgument(expr);
  2508. unsigned last = first + getNumActivityArguments(expr);
  2509. createInitialGraph(expr->queryChild(first), expr, thisGraph, SequenceLink, true);
  2510. for (unsigned idx = first+1; idx < last; idx++)
  2511. createInitialGraph(expr->queryChild(idx), expr, thisGraph, SequenceLink, true);
  2512. return;
  2513. }
  2514. case no_case:
  2515. case no_map:
  2516. {
  2517. throwUnexpected();
  2518. }
  2519. case no_output:
  2520. {
  2521. //Tag the inputs to an output statement, so that if a spill was going to occur we read
  2522. //from the output file instead of spilling.
  2523. //Needs the grouping to be saved in the same way. Could cope with compressed matching, but not
  2524. //much point - since fairly unlikely.
  2525. IHqlExpression * filename = expr->queryChild(1);
  2526. if (filename && (filename->getOperator() == no_constant) && !expr->hasProperty(xmlAtom) && !expr->hasProperty(csvAtom))
  2527. {
  2528. IHqlExpression * dataset = expr->queryChild(0);
  2529. if (expr->hasProperty(groupedAtom) == (dataset->queryType()->queryGroupInfo() != NULL))
  2530. {
  2531. StringBuffer filenameText;
  2532. filename->queryValue()->getStringValue(filenameText);
  2533. ResourcerInfo * childInfo = queryResourceInfo(dataset);
  2534. if (!childInfo->linkedFromChild && !isUpdatedConditionally(expr))
  2535. childInfo->outputToUseForSpill = expr;
  2536. }
  2537. }
  2538. if (isUpdatedConditionally(expr))
  2539. thisGraph->mergedConditionSource = true;
  2540. break;
  2541. }
  2542. case no_buildindex:
  2543. if (isUpdatedConditionally(expr))
  2544. thisGraph->mergedConditionSource = true;
  2545. break;
  2546. }
  2547. }
  2548. unsigned first = getFirstActivityArgument(expr);
  2549. unsigned last = first + getNumActivityArguments(expr);
  2550. for (unsigned idx = first; idx < last; idx++)
  2551. createInitialGraph(expr->queryChild(idx), expr, thisGraph, childLinkKind, forceNewChildGraph);
  2552. ForEachItemIn(i2, info->childDependents)
  2553. {
  2554. IHqlExpression & cur = info->childDependents.item(i2);
  2555. if (isResourcedActivity(&cur))
  2556. createInitialGraph(&cur, expr, thisGraph, SequenceLink, true);
  2557. }
  2558. }
  2559. void EclResourcer::createInitialGraphs(HqlExprArray & exprs)
  2560. {
  2561. ForEachItemIn(idx, exprs)
  2562. createInitialGraph(&exprs.item(idx), NULL, NULL, UnconditionalLink, false);
  2563. }
  2564. void EclResourcer::createInitialRemoteGraph(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerGraph, bool forceNewGraph)
  2565. {
  2566. ResourcerInfo * info = queryResourceInfo(expr);
  2567. if (!info || !info->containsActivity)
  2568. return;
  2569. Linked<ResourceGraphInfo> thisGraph = ownerGraph;
  2570. if (info->isActivity)
  2571. {
  2572. if (info->graph)
  2573. {
  2574. connectGraphs(info->graph, expr, ownerGraph, owner, UnconditionalLink);
  2575. info->numExternalUses++;
  2576. return;
  2577. }
  2578. if (!ownerGraph || forceNewGraph)
  2579. {
  2580. thisGraph.setown(createGraph());
  2581. connectGraphs(thisGraph, expr, ownerGraph, owner, UnconditionalLink);
  2582. info->numExternalUses++;
  2583. }
  2584. info->graph.set(thisGraph);
  2585. switch (expr->getOperator())
  2586. {
  2587. case no_compound:
  2588. createInitialRemoteGraph(expr->queryChild(0), expr, NULL, true);
  2589. createInitialRemoteGraph(expr->queryChild(1), expr, thisGraph, false);
  2590. return;
  2591. case no_executewhen:
  2592. createInitialRemoteGraph(expr->queryChild(0), expr, thisGraph, false);
  2593. createInitialRemoteGraph(expr->queryChild(1), expr, thisGraph, true);
  2594. return;
  2595. }
  2596. }
  2597. unsigned first = getFirstActivityArgument(expr);
  2598. unsigned last = first + getNumActivityArguments(expr);
  2599. for (unsigned idx = first; idx < last; idx++)
  2600. createInitialRemoteGraph(expr->queryChild(idx), expr, thisGraph, false);
  2601. }
  2602. void EclResourcer::createInitialRemoteGraphs(HqlExprArray & exprs)
  2603. {
  2604. ForEachItemIn(idx, exprs)
  2605. createInitialRemoteGraph(&exprs.item(idx), NULL, NULL, false);
  2606. }
  2607. //------------------------------------------------------------------------------------------
  2608. // PASS3: Tag graphs/links that are conditional or unconditional
  2609. void EclResourcer::markChildDependentsAsUnconditional(ResourcerInfo * info, IHqlExpression * condition)
  2610. {
  2611. if (options.hoistResourced)
  2612. {
  2613. ForEachItemIn(i2, info->childDependents)
  2614. {
  2615. IHqlExpression & cur = info->childDependents.item(i2);
  2616. if (isResourcedActivity(&cur))
  2617. markAsUnconditional(&cur, NULL, condition);
  2618. }
  2619. }
  2620. }
  2621. void EclResourcer::markAsUnconditional(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, IHqlExpression * condition)
  2622. {
  2623. ResourcerInfo * info = queryResourceInfo(expr);
  2624. if (!info || !info->containsActivity)
  2625. return;
  2626. if (!info->isActivity)
  2627. {
  2628. unsigned first = getFirstActivityArgument(expr);
  2629. unsigned last = first + getNumActivityArguments(expr);
  2630. for (unsigned idx=first; idx < last; idx++)
  2631. markAsUnconditional(expr->queryChild(idx), ownerGraph, condition);
  2632. return;
  2633. }
  2634. if (condition)
  2635. if (info->addCondition(condition))
  2636. condition = NULL;
  2637. if (info->pathToExpr == ResourcerInfo::PathUnconditional)
  2638. return;
  2639. if ((info->pathToExpr == ResourcerInfo::PathConditional) && condition)
  2640. {
  2641. if (targetClusterType == RoxieCluster)
  2642. {
  2643. if (spillMultiCondition)
  2644. {
  2645. if (info->graph != ownerGraph)
  2646. info->graph->isUnconditional = true;
  2647. }
  2648. return;
  2649. }
  2650. else
  2651. {
  2652. if (info->graph != ownerGraph)
  2653. return;
  2654. }
  2655. }
  2656. bool wasConditional = (info->pathToExpr == ResourcerInfo::PathConditional);
  2657. if (!condition)
  2658. {
  2659. info->pathToExpr = ResourcerInfo::PathUnconditional;
  2660. if (info->graph != ownerGraph)
  2661. info->graph->isUnconditional = true;
  2662. }
  2663. else
  2664. info->pathToExpr = ResourcerInfo::PathConditional;
  2665. node_operator op = expr->getOperator();
  2666. switch (op)
  2667. {
  2668. case no_if:
  2669. if (options.noConditionalLinks)
  2670. break;
  2671. if (condition)
  2672. markCondition(expr, condition, wasConditional);
  2673. else
  2674. {
  2675. //This list is processed in a second phase.
  2676. if (rootConditions.find(*expr) == NotFound)
  2677. rootConditions.append(*LINK(expr));
  2678. }
  2679. markChildDependentsAsUnconditional(info, condition);
  2680. return;
  2681. case no_sequential:
  2682. // case no_nonempty:
  2683. if (!options.isChildQuery)
  2684. {
  2685. unsigned first = getFirstActivityArgument(expr);
  2686. unsigned last = first + getNumActivityArguments(expr);
  2687. IHqlExpression * child0 = expr->queryChild(0);
  2688. markAsUnconditional(child0, info->graph, condition);
  2689. queryResourceInfo(child0)->graph->hasConditionSource = true; // force it to generate even if contains something very simple e.g., null action
  2690. for (unsigned idx = first+1; idx < last; idx++)
  2691. {
  2692. OwnedHqlExpr tag = createAttribute(instanceAtom, LINK(expr), getSizetConstant(idx), LINK(condition));
  2693. IHqlExpression * child = expr->queryChild(idx);
  2694. markAsUnconditional(child, queryResourceInfo(child)->graph, tag);
  2695. queryResourceInfo(child)->setConditionSource(tag, !wasConditional);
  2696. }
  2697. markChildDependentsAsUnconditional(info, condition);
  2698. return;
  2699. }
  2700. break;
  2701. case no_case:
  2702. case no_map:
  2703. UNIMPLEMENTED;
  2704. }
  2705. unsigned first = getFirstActivityArgument(expr);
  2706. unsigned last = first + getNumActivityArguments(expr);
  2707. for (unsigned idx=first; idx < last; idx++)
  2708. markAsUnconditional(expr->queryChild(idx), info->graph, condition);
  2709. markChildDependentsAsUnconditional(info, condition);
  2710. }
  2711. void EclResourcer::markConditionBranch(unsigned childIndex, IHqlExpression * expr, IHqlExpression * condition, bool wasConditional)
  2712. {
  2713. IHqlExpression * child = expr->queryChild(childIndex);
  2714. if (child)
  2715. {
  2716. OwnedHqlExpr tag = createAttribute(((childIndex==1) ? trueAtom : falseAtom), LINK(expr), LINK(condition));
  2717. markAsUnconditional(child, queryResourceInfo(child)->graph, tag);
  2718. queryResourceInfo(child)->setConditionSource(tag, !wasConditional);
  2719. }
  2720. }
  2721. void EclResourcer::markCondition(IHqlExpression * expr, IHqlExpression * condition, bool wasConditional)
  2722. {
  2723. markConditionBranch(1, expr, condition, wasConditional);
  2724. markConditionBranch(2, expr, condition, wasConditional);
  2725. }
  2726. void EclResourcer::markConditions(HqlExprArray & exprs)
  2727. {
  2728. ForEachItemIn(idx, exprs)
  2729. markAsUnconditional(&exprs.item(idx), NULL, NULL);
  2730. ForEachItemIn(idx2, rootConditions)
  2731. markCondition(&rootConditions.item(idx2), NULL, false);
  2732. }
  2733. //------------------------------------------------------------------------------------------
  2734. // PASS4: Split subgraphs based on resource requirements for activities
  2735. //This will need to be improved if we allow backtracking to get the best combination of activities to fit in the subgraph
  2736. void EclResourcer::createResourceSplit(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerNewGraph, ResourceGraphInfo * originalGraph)
  2737. {
  2738. ResourcerInfo * info = queryResourceInfo(expr);
  2739. info->graph.setown(createGraph());
  2740. info->graph->isUnconditional = originalGraph->isUnconditional;
  2741. changeGraph(expr, info->graph);
  2742. connectGraphs(info->graph, expr, ownerNewGraph, owner, UnconditionalLink);
  2743. info->numExternalUses++;
  2744. }
  2745. void EclResourcer::getResources(IHqlExpression * expr, CResources & exprResources)
  2746. {
  2747. ::getResources(expr, exprResources, options);
  2748. }
  2749. bool EclResourcer::calculateResourceSpillPoints(IHqlExpression * expr, ResourceGraphInfo * graph, CResources & resourcesSoFar, bool hasGoodSpillPoint, bool canSpill)
  2750. {
  2751. ResourcerInfo * info = queryResourceInfo(expr);
  2752. if (!info || !info->containsActivity)
  2753. return true;
  2754. if (!info->isActivity)
  2755. {
  2756. unsigned first = getFirstActivityArgument(expr);
  2757. unsigned last = first + getNumActivityArguments(expr);
  2758. if (last - first == 1)
  2759. return calculateResourceSpillPoints(expr->queryChild(first), graph, resourcesSoFar, hasGoodSpillPoint, canSpill);
  2760. for (unsigned idx = first; idx < last; idx++)
  2761. calculateResourceSpillPoints(expr->queryChild(idx), graph, resourcesSoFar, false, canSpill);
  2762. return true;
  2763. }
  2764. if (info->graph != graph)
  2765. return true;
  2766. CResources exprResources(clusterSize);
  2767. getResources(expr, exprResources);
  2768. info->isSpillPoint = false;
  2769. Owned<CResources> curResources = LINK(&resourcesSoFar);
  2770. if (resourcesSoFar.addExceeds(exprResources, *resourceLimit))
  2771. {
  2772. if (hasGoodSpillPoint)
  2773. return false;
  2774. info->isSpillPoint = true;
  2775. spilled = true;
  2776. curResources.setown(new CResources(clusterSize));
  2777. if (exprResources.exceeds(*resourceLimit))
  2778. throwError2(HQLERR_CannotResourceActivity, getOpString(expr->getOperator()), clusterSize);
  2779. }
  2780. if (options.minimizeSkewBeforeSpill)
  2781. {
  2782. if (canSpill && heavyweightAndReducesSizeOrSkew(expr))
  2783. {
  2784. //if the input activity is going to cause us to run out of resources, then it is going to be better to split here than anywhere else
  2785. //this code may conceivably cause extra spills far away because the hash distributes are moved.
  2786. IHqlExpression * childExpr = expr->queryChild(0);
  2787. ResourcerInfo * childInfo = queryResourceInfo(childExpr);
  2788. if (childInfo->graph == graph)
  2789. {
  2790. CResources childResources(clusterSize);
  2791. getResources(childExpr, childResources);
  2792. childResources.add(exprResources);
  2793. if (curResources->addExceeds(childResources, *resourceLimit))
  2794. {
  2795. info->isSpillPoint = true;
  2796. spilled = true;
  2797. calculateResourceSpillPoints(childExpr, graph, exprResources, false, true);
  2798. return true;
  2799. }
  2800. }
  2801. //otherwise continue as normal.
  2802. }
  2803. }
  2804. curResources->add(exprResources);
  2805. unsigned first = getFirstActivityArgument(expr);
  2806. unsigned last = first + getNumActivityArguments(expr);
  2807. if (hasGoodSpillPoint)
  2808. {
  2809. if (exprResources.resource[RESheavy] || exprResources.resource[REShashdist] || last-first != 1)
  2810. hasGoodSpillPoint = false;
  2811. }
  2812. else if (!info->isSpillPoint && canSpill)
  2813. {
  2814. if (lightweightAndReducesDatasetSize(expr) || queryHint(expr, spillAtom))
  2815. {
  2816. CResources savedResources(*curResources);
  2817. if (!calculateResourceSpillPoints(expr->queryChild(0), graph, *curResources, true, true))
  2818. {
  2819. curResources->set(savedResources);
  2820. info->isSpillPoint = true;
  2821. spilled = true;
  2822. calculateResourceSpillPoints(expr->queryChild(0), graph, exprResources, false, true);
  2823. }
  2824. return true;
  2825. }
  2826. }
  2827. if (expr->getOperator() == no_if)
  2828. {
  2829. //For conditions, spill on intersection of resources used, not union.
  2830. CResources savedResources(*curResources);
  2831. if (!calculateResourceSpillPoints(expr->queryChild(1), graph, *curResources, hasGoodSpillPoint, true))
  2832. return false;
  2833. if (expr->queryChild(2))
  2834. {
  2835. if (!calculateResourceSpillPoints(expr->queryChild(2), graph, savedResources, hasGoodSpillPoint, true))
  2836. return false;
  2837. curResources->maximize(savedResources);
  2838. }
  2839. }
  2840. else
  2841. {
  2842. for (unsigned idx = first; idx < last; idx++)
  2843. if (!calculateResourceSpillPoints(expr->queryChild(idx), graph, *curResources, hasGoodSpillPoint, true))
  2844. return false;
  2845. }
  2846. return true;
  2847. }
  2848. void EclResourcer::insertResourceSpillPoints(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerOriginalGraph, ResourceGraphInfo * ownerNewGraph)
  2849. {
  2850. ResourcerInfo * info = queryResourceInfo(expr);
  2851. if (!info || !info->containsActivity)
  2852. return;
  2853. if (!info->isActivity)
  2854. {
  2855. unsigned first = getFirstActivityArgument(expr);
  2856. unsigned last = first + getNumActivityArguments(expr);
  2857. for (unsigned idx = first; idx < last; idx++)
  2858. insertResourceSpillPoints(expr->queryChild(idx), expr, ownerOriginalGraph, ownerNewGraph);
  2859. return;
  2860. }
  2861. ResourceGraphInfo * originalGraph = info->graph; //NB: Graph will never cease to exist, so don't need to link.
  2862. if (originalGraph != ownerOriginalGraph)
  2863. return;
  2864. if (info->isSpillPoint)
  2865. createResourceSplit(expr, owner, ownerNewGraph, originalGraph);
  2866. else if (info->graph != ownerNewGraph)
  2867. changeGraph(expr, ownerNewGraph);
  2868. CResources exprResources(clusterSize);
  2869. getResources(expr, exprResources);
  2870. bool ok = info->graph->allocateResources(exprResources, *resourceLimit);
  2871. assertex(ok);
  2872. if (expr->getOperator() == no_if)
  2873. {
  2874. CResources savedResources(info->graph->resources);
  2875. insertResourceSpillPoints(expr->queryChild(1), expr, originalGraph, info->graph);
  2876. if (expr->queryChild(2))
  2877. {
  2878. CResources branchResources(info->graph->resources);
  2879. info->graph->resources.set(savedResources);
  2880. insertResourceSpillPoints(expr->queryChild(2), expr, originalGraph, info->graph);
  2881. info->graph->resources.maximize(branchResources);
  2882. }
  2883. }
  2884. else
  2885. {
  2886. unsigned first = getFirstActivityArgument(expr);
  2887. unsigned last = first + getNumActivityArguments(expr);
  2888. for (unsigned idx = first; idx < last; idx++)
  2889. insertResourceSpillPoints(expr->queryChild(idx), expr, originalGraph, info->graph);
  2890. }
  2891. }
  2892. void EclResourcer::resourceSubGraph(ResourceGraphInfo * graph)
  2893. {
  2894. if (graph->beenResourced)
  2895. return;
  2896. graph->beenResourced = true;
  2897. ForEachItemIn(idx, graph->sources)
  2898. resourceSubGraph(graph->sources.item(idx).sourceGraph);
  2899. IHqlExpression * sourceNode = graph->sinks.item(0).sourceNode->queryBody();
  2900. #ifdef _DEBUG
  2901. //Sanity check, ensure there is only a single sink for this graph.
  2902. //However because libraryselects are tightly bound to their library instance there may be multiple library selects.
  2903. //They won't affect the resourcing though, since they'll plug into the same library instance, and the selects use no resources.
  2904. ForEachItemIn(idx2, graph->sinks)
  2905. {
  2906. IHqlExpression * thisSink = graph->sinks.item(idx2).sourceNode->queryBody();
  2907. if (thisSink->getOperator() != no_libraryselect)
  2908. assertex(thisSink == sourceNode);
  2909. }
  2910. #endif
  2911. spilled = false;
  2912. CResources resources(clusterSize);
  2913. calculateResourceSpillPoints(sourceNode, graph, resources, false, false);
  2914. if (spilled)
  2915. insertResourceSpillPoints(sourceNode, NULL, graph, graph);
  2916. else
  2917. graph->resources.set(resources);
  2918. }
  2919. void EclResourcer::resourceSubGraphs(HqlExprArray & exprs)
  2920. {
  2921. ForEachItemIn(idx, graphs)
  2922. resourceSubGraph(&graphs.item(idx));
  2923. }
  2924. //------------------------------------------------------------------------------------------
  2925. // PASS5: Link subrgaphs with dependency information so they don't get merged by accident.
  2926. void EclResourcer::addDependencySource(IHqlExpression * search, ResourceGraphInfo * curGraph, IHqlExpression * expr)
  2927. {
  2928. //MORE: Should we check this doesn't already exist?
  2929. dependencySource.search.append(*LINK(search));
  2930. dependencySource.graphs.append(*LINK(curGraph));
  2931. dependencySource.exprs.append(*LINK(expr));
  2932. }
  2933. void EclResourcer::addDependencyUse(IHqlExpression * search, ResourceGraphInfo * curGraph, IHqlExpression * expr)
  2934. {
  2935. unsigned index = dependencySource.search.find(*search);
  2936. if (index != NotFound)
  2937. {
  2938. if (&dependencySource.graphs.item(index) == curGraph)
  2939. {
  2940. //Don't give a warning if get/set is within the same activity (e.g., within a local())
  2941. if (&dependencySource.exprs.item(index) != expr)
  2942. //errors->reportWarning(HQLWRN_RecursiveDependendencies, HQLWRN_RecursiveDependendencies_Text, *codeGeneratorAtom, 0, 0, 0);
  2943. errors->reportError(HQLWRN_RecursiveDependendencies, HQLWRN_RecursiveDependendencies_Text, *codeGeneratorAtom, 0, 0, 0);
  2944. }
  2945. else
  2946. {
  2947. ResourceGraphLink * link = new ResourceGraphDependencyLink(&dependencySource.graphs.item(index), &dependencySource.exprs.item(index), curGraph, expr);
  2948. curGraph->dependsOn.append(*link);
  2949. links.append(*link);
  2950. }
  2951. }
  2952. }
  2953. void EclResourcer::addRefExprDependency(IHqlExpression * expr, ResourceGraphInfo * curGraph, IHqlExpression * activityExpr)
  2954. {
  2955. IHqlExpression * filename = queryTableFilename(expr);
  2956. if (filename)
  2957. {
  2958. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  2959. addDependencySource(value, curGraph, activityExpr);
  2960. }
  2961. }
  2962. bool EclResourcer::addExprDependency(IHqlExpression * expr, ResourceGraphInfo * curGraph, IHqlExpression * activityExpr)
  2963. {
  2964. switch (expr->getOperator())
  2965. {
  2966. case no_buildindex:
  2967. case no_output:
  2968. {
  2969. IHqlExpression * filename = queryRealChild(expr, 1);
  2970. if (filename)
  2971. {
  2972. switch (filename->getOperator())
  2973. {
  2974. case no_pipe:
  2975. // allWritten = true;
  2976. break;
  2977. default:
  2978. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  2979. addDependencySource(value, curGraph, activityExpr);
  2980. break;
  2981. }
  2982. }
  2983. else
  2984. {
  2985. IHqlExpression * seq = querySequence(expr);
  2986. assertex(seq && seq->queryValue());
  2987. IHqlExpression * name = queryResultName(expr);
  2988. OwnedHqlExpr value = createAttribute(resultAtom, LINK(seq), LINK(name));
  2989. addDependencySource(value, curGraph, activityExpr);
  2990. }
  2991. return true;
  2992. }
  2993. case no_keydiff:
  2994. {
  2995. addRefExprDependency(expr->queryChild(0), curGraph, activityExpr);
  2996. addRefExprDependency(expr->queryChild(1), curGraph, activityExpr);
  2997. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(2)));
  2998. addDependencySource(value, curGraph, activityExpr);
  2999. return true;
  3000. }
  3001. case no_keypatch:
  3002. {
  3003. addRefExprDependency(expr->queryChild(0), curGraph, activityExpr);
  3004. OwnedHqlExpr patchName = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(1)));
  3005. addDependencyUse(patchName, curGraph, activityExpr);
  3006. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(2)));
  3007. addDependencySource(value, curGraph, activityExpr);
  3008. return true;
  3009. }
  3010. case no_table:
  3011. {
  3012. IHqlExpression * filename = expr->queryChild(0);
  3013. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  3014. addDependencyUse(value, curGraph, activityExpr);
  3015. return !filename->isConstant();
  3016. }
  3017. case no_select:
  3018. return isNewSelector(expr);
  3019. case no_workunit_dataset:
  3020. {
  3021. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3022. IHqlExpression * name = queryPropertyChild(expr, nameAtom, 0);
  3023. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3024. addDependencyUse(value, curGraph, activityExpr);
  3025. return false;
  3026. }
  3027. case no_getresult:
  3028. {
  3029. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3030. IHqlExpression * name = queryPropertyChild(expr, namedAtom, 0);
  3031. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3032. addDependencyUse(value, curGraph, activityExpr);
  3033. return false;
  3034. }
  3035. case no_getgraphresult:
  3036. {
  3037. OwnedHqlExpr value = createAttribute(resultAtom, LINK(expr->queryChild(1)), LINK(expr->queryChild(2)));
  3038. addDependencyUse(value, curGraph, activityExpr);
  3039. return false;
  3040. }
  3041. case no_setgraphresult:
  3042. {
  3043. OwnedHqlExpr value = createAttribute(resultAtom, LINK(expr->queryChild(1)), LINK(expr->queryChild(2)));
  3044. addDependencySource(value, curGraph, activityExpr);
  3045. return true;
  3046. }
  3047. case no_ensureresult:
  3048. case no_setresult:
  3049. case no_extractresult:
  3050. {
  3051. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3052. IHqlExpression * name = queryPropertyChild(expr, namedAtom, 0);
  3053. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3054. addDependencySource(value, curGraph, activityExpr);
  3055. return true;
  3056. }
  3057. case no_attr:
  3058. case no_attr_link:
  3059. case no_record:
  3060. case no_field:
  3061. return false; //no need to look any further
  3062. default:
  3063. return true;
  3064. }
  3065. }
  3066. void EclResourcer::doAddChildDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3067. {
  3068. if (expr->queryTransformExtra())
  3069. return;
  3070. expr->setTransformExtraUnlinked(expr);
  3071. if (addExprDependency(expr, graph, activityExpr))
  3072. {
  3073. ForEachChild(idx, expr)
  3074. doAddChildDependencies(expr->queryChild(idx), graph, activityExpr);
  3075. }
  3076. }
  3077. void EclResourcer::addChildDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3078. {
  3079. if (graph)
  3080. {
  3081. lockTransformMutex();
  3082. doAddChildDependencies(expr, graph, activityExpr);
  3083. unlockTransformMutex();
  3084. }
  3085. }
  3086. void EclResourcer::addDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3087. {
  3088. ResourcerInfo * info = queryResourceInfo(expr);
  3089. if (info && info->containsActivity)
  3090. {
  3091. if (info->isActivity)
  3092. {
  3093. if (info->gatheredDependencies)
  3094. return;
  3095. info->gatheredDependencies = true;
  3096. graph = info->graph;
  3097. activityExpr = expr;
  3098. }
  3099. if (addExprDependency(expr, graph, activityExpr))
  3100. {
  3101. unsigned first = getFirstActivityArgument(expr);
  3102. unsigned last = first + getNumActivityArguments(expr);
  3103. ForEachChild(idx, expr)
  3104. {
  3105. if ((idx >= first) && (idx < last))
  3106. addDependencies(expr->queryChild(idx), graph, activityExpr);
  3107. else
  3108. addChildDependencies(expr->queryChild(idx), graph, activityExpr);
  3109. }
  3110. }
  3111. }
  3112. else
  3113. addChildDependencies(expr, graph, activityExpr);
  3114. ForEachItemIn(i, info->childDependents)
  3115. {
  3116. IHqlExpression & cur = info->childDependents.item(i);
  3117. if (isResourcedActivity(&cur))
  3118. {
  3119. addDependencies(&cur, NULL, NULL);
  3120. ResourcerInfo * sourceInfo = queryResourceInfo(&cur);
  3121. sourceInfo->noteUsedFromChild();
  3122. ResourceGraphLink * link = new ResourceGraphDependencyLink(sourceInfo->graph, &cur, graph, expr);
  3123. graph->dependsOn.append(*link);
  3124. links.append(*link);
  3125. }
  3126. }
  3127. }
  3128. void EclResourcer::addDependencies(HqlExprArray & exprs)
  3129. {
  3130. ForEachItemIn(idx, exprs)
  3131. addDependencies(&exprs.item(idx), NULL, NULL);
  3132. }
  3133. void EclResourcer::spotUnbalancedSplitters(IHqlExpression * expr, unsigned whichSource, IHqlExpression * path, ResourceGraphInfo * graph)
  3134. {
  3135. ResourcerInfo * info = queryResourceInfo(expr);
  3136. if (!info)
  3137. return;
  3138. if (graph && info->graph && info->graph != graph)
  3139. {
  3140. if ((info->currentSource == whichSource) && (info->pathToSplitter != path))
  3141. graph->unbalancedExternalSources.append(*LINK(expr->queryBody()));
  3142. info->currentSource = whichSource;
  3143. info->pathToSplitter.set(path);
  3144. return;
  3145. }
  3146. else
  3147. {
  3148. if (info->currentSource == whichSource)
  3149. {
  3150. if (info->pathToSplitter != path)
  3151. info->balanced = false;
  3152. return;
  3153. }
  3154. info->currentSource = whichSource;
  3155. info->pathToSplitter.set(path);
  3156. }
  3157. if (info->containsActivity)
  3158. {
  3159. unsigned first = getFirstActivityArgument(expr);
  3160. unsigned num = getNumActivityArguments(expr);
  3161. bool modify = false;
  3162. if (num > 1)
  3163. {
  3164. switch (expr->getOperator())
  3165. {
  3166. case no_addfiles:
  3167. if (expr->hasProperty(_ordered_Atom) || expr->hasProperty(_orderedPull_Atom) || isGrouped(expr))
  3168. modify = true;
  3169. break;
  3170. default:
  3171. modify = true;
  3172. break;
  3173. }
  3174. }
  3175. unsigned last = first + num;
  3176. for (unsigned idx = first; idx < last; idx++)
  3177. {
  3178. OwnedHqlExpr childPath = modify ? createAttribute(pathAtom, getSizetConstant(idx), LINK(path)) : LINK(path);
  3179. spotUnbalancedSplitters(expr->queryChild(idx), whichSource, childPath, graph);
  3180. }
  3181. }
  3182. //Now check dependencies between graphs (for roxie)
  3183. if (!graph)
  3184. {
  3185. if (info->graph)
  3186. {
  3187. GraphLinkArray & graphLinks = info->graph->dependsOn;
  3188. ForEachItemIn(i, graphLinks)
  3189. {
  3190. ResourceGraphLink & link = graphLinks.item(i);
  3191. if (link.sinkNode == expr)
  3192. {
  3193. OwnedHqlExpr childPath = createAttribute(dependencyAtom, LINK(link.sourceNode), LINK(path));
  3194. spotUnbalancedSplitters(link.sourceNode, whichSource, childPath, graph);
  3195. }
  3196. }
  3197. }
  3198. else
  3199. {
  3200. ForEachItemIn(i, links)
  3201. {
  3202. ResourceGraphLink & link = links.item(i);
  3203. if (link.sinkNode == expr)
  3204. {
  3205. OwnedHqlExpr childPath = createAttribute(dependencyAtom, LINK(link.sourceNode), LINK(path));
  3206. spotUnbalancedSplitters(link.sourceNode, whichSource, childPath, graph);
  3207. }
  3208. }
  3209. }
  3210. }
  3211. }
  3212. void EclResourcer::spotUnbalancedSplitters(HqlExprArray & exprs)
  3213. {
  3214. unsigned curSource = 1;
  3215. switch (targetClusterType)
  3216. {
  3217. case HThorCluster:
  3218. break;
  3219. case ThorCluster:
  3220. case ThorLCRCluster:
  3221. {
  3222. //Thor only handles one graph at a time, so only walk expressions within a single graph.
  3223. ForEachItemIn(i1, graphs)
  3224. {
  3225. ResourceGraphInfo & curGraph = graphs.item(i1);
  3226. ForEachItemIn(i2, curGraph.sinks)
  3227. {
  3228. ResourceGraphLink & cur = curGraph.sinks.item(i2);
  3229. spotUnbalancedSplitters(cur.sourceNode, curSource++, 0, &curGraph);
  3230. }
  3231. }
  3232. }
  3233. break;
  3234. case RoxieCluster:
  3235. {
  3236. //Roxie pulls all at once, so need to analyse globally.
  3237. ForEachItemIn(idx, exprs)
  3238. spotUnbalancedSplitters(&exprs.item(idx), curSource++, 0, NULL);
  3239. break;
  3240. }
  3241. }
  3242. }
  3243. void EclResourcer::spotSharedInputs(IHqlExpression * expr, ResourceGraphInfo * graph)
  3244. {
  3245. ResourcerInfo * info = queryResourceInfo(expr);
  3246. if (!info)
  3247. return;
  3248. if (info->graph && info->graph != graph)
  3249. {
  3250. IHqlExpression * body = expr->queryBody();
  3251. if (!graph->unbalancedExternalSources.contains(*body))
  3252. graph->balancedExternalSources.append(*LINK(body));
  3253. return;
  3254. }
  3255. if (info->isSplit())
  3256. {
  3257. //overload currentSource to track if we have visited this splitter before. It cannot have value value NotFound up to now
  3258. if (info->currentSource == NotFound)
  3259. return;
  3260. info->currentSource = NotFound;
  3261. }
  3262. if (info->containsActivity)
  3263. {
  3264. unsigned first = getFirstActivityArgument(expr);
  3265. unsigned num = getNumActivityArguments(expr);
  3266. unsigned last = first + num;
  3267. for (unsigned idx = first; idx < last; idx++)
  3268. {
  3269. spotSharedInputs(expr->queryChild(idx), graph);
  3270. }
  3271. }
  3272. }
  3273. void EclResourcer::spotSharedInputs()
  3274. {
  3275. //Thor only handles one graph at a time, so only walk expressions within a single graph.
  3276. ForEachItemIn(i1, graphs)
  3277. {
  3278. ResourceGraphInfo & curGraph = graphs.item(i1);
  3279. HqlExprCopyArray visited;
  3280. ForEachItemIn(i2, curGraph.sinks)
  3281. {
  3282. ResourceGraphLink & cur = curGraph.sinks.item(i2);
  3283. IHqlExpression * curExpr = cur.sourceNode->queryBody();
  3284. if (!visited.contains(*curExpr))
  3285. {
  3286. ResourcerInfo * info = queryResourceInfo(curExpr);
  3287. if (!info->isExternalSpill() && !info->expandRatherThanSpill(true))
  3288. {
  3289. spotSharedInputs(curExpr, &curGraph);
  3290. visited.append(*curExpr);
  3291. }
  3292. }
  3293. }
  3294. }
  3295. }
  3296. //------------------------------------------------------------------------------------------
  3297. // PASS6: Merge sub graphs that can share resources and don't have dependencies
  3298. // MORE: Once sources are merged, should try merging between trees.
  3299. static bool conditionsMatch(const HqlExprArray & left, const HqlExprArray & right)
  3300. {
  3301. if (left.ordinality() != right.ordinality())
  3302. return false;
  3303. ForEachItemIn(i, left)
  3304. {
  3305. if (!left.contains(right.item(i)) || !right.contains(left.item(i)))
  3306. return false;
  3307. }
  3308. return true;
  3309. }
  3310. bool EclResourcer::queryMergeGraphLink(ResourceGraphLink & link)
  3311. {
  3312. if (link.linkKind == UnconditionalLink)
  3313. {
  3314. //Don't combine any dependencies
  3315. const GraphLinkArray & sinks = link.sourceGraph->sinks;
  3316. ForEachItemIn(i1, sinks)
  3317. {
  3318. ResourceGraphLink & cur = sinks.item(i1);
  3319. if (cur.sinkGraph && cur.sourceNode->isAction())
  3320. return false;
  3321. }
  3322. //Roxie pulls all subgraphs at same time, so no problem with conditional links since handled at run time.
  3323. if (options.noConditionalLinks)
  3324. return true;
  3325. //No conditionals in the sink graph=>will be executed just as frequently
  3326. if (!link.sinkGraph->mergedConditionSource)
  3327. return true;
  3328. //Is this the only place this source graph is used? If so, always fine to merge
  3329. if (sinks.ordinality() == 1)
  3330. return true;
  3331. //1) if context the source graph is being merged into is unconditional, then it is ok [ could have conditional and unconditional paths to same graph]
  3332. //2) if context is conditional, then we don't really want to do it unless the conditions on all sinks are identical, and the only links occur between these two graphs.
  3333. // (situation occurs with spill fed into two branches of a join).
  3334. bool isConditionalInSinkGraph = false;
  3335. bool accessedFromManyGraphs = false;
  3336. ForEachItemIn(i, sinks)
  3337. {
  3338. ResourceGraphLink & cur = sinks.item(i);
  3339. if (cur.sinkNode)
  3340. {
  3341. if (cur.sinkGraph != link.sinkGraph)
  3342. accessedFromManyGraphs = true;
  3343. else
  3344. {
  3345. if (!isConditionalInSinkGraph)
  3346. {
  3347. ResourcerInfo * sinkInfo = queryResourceInfo(cur.sinkNode);
  3348. //If this is conditional, don't merge if there is a link to another graph
  3349. if ((!cur.isDependency() && sinkInfo->isConditionExpr()) ||
  3350. //if (sinkInfo->isConditionExpr() ||
  3351. (!sinkInfo->isUnconditional() && sinkInfo->conditions.ordinality()))
  3352. isConditionalInSinkGraph = true;
  3353. }
  3354. }
  3355. }
  3356. }
  3357. if (isConditionalInSinkGraph && accessedFromManyGraphs)
  3358. return false;
  3359. return true;
  3360. }
  3361. return false;
  3362. }
  3363. unsigned EclResourcer::getMaxDepth() const
  3364. {
  3365. unsigned maxDepth = 0;
  3366. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3367. {
  3368. unsigned depth = graphs.item(idx).getDepth();
  3369. if (depth > maxDepth)
  3370. maxDepth = depth;
  3371. }
  3372. return maxDepth;
  3373. }
  3374. void EclResourcer::mergeSubGraphs(unsigned pass)
  3375. {
  3376. unsigned maxDepth = getMaxDepth();
  3377. for (unsigned curDepth = maxDepth+1; curDepth-- != 0;)
  3378. {
  3379. mergeAgain:
  3380. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3381. {
  3382. ResourceGraphInfo & cur = graphs.item(idx);
  3383. if ((cur.getDepth() == curDepth) && !cur.isDead)
  3384. {
  3385. bool tryAgain;
  3386. do
  3387. {
  3388. tryAgain = false;
  3389. for (unsigned idxSource = 0; idxSource < cur.sources.ordinality(); /*incremented in loop*/)
  3390. {
  3391. ResourceGraphLink & curLink = cur.sources.item(idxSource);
  3392. ResourceGraphInfo * source = curLink.sourceGraph;
  3393. IHqlExpression * sourceNode = curLink.sourceNode;
  3394. bool tryToMerge;
  3395. bool expandSourceInPlace = queryResourceInfo(sourceNode)->expandRatherThanSpill(false);
  3396. if (pass == 0)
  3397. tryToMerge = !expandSourceInPlace;
  3398. else
  3399. tryToMerge = expandSourceInPlace;
  3400. if (tryToMerge)
  3401. {
  3402. bool ok = true;
  3403. ResourcerInfo * sourceResourceInfo = queryResourceInfo(sourceNode);
  3404. if (sourceResourceInfo->outputToUseForSpill && (targetClusterType == HThorCluster))
  3405. {
  3406. if (curLink.sinkNode != sourceResourceInfo->outputToUseForSpill)
  3407. ok = false;
  3408. }
  3409. unsigned curSourceDepth = source->getDepth();
  3410. //MORE: Merging identical conditionals?
  3411. if (ok && queryMergeGraphLink(curLink) &&
  3412. !sourceResourceInfo->expandRatherThanSplit() &&
  3413. cur.mergeInSource(*source, *resourceLimit, (curLink.linkKind == ConditionalLink)))
  3414. {
  3415. //NB: Following cannot remove sources below the current index.
  3416. replaceGraphReferences(source, &cur);
  3417. source->isDead = true;
  3418. #ifdef VERIFY_RESOURCING
  3419. checkRecursion(&cur);
  3420. #endif
  3421. unsigned newDepth = cur.getDepth();
  3422. //Unusual: The source we are merging with has just increased in depth, so any
  3423. //dependents have also increased in depth. Need to try again at different depth
  3424. //to see if one of those will merge in.
  3425. if (newDepth > curSourceDepth)
  3426. {
  3427. curDepth += (newDepth - curSourceDepth);
  3428. goto mergeAgain;
  3429. }
  3430. //depth of this element has changed, so don't check to see if it merges with any other
  3431. //sources on this iteration.
  3432. if (newDepth != curDepth)
  3433. {
  3434. tryAgain = false;
  3435. break;
  3436. }
  3437. tryAgain = true;
  3438. }
  3439. else
  3440. idxSource++;
  3441. }
  3442. else
  3443. idxSource++;
  3444. }
  3445. } while (tryAgain);
  3446. }
  3447. }
  3448. }
  3449. }
  3450. void EclResourcer::mergeSiblings()
  3451. {
  3452. unsigned maxDepth = getMaxDepth();
  3453. for (unsigned curDepth = maxDepth+1; curDepth-- != 0;)
  3454. {
  3455. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3456. {
  3457. ResourceGraphInfo & cur = graphs.item(idx);
  3458. if ((cur.getDepth() == curDepth) && !cur.isDead)
  3459. {
  3460. ForEachItemIn(idxSource, cur.sources)
  3461. {
  3462. ResourceGraphLink & curLink = cur.sources.item(idxSource);
  3463. ResourceGraphInfo * source = curLink.sourceGraph;
  3464. IHqlExpression * sourceNode = curLink.sourceNode;
  3465. ResourcerInfo * sourceInfo = queryResourceInfo(sourceNode);
  3466. if (sourceInfo->neverSplit || sourceInfo->expandRatherThanSplit())
  3467. continue;
  3468. for (unsigned iSink = 0; iSink < source->sinks.ordinality(); )
  3469. {
  3470. ResourceGraphLink & secondLink = source->sinks.item(iSink);
  3471. ResourceGraphInfo * sink = secondLink.sinkGraph;
  3472. if (sink && (sink != &cur) && !sink->isDead && sourceNode->queryBody() == secondLink.sourceNode->queryBody())
  3473. {
  3474. if (cur.mergeInSibling(*sink, *resourceLimit))
  3475. {
  3476. //NB: Following cannot remove sources below the current index.
  3477. replaceGraphReferences(sink, &cur);
  3478. sink->isDead = true;
  3479. }
  3480. else
  3481. iSink++;
  3482. }
  3483. else
  3484. iSink++;
  3485. }
  3486. }
  3487. }
  3488. }
  3489. }
  3490. }
  3491. void EclResourcer::mergeSubGraphs()
  3492. {
  3493. for (unsigned pass=0; pass < 2; pass++)
  3494. mergeSubGraphs(pass);
  3495. if (options.combineSiblings)
  3496. mergeSiblings();
  3497. ForEachItemInRev(idx2, graphs)
  3498. {
  3499. if (graphs.item(idx2).isDead)
  3500. graphs.remove(idx2);
  3501. }
  3502. }
  3503. //------------------------------------------------------------------------------------------
  3504. // PASS7: Optimize aggregates off of splitters into through aggregates.
  3505. bool EclResourcer::optimizeAggregate(IHqlExpression * expr)
  3506. {
  3507. if (!isSimpleAggregateResult(expr))
  3508. return false;
  3509. //expr is a no_extractresult
  3510. if (queryResourceInfo(expr)->childDependents.ordinality())
  3511. return false;
  3512. IHqlExpression * row2ds = expr->queryChild(0); // no_datasetfromrow
  3513. IHqlExpression * selectNth = row2ds->queryChild(0);
  3514. ResourcerInfo * row2dsInfo = queryResourceInfo(row2ds);
  3515. //If more than one set result for the same aggregate don't merge the aggregation because
  3516. //it messes up the internal count. Should really fix it and do multiple stores in the
  3517. //through aggregate.
  3518. if (row2dsInfo->numInternalUses() > 1)
  3519. return false;
  3520. //Be careful not to lose any spills...
  3521. if (row2dsInfo->numExternalUses)
  3522. return false;
  3523. ResourcerInfo * selectNthInfo = queryResourceInfo(selectNth);
  3524. if (selectNthInfo->numExternalUses)
  3525. return false;
  3526. IHqlExpression * aggregate = selectNth->queryChild(0); // no_newaggregate
  3527. IHqlExpression * parent = aggregate->queryChild(0);
  3528. ResourcerInfo * info = queryResourceInfo(parent);
  3529. if (info->numInternalUses() <= 1)
  3530. return false;
  3531. //ok, we can go ahead and merge.
  3532. info->aggregates.append(*LINK(expr));
  3533. // info->numExternalUses--;
  3534. // info->numUses--;
  3535. return true;
  3536. }
  3537. void EclResourcer::optimizeAggregates()
  3538. {
  3539. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3540. {
  3541. ResourceGraphInfo & cur = graphs.item(idx);
  3542. for (unsigned idxSink = 0; idxSink < cur.sinks.ordinality(); /*incremented in loop*/)
  3543. {
  3544. ResourceGraphLink & link = cur.sinks.item(idxSink);
  3545. if ((link.sinkGraph == NULL) && optimizeAggregate(link.sourceNode))
  3546. cur.sinks.remove(idxSink);
  3547. else
  3548. idxSink++;
  3549. }
  3550. }
  3551. }
  3552. //------------------------------------------------------------------------------------------
  3553. // PASS8: Improve efficiency by merging the split points slightly
  3554. IHqlExpression * EclResourcer::findPredecessor(IHqlExpression * expr, IHqlExpression * search, IHqlExpression * prev)
  3555. {
  3556. if (expr == search)
  3557. return prev;
  3558. ResourcerInfo * info = queryResourceInfo(expr);
  3559. if (info && info->containsActivity)
  3560. {
  3561. unsigned first = getFirstActivityArgument(expr);
  3562. unsigned last = first + getNumActivityArguments(expr);
  3563. for (unsigned idx=first; idx < last; idx++)
  3564. {
  3565. IHqlExpression * match = findPredecessor(expr->queryChild(idx), search, expr);
  3566. if (match)
  3567. return match;
  3568. }
  3569. }
  3570. return NULL;
  3571. }
  3572. IHqlExpression * EclResourcer::findPredecessor(ResourcerInfo * search)
  3573. {
  3574. ForEachItemIn(idx, links)
  3575. {
  3576. ResourceGraphLink & cur = links.item(idx);
  3577. if (cur.sourceGraph == search->graph)
  3578. {
  3579. IHqlExpression * match = findPredecessor(cur.sourceNode, search->original, NULL);
  3580. if (match)
  3581. return match;
  3582. }
  3583. }
  3584. return NULL;
  3585. }
  3586. void EclResourcer::moveExternalSpillPoints()
  3587. {
  3588. if (options.minimizeSpillSize == 0)
  3589. return;
  3590. //if we have a external spill point where all the external outputs reduce their data significantly
  3591. //either via a project or a filter, then it might be worth including those activities in the main
  3592. //graph and ,if all external children reduce data, then may be best to filter
  3593. ForEachItemIn(idx, links)
  3594. {
  3595. ResourceGraphLink & cur = links.item(idx);
  3596. if ((cur.linkKind == UnconditionalLink) && cur.sinkGraph)
  3597. {
  3598. while (lightweightAndReducesDatasetSize(cur.sinkNode))
  3599. {
  3600. ResourcerInfo * sourceInfo = queryResourceInfo(cur.sourceNode);
  3601. if (!sourceInfo->isExternalSpill() || (sourceInfo->numExternalUses > options.minimizeSpillSize))
  3602. break;
  3603. ResourcerInfo * sinkInfo = queryResourceInfo(cur.sinkNode);
  3604. if (sinkInfo->numInternalUses() != 1)
  3605. break;
  3606. IHqlExpression * sinkPred = findPredecessor(sinkInfo);
  3607. sinkInfo->graph.set(cur.sourceGraph);
  3608. sourceInfo->numExternalUses--;
  3609. sinkInfo->numExternalUses++;
  3610. cur.sourceNode.set(cur.sinkNode);
  3611. cur.sinkNode.set(sinkPred);
  3612. }
  3613. }
  3614. }
  3615. }
  3616. //------------------------------------------------------------------------------------------
  3617. // PASS9: Create a new expression tree representing the information
  3618. static HqlTransformerInfo childDependentReplacerInfo("ChildDependentReplacer");
  3619. class ChildDependentReplacer : public MergingHqlTransformer
  3620. {
  3621. public:
  3622. ChildDependentReplacer(const HqlExprCopyArray & _childDependents, const HqlExprArray & _replacements)
  3623. : MergingHqlTransformer(childDependentReplacerInfo), childDependents(_childDependents), replacements(_replacements)
  3624. {
  3625. }
  3626. protected:
  3627. virtual IHqlExpression * createTransformed(IHqlExpression * expr)
  3628. {
  3629. unsigned match = childDependents.find(*expr);
  3630. if (match != NotFound)
  3631. return LINK(&replacements.item(match));
  3632. return MergingHqlTransformer::createTransformed(expr);
  3633. }
  3634. protected:
  3635. const HqlExprCopyArray & childDependents;
  3636. const HqlExprArray & replacements;
  3637. };
  3638. static IHqlExpression * getScalarReplacement(IHqlExpression * original, IHqlExpression * replacement)
  3639. {
  3640. IHqlExpression * value = original;
  3641. //First skip any wrappers which are there to cause things to be hoisted.
  3642. loop
  3643. {
  3644. node_operator op = value->getOperator();
  3645. if ((op != no_globalscope) && (op != no_thisnode) && (op != no_evalonce))
  3646. break;
  3647. value = value->queryChild(0);
  3648. }
  3649. //Now modify the spilled result depending on how the spilled result was created (see EclHoistLocator::noteScalar() above)
  3650. if (value->getOperator() == no_select)
  3651. {
  3652. IHqlExpression * field = value->queryChild(1);
  3653. bool isNew;
  3654. IHqlExpression * ds = querySelectorDataset(value, isNew);
  3655. if(isNew || ds->isDatarow())
  3656. {
  3657. if (projectSelectorDatasetToField(ds))
  3658. return createNewSelectExpr(LINK(replacement), LINK(field));
  3659. return replaceSelectorDataset(value, replacement);
  3660. }
  3661. }
  3662. else if (value->getOperator() == no_createset)
  3663. {
  3664. IHqlExpression * record = replacement->queryRecord();
  3665. IHqlExpression * field = record->queryChild(0);
  3666. return createValue(no_createset, original->getType(), LINK(replacement), createSelectExpr(LINK(replacement->queryNormalizedSelector()), LINK(field)));
  3667. }
  3668. IHqlExpression * record = replacement->queryRecord();
  3669. return createNewSelectExpr(LINK(replacement), LINK(record->queryChild(0)));
  3670. }
  3671. IHqlExpression * EclResourcer::replaceResourcedReferences(ResourcerInfo * info, IHqlExpression * expr)
  3672. {
  3673. if (!isAffectedByResourcing(expr))
  3674. return LINK(expr);
  3675. LinkedHqlExpr mapped = expr;
  3676. if (info && (info->childDependents.ordinality()))
  3677. {
  3678. HqlExprArray replacements;
  3679. ForEachItemIn(i, info->originalChildDependents)
  3680. {
  3681. IHqlExpression & cur = info->childDependents.item(i);
  3682. LinkedHqlExpr replacement = &cur;
  3683. if (isResourcedActivity(&cur))
  3684. replacement.setown(createResourced(&cur, NULL, false, false));
  3685. IHqlExpression * original = &info->originalChildDependents.item(i);
  3686. if (!original->isDataset() && !original->isDatarow())
  3687. replacement.setown(getScalarReplacement(original, replacement));
  3688. replacements.append(*replacement.getClear());
  3689. }
  3690. ChildDependentReplacer replacer(info->originalChildDependents, replacements);
  3691. mapped.setown(replacer.transformRoot(mapped));
  3692. }
  3693. return mapped.getClear();
  3694. }
  3695. IHqlExpression * EclResourcer::doCreateResourced(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, bool expandInParent, bool defineSideEffect)
  3696. {
  3697. ResourcerInfo * info = queryResourceInfo(expr);
  3698. node_operator op = expr->getOperator();
  3699. HqlExprArray args;
  3700. bool same = true;
  3701. unsigned first = getFirstActivityArgument(expr);
  3702. unsigned last = first + getNumActivityArguments(expr);
  3703. OwnedHqlExpr transformed;
  3704. switch (op)
  3705. {
  3706. case no_if:
  3707. {
  3708. ForEachChild(idx, expr)
  3709. {
  3710. IHqlExpression * child = expr->queryChild(idx);
  3711. IHqlExpression * resourced;
  3712. if ((idx < first) || (idx >= last))
  3713. resourced = replaceResourcedReferences(info, child);
  3714. else
  3715. resourced = createResourced(child, ownerGraph, expandInParent, false);
  3716. if (child != resourced)
  3717. same = false;
  3718. args.append(*resourced);
  3719. }
  3720. break;
  3721. }
  3722. case no_case:
  3723. case no_map:
  3724. UNIMPLEMENTED;
  3725. case no_keyed:
  3726. return LINK(expr);
  3727. case no_compound:
  3728. transformed.setown(createResourced(expr->queryChild(1), ownerGraph, expandInParent, false));
  3729. break;
  3730. case no_executewhen:
  3731. {
  3732. args.append(*createResourced(expr->queryChild(0), ownerGraph, expandInParent, false));
  3733. args.append(*createResourced(expr->queryChild(1), ownerGraph, expandInParent, false));
  3734. assertex(args.item(1).getOperator() == no_callsideeffect);
  3735. unwindChildren(args, expr, 2);
  3736. same = false;
  3737. break;
  3738. }
  3739. case no_select:
  3740. {
  3741. IHqlExpression * ds = expr->queryChild(0);
  3742. OwnedHqlExpr newDs = createResourced(ds, ownerGraph, expandInParent, false);
  3743. if (ds != newDs)
  3744. {
  3745. args.append(*LINK(newDs));
  3746. unwindChildren(args, expr, 1);
  3747. if (!expr->hasProperty(newAtom) && isNewSelector(expr) && (newDs->getOperator() != no_select))
  3748. args.append(*LINK(queryNewSelectAttrExpr()));
  3749. same = false;
  3750. }
  3751. break;
  3752. }
  3753. case no_join:
  3754. case no_denormalize:
  3755. case no_denormalizegroup:
  3756. if (false)//if (isKeyedJoin(expr))
  3757. {
  3758. args.append(*createResourced(expr->queryChild(0), ownerGraph, expandInParent, false));
  3759. args.append(*LINK(expr->queryChild(1)));
  3760. unsigned max = expr->numChildren();
  3761. for (unsigned idx=2; idx < max; idx++)
  3762. args.append(*replaceResourcedReferences(info, expr->queryChild(idx)));
  3763. same = false;
  3764. break;
  3765. }
  3766. //fall through...
  3767. default:
  3768. {
  3769. IHqlExpression * activeTable = NULL;
  3770. // Check to see if the activity has a dataset which is in scope for the rest of its arguments.
  3771. // If so we'll need to remap references from the children.
  3772. if (hasActiveTopDataset(expr) && (first != last))
  3773. activeTable = expr->queryChild(0);
  3774. ForEachChild(idx, expr)
  3775. {
  3776. IHqlExpression * child = expr->queryChild(idx);
  3777. IHqlExpression * resourced;
  3778. if ((idx < first) || (idx >= last))
  3779. {
  3780. LinkedHqlExpr mapped = child;
  3781. if (activeTable && isAffectedByResourcing(child))
  3782. {
  3783. IHqlExpression * activeTableTransformed = &args.item(0);
  3784. if (activeTable != activeTableTransformed)
  3785. mapped.setown(scopedReplaceSelector(child, activeTable, activeTableTransformed));
  3786. }
  3787. resourced = replaceResourcedReferences(info, mapped);
  3788. }
  3789. else
  3790. resourced = createResourced(child, ownerGraph, expandInParent, false);
  3791. if (child != resourced)
  3792. same = false;
  3793. args.append(*resourced);
  3794. }
  3795. }
  3796. break;
  3797. }
  3798. if (!transformed)
  3799. transformed.setown(same ? LINK(expr) : expr->clone(args));
  3800. if (!expandInParent)
  3801. {
  3802. if (!transformed->isAction())
  3803. transformed.setown(info->createTransformedExpr(transformed));
  3804. else if (defineSideEffect)
  3805. transformed.setown(createValue(no_definesideeffect, LINK(transformed), createUniqueId()));
  3806. }
  3807. return transformed.getClear();
  3808. }
  3809. /*
  3810. Need to be careful because result should not reuse the same expression tree unless that element is a splitter.
  3811. createResourced()
  3812. {
  3813. if (!isActivity)
  3814. if (!containsActivity)
  3815. replace any refs to the activeTable with whatever it has been mapped to
  3816. else
  3817. recurse
  3818. else if (!isDefinedInSameGraph)
  3819. expand/create reader
  3820. set active table
  3821. else isSplitter and alreadyGeneratedForThisGraph
  3822. return previous result
  3823. else
  3824. create transformed
  3825. }
  3826. */
  3827. void EclResourcer::doCheckRecursion(ResourceGraphInfo * graph, PointerArray & visited)
  3828. {
  3829. visited.append(graph);
  3830. ForEachItemIn(idxD, graph->dependsOn)
  3831. checkRecursion(graph->dependsOn.item(idxD).sourceGraph, visited);
  3832. ForEachItemIn(idxS, graph->sources)
  3833. checkRecursion(graph->sources.item(idxS).sourceGraph, visited);
  3834. visited.pop();
  3835. }
  3836. void EclResourcer::checkRecursion(ResourceGraphInfo * graph, PointerArray & visited)
  3837. {
  3838. if (visited.find(graph) != NotFound)
  3839. throwUnexpected();
  3840. doCheckRecursion(graph, visited);
  3841. }
  3842. void EclResourcer::checkRecursion(ResourceGraphInfo * graph)
  3843. {
  3844. PointerArray visited;
  3845. doCheckRecursion(graph, visited);
  3846. }
  3847. IHqlExpression * EclResourcer::createResourced(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, bool expandInParent, bool defineSideEffect)
  3848. {
  3849. ResourcerInfo * info = queryResourceInfo(expr);
  3850. if (!info || !info->containsActivity)
  3851. return replaceResourcedReferences(info, expr);
  3852. if (!info->isActivity)
  3853. {
  3854. assertex(!defineSideEffect);
  3855. HqlExprArray args;
  3856. bool same = true;
  3857. ForEachChild(idx, expr)
  3858. {
  3859. IHqlExpression * cur = expr->queryChild(idx);
  3860. IHqlExpression * curResourced = createResourced(cur, ownerGraph, expandInParent, false);
  3861. args.append(*curResourced);
  3862. if (cur != curResourced)
  3863. same = false;
  3864. }
  3865. if (same)
  3866. return LINK(expr);
  3867. return expr->clone(args);
  3868. }
  3869. if (info->graph != ownerGraph)
  3870. {
  3871. assertex(!defineSideEffect);
  3872. bool isShared = options.optimizeSharedInputs && ownerGraph && ownerGraph->isSharedInput(expr);
  3873. if (isShared)
  3874. {
  3875. IHqlExpression * mapped = ownerGraph->queryMappedSharedInput(expr->queryBody());
  3876. if (mapped)
  3877. return LINK(mapped);
  3878. }
  3879. IHqlExpression * source;
  3880. if (info->expandRatherThanSpill(true))
  3881. {
  3882. bool expandChildInParent = options.minimiseSpills ? expandInParent : true;
  3883. OwnedHqlExpr resourced = doCreateResourced(expr, ownerGraph, expandChildInParent, false);
  3884. if (queryAddUniqueToActivity(resourced))
  3885. source = appendUniqueAttr(resourced);
  3886. else
  3887. source = LINK(resourced);
  3888. }
  3889. else
  3890. {
  3891. if (!expr->isAction())
  3892. {
  3893. OwnedHqlExpr reason;
  3894. if (ownerGraph && options.checkResources())
  3895. {
  3896. StringBuffer reasonText;
  3897. ownerGraph->getMergeFailReason(reasonText, info->graph, *resourceLimit);
  3898. if (reasonText.length())
  3899. {
  3900. reasonText.insert(0, "Resource limit spill: ");
  3901. reason.setown(createAttribute(_spillReason_Atom, createConstant(reasonText.str())));
  3902. }
  3903. }
  3904. source = info->createSpilledRead(reason);
  3905. }
  3906. else
  3907. {
  3908. IHqlExpression * uid = info->transformed->queryProperty(_uid_Atom);
  3909. source = createValue(no_callsideeffect, makeVoidType(), LINK(uid));
  3910. //source = LINK(info->transformed);
  3911. }
  3912. }
  3913. if (isShared)
  3914. {
  3915. source = createDatasetF(no_split, source, createAttribute(balancedAtom), createUniqueId(), NULL);
  3916. ownerGraph->addSharedInput(expr->queryBody(), source);
  3917. }
  3918. return source;
  3919. }
  3920. if (!expandInParent && info->transformed && info->isSplit())
  3921. {
  3922. return LINK(info->transformed);
  3923. }
  3924. OwnedHqlExpr resourced = doCreateResourced(expr, ownerGraph, expandInParent, defineSideEffect);
  3925. if (queryAddUniqueToActivity(resourced))// && !resourced->hasProperty(_internal_Atom))
  3926. resourced.setown(appendUniqueAttr(resourced));
  3927. if (!expandInParent)
  3928. {
  3929. info->transformed = resourced;
  3930. }
  3931. return resourced.getClear();
  3932. }
  3933. void EclResourcer::createResourced(ResourceGraphInfo * graph, HqlExprArray & transformed)
  3934. {
  3935. if (graph->createdGraph || graph->isDead)
  3936. return;
  3937. if (!graph->containsActiveSinks() && (!graph->hasConditionSource))
  3938. return;
  3939. #ifdef VERIFY_RESOURCING
  3940. checkRecursion(graph);
  3941. #endif
  3942. // DBGLOG("Prepare to CreateResourced(%p)", graph);
  3943. if (graph->startedGeneratingResourced)
  3944. throwError(HQLWRN_RecursiveDependendencies);
  3945. graph->startedGeneratingResourced = true;
  3946. ForEachItemIn(idxD, graph->dependsOn)
  3947. createResourced(graph->dependsOn.item(idxD).sourceGraph, transformed);
  3948. ForEachItemIn(idxS, graph->sources)
  3949. createResourced(graph->sources.item(idxS).sourceGraph, transformed);
  3950. // DBGLOG("Create resourced %p", graph);
  3951. //First generate the graphs for all the unconditional sinks
  3952. HqlExprArray args;
  3953. ForEachItemIn(idx, graph->sinks)
  3954. {
  3955. ResourceGraphLink & sink = graph->sinks.item(idx);
  3956. IHqlExpression * sinkNode = sink.sourceNode;
  3957. ResourcerInfo * info = queryResourceInfo(sinkNode);
  3958. //If graph is unconditional, any condition sinks are forced to be generated (and spilt)
  3959. if (!info->transformed)
  3960. {
  3961. // if it is a spiller, then it will be generated from another sink
  3962. if (!info->isExternalSpill())
  3963. {
  3964. IHqlExpression * resourced = createResourced(sinkNode, graph, false, sinkNode->isAction() && sink.sinkGraph);
  3965. assertex(info->transformed);
  3966. args.append(*resourced);
  3967. }
  3968. }
  3969. }
  3970. ForEachItemIn(i2, graph->sinks)
  3971. {
  3972. ResourceGraphLink & sink = graph->sinks.item(i2);
  3973. IHqlExpression * sinkNode = sink.sourceNode;
  3974. ResourcerInfo * info = queryResourceInfo(sinkNode);
  3975. IHqlExpression * splitter = info->splitterOutput;
  3976. if (splitter && !args.contains(*splitter))
  3977. args.append(*LINK(splitter));
  3978. }
  3979. if (args.ordinality() == 0)
  3980. graph->isDead = true;
  3981. else
  3982. {
  3983. if (options.useGraphResults)
  3984. args.append(*createAttribute(childAtom));
  3985. graph->createdGraph.setown(createValue(no_subgraph, makeVoidType(), args));
  3986. transformed.append(*LINK(graph->createdGraph));
  3987. }
  3988. }
  3989. void EclResourcer::inheritRedundantDependencies(ResourceGraphInfo * thisGraph)
  3990. {
  3991. if (thisGraph->inheritedExpandedDependencies)
  3992. return;
  3993. thisGraph->inheritedExpandedDependencies = true;
  3994. ForEachItemIn(idx, thisGraph->sources)
  3995. {
  3996. ResourceGraphLink & cur = thisGraph->sources.item(idx);
  3997. if (cur.isRedundantLink())
  3998. {
  3999. inheritRedundantDependencies(cur.sourceGraph);
  4000. ForEachItemIn(i, cur.sourceGraph->dependsOn)
  4001. {
  4002. ResourceGraphLink & curDepend = cur.sourceGraph->dependsOn.item(i);
  4003. ResourceGraphLink * link = new ResourceGraphDependencyLink(curDepend.sourceGraph, curDepend.sourceNode, thisGraph, cur.sinkNode);
  4004. thisGraph->dependsOn.append(*link);
  4005. links.append(*link);
  4006. }
  4007. }
  4008. }
  4009. }
  4010. void EclResourcer::createResourced(HqlExprArray & transformed)
  4011. {
  4012. //Before removing null links (e.g., where the source graph is expanded inline), need to make sure
  4013. //dependencies are cloned, otherwise graphs can be generated in the wrong order
  4014. ForEachItemIn(idx1, graphs)
  4015. inheritRedundantDependencies(&graphs.item(idx1));
  4016. ForEachItemInRev(idx2, links)
  4017. {
  4018. ResourceGraphLink & cur = links.item(idx2);
  4019. if (cur.isRedundantLink())
  4020. removeLink(cur, true);
  4021. }
  4022. ForEachItemIn(idx3, graphs)
  4023. createResourced(&graphs.item(idx3), transformed);
  4024. }
  4025. static int compareGraphDepth(CInterface * * _l, CInterface * * _r)
  4026. {
  4027. ResourceGraphInfo * l = (ResourceGraphInfo *)*_l;
  4028. ResourceGraphInfo * r = (ResourceGraphInfo *)*_r;
  4029. return l->getDepth() - r->getDepth();
  4030. }
  4031. static int compareLinkDepth(CInterface * * _l, CInterface * * _r)
  4032. {
  4033. ResourceGraphLink * l = (ResourceGraphLink *)*_l;
  4034. ResourceGraphLink * r = (ResourceGraphLink *)*_r;
  4035. int diff = l->sourceGraph->getDepth() - r->sourceGraph->getDepth();
  4036. if (diff) return diff;
  4037. if (l->sinkGraph)
  4038. if (r->sinkGraph)
  4039. return l->sinkGraph->getDepth() - r->sinkGraph->getDepth();
  4040. else
  4041. return -1;
  4042. else
  4043. if (r->sinkGraph)
  4044. return +1;
  4045. else
  4046. return 0;
  4047. }
  4048. void EclResourcer::display(StringBuffer & out)
  4049. {
  4050. CIArrayOf<ResourceGraphInfo> sortedGraphs;
  4051. ForEachItemIn(j1, graphs)
  4052. sortedGraphs.append(OLINK(graphs.item(j1)));
  4053. sortedGraphs.sort(compareGraphDepth);
  4054. out.append("Graphs:\n");
  4055. ForEachItemIn(i, sortedGraphs)
  4056. {
  4057. ResourceGraphInfo & cur = sortedGraphs.item(i);
  4058. out.appendf("%d: depth(%d) uncond(%d) cond(%d) %s {%p}\n", i, cur.getDepth(), cur.isUnconditional, cur.hasConditionSource, cur.isDead ? "dead" : "", &cur);
  4059. ForEachItemIn(j, cur.sources)
  4060. {
  4061. ResourceGraphLink & link = cur.sources.item(j);
  4062. out.appendf(" Source: %p %s\n", link.sinkNode.get(), getOpString(link.sinkNode->getOperator()));
  4063. }
  4064. ForEachItemIn(k, cur.sinks)
  4065. {
  4066. ResourceGraphLink & link = cur.sinks.item(k);
  4067. IHqlExpression * sourceNode = link.sourceNode;
  4068. ResourcerInfo * sourceInfo = queryResourceInfo(sourceNode);
  4069. out.appendf(" Sink: %p %s cond(%d,%d) int(%d) ext(%d)\n", sourceNode, getOpString(sourceNode->getOperator()), sourceInfo->conditions.ordinality(), sourceInfo->conditionSourceCount, sourceInfo->numInternalUses(), sourceInfo->numExternalUses);
  4070. }
  4071. ForEachItemIn(i3, dependencySource.graphs)
  4072. {
  4073. if (&dependencySource.graphs.item(i3) == &cur)
  4074. {
  4075. StringBuffer s;
  4076. toECL(&dependencySource.search.item(i3), s);
  4077. out.appendf(" Creates: %s\n", s.str());
  4078. }
  4079. }
  4080. }
  4081. out.append("Links:\n");
  4082. CIArrayOf<ResourceGraphLink> sortedLinks;
  4083. ForEachItemIn(j2, links)
  4084. sortedLinks.append(OLINK(links.item(j2)));
  4085. sortedLinks.sort(compareLinkDepth);
  4086. ForEachItemIn(i2, sortedLinks)
  4087. {
  4088. ResourceGraphLink & link = sortedLinks.item(i2);
  4089. unsigned len = out.length();
  4090. out.appendf(" Source: %d %s", sortedGraphs.find(*link.sourceGraph), getOpString(link.sourceNode->getOperator()));
  4091. if (link.sinkNode)
  4092. {
  4093. out.padTo(len+30);
  4094. out.appendf(" Sink: %d %s", sortedGraphs.find(*link.sinkGraph), getOpString(link.sinkNode->getOperator()));
  4095. }
  4096. if (link.linkKind == ConditionalLink)
  4097. out.append(" <conditional>");
  4098. else if (link.linkKind == SequenceLink)
  4099. out.append(" <sequence>");
  4100. out.newline();
  4101. }
  4102. }
  4103. void EclResourcer::trace()
  4104. {
  4105. StringBuffer s;
  4106. display(s);
  4107. DBGLOG("%s", s.str());
  4108. }
  4109. //---------------------------------------------------------------------------
  4110. void EclResourcer::resourceGraph(HqlExprArray & exprs, HqlExprArray & transformed)
  4111. {
  4112. //NB: This only resources a single level of queries. SubQueries should be resourced in a separate
  4113. //pass so that commonality between different activities/subgraphs isn't introduced/messed up.
  4114. findSplitPoints(exprs);
  4115. createInitialGraphs(exprs);
  4116. markConditions(exprs);
  4117. if (options.checkResources())
  4118. resourceSubGraphs(exprs);
  4119. addDependencies(exprs);
  4120. #ifdef TRACE_RESOURCING
  4121. trace();
  4122. #endif
  4123. mergeSubGraphs();
  4124. #ifdef TRACE_RESOURCING
  4125. trace();
  4126. #endif
  4127. spotUnbalancedSplitters(exprs);
  4128. if (options.optimizeSharedInputs)
  4129. spotSharedInputs();
  4130. if (spotThroughAggregate)
  4131. optimizeAggregates();
  4132. moveExternalSpillPoints();
  4133. createResourced(transformed);
  4134. }
  4135. void EclResourcer::resourceRemoteGraph(HqlExprArray & exprs, HqlExprArray & transformed)
  4136. {
  4137. //NB: This only resources a single level of queries. SubQueries should be resourced in a separate
  4138. //pass so that commonality between different activities/subgraphs isn't introduced/messed up.
  4139. findSplitPoints(exprs);
  4140. createInitialRemoteGraphs(exprs);
  4141. markConditions(exprs);
  4142. addDependencies(exprs);
  4143. #ifdef TRACE_RESOURCING
  4144. trace();
  4145. #endif
  4146. mergeSubGraphs();
  4147. #ifdef TRACE_RESOURCING
  4148. trace();
  4149. #endif
  4150. createResourced(transformed);
  4151. }
  4152. //---------------------------------------------------------------------------
  4153. void expandLists(HqlExprArray & args, IHqlExpression * expr)
  4154. {
  4155. switch (expr->getOperator())
  4156. {
  4157. case no_comma:
  4158. case no_compound:
  4159. case no_parallel:
  4160. case no_actionlist:
  4161. // for the moment, expand root parallel nodes, it generates much better code.
  4162. // I should really come up with a better way of implementing sequential/parallel.
  4163. {
  4164. ForEachChild(idx, expr)
  4165. expandLists(args, expr->queryChild(idx));
  4166. break;
  4167. }
  4168. default:
  4169. args.append(*LINK(expr));
  4170. break;
  4171. }
  4172. }
  4173. IHqlExpression * resourceThorGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr)
  4174. {
  4175. HqlExprArray transformed;
  4176. {
  4177. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4178. if (graphIdExpr)
  4179. resourcer.setNewChildQuery(graphIdExpr, 0);
  4180. HqlExprArray exprs;
  4181. expandLists(exprs, expr);
  4182. resourcer.resourceGraph(exprs, transformed);
  4183. }
  4184. hoistNestedCompound(translator, transformed);
  4185. return createActionList(transformed);
  4186. }
  4187. static IHqlExpression * doResourceGraph(HqlCppTranslator & translator, HqlExprCopyArray * activeRows, IHqlExpression * expr,
  4188. ClusterType targetClusterType, unsigned clusterSize,
  4189. IHqlExpression * graphIdExpr, unsigned * numResults, bool isChild, bool useGraphResults)
  4190. {
  4191. HqlExprArray transformed;
  4192. {
  4193. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4194. if (isChild)
  4195. resourcer.setChildQuery(true);
  4196. resourcer.setNewChildQuery(graphIdExpr, *numResults);
  4197. resourcer.setUseGraphResults(useGraphResults);
  4198. if (activeRows)
  4199. resourcer.tagActiveCursors(*activeRows);
  4200. HqlExprArray exprs;
  4201. expandLists(exprs, expr);
  4202. resourcer.resourceGraph(exprs, transformed);
  4203. *numResults = resourcer.numGraphResults();
  4204. }
  4205. hoistNestedCompound(translator, transformed);
  4206. return createActionList(transformed);
  4207. }
  4208. IHqlExpression * resourceLibraryGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr, unsigned * numResults)
  4209. {
  4210. return doResourceGraph(translator, NULL, expr, targetClusterType, clusterSize, graphIdExpr, numResults, false, true); //?? what value for isChild (e.g., thor library call). Need to gen twice?
  4211. }
  4212. IHqlExpression * resourceNewChildGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults)
  4213. {
  4214. return doResourceGraph(translator, &activeRows, expr, targetClusterType, 0, graphIdExpr, numResults, true, true);
  4215. }
  4216. IHqlExpression * resourceLoopGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults, bool insideChildQuery)
  4217. {
  4218. return doResourceGraph(translator, &activeRows, expr, targetClusterType, 0, graphIdExpr, numResults, insideChildQuery, true);
  4219. }
  4220. IHqlExpression * resourceRemoteGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize)
  4221. {
  4222. HqlExprArray transformed;
  4223. {
  4224. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4225. HqlExprArray exprs;
  4226. expandLists(exprs, expr);
  4227. resourcer.resourceRemoteGraph(exprs, transformed);
  4228. }
  4229. hoistNestedCompound(translator, transformed);
  4230. return createActionList(transformed);
  4231. }
  4232. /*
  4233. Conditions:
  4234. They are nasty. We process the tree in two passes. First we tag anything which must be evaluated, and
  4235. save a list of condition statements to process later.
  4236. Second pass we tag conditionals.
  4237. a) all left and right branches of a condition are tagged. [conditionSourceCount]
  4238. b) all conditional expressions are tagged with the conditions they are evaluated for.
  4239. [if the condition lists match then it should be possible to merge the graphs]
  4240. c) The spill count for an node should ignore the number of links from conditional graphs,
  4241. but should add the number of conditions.
  4242. d) if (a, b(f1) +b(f2), c) needs to link b twice though!
  4243. */
  4244. /*
  4245. This transformer converts spill activities to no_dataset/no_output, and also converts splitters of splitters into
  4246. a single splitter.
  4247. */
  4248. class SpillActivityTransformer : public NewHqlTransformer
  4249. {
  4250. public:
  4251. SpillActivityTransformer();
  4252. protected:
  4253. virtual void analyseExpr(IHqlExpression * expr);
  4254. virtual IHqlExpression * createTransformed(IHqlExpression * expr);
  4255. bool isUnbalanced(IHqlExpression * body)
  4256. {
  4257. ANewTransformInfo * info = queryTransformExtra(body);
  4258. return info->spareByte1 != 0;
  4259. }
  4260. void setUnbalanced(IHqlExpression * body)
  4261. {
  4262. ANewTransformInfo * info = queryTransformExtra(body);
  4263. info->spareByte1 = true;
  4264. }
  4265. };
  4266. static HqlTransformerInfo spillActivityTransformerInfo("SpillActivityTransformer");
  4267. SpillActivityTransformer::SpillActivityTransformer()
  4268. : NewHqlTransformer(spillActivityTransformerInfo)
  4269. {
  4270. }
  4271. void SpillActivityTransformer::analyseExpr(IHqlExpression * expr)
  4272. {
  4273. IHqlExpression * body = expr->queryBody();
  4274. if (alreadyVisited(body))
  4275. return;
  4276. if (body->getOperator() == no_split)
  4277. {
  4278. IHqlExpression * input = body->queryChild(0);
  4279. if (input->getOperator() == no_split)
  4280. {
  4281. loop
  4282. {
  4283. IHqlExpression * cur = input->queryChild(0);
  4284. if (cur->getOperator() != no_split)
  4285. break;
  4286. input = cur;
  4287. }
  4288. if (!body->hasProperty(balancedAtom))
  4289. setUnbalanced(input->queryBody());
  4290. }
  4291. }
  4292. NewHqlTransformer::analyseExpr(expr);
  4293. }
  4294. IHqlExpression * SpillActivityTransformer::createTransformed(IHqlExpression * expr)
  4295. {
  4296. IHqlExpression * annotation = queryTransformAnnotation(expr);
  4297. if (annotation)
  4298. return annotation;
  4299. switch (expr->getOperator())
  4300. {
  4301. case no_split:
  4302. {
  4303. IHqlExpression * input = expr->queryChild(0);
  4304. if (input->getOperator() == no_split)
  4305. return transform(input);
  4306. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  4307. if (transformed->hasProperty(balancedAtom) && isUnbalanced(expr))
  4308. return removeProperty(transformed, balancedAtom);
  4309. return transformed.getClear();
  4310. }
  4311. case no_writespill:
  4312. {
  4313. HqlExprArray args;
  4314. transformChildren(expr, args);
  4315. return createValue(no_output, makeVoidType(), args);
  4316. }
  4317. case no_commonspill:
  4318. return transform(expr->queryChild(0));
  4319. case no_readspill:
  4320. {
  4321. OwnedHqlExpr ds = transform(expr->queryChild(0));
  4322. HqlExprArray args;
  4323. args.append(*transform(expr->queryChild(1)));
  4324. args.append(*LINK(ds->queryRecord()));
  4325. ForEachChildFrom(i, expr, 2)
  4326. {
  4327. IHqlExpression * cur = expr->queryChild(i);
  4328. args.append(*transform(cur));
  4329. }
  4330. IHqlExpression * recordCountAttr = queryRecordCountInfo(expr);
  4331. if (recordCountAttr)
  4332. args.append(*LINK(recordCountAttr));
  4333. return createDataset(no_table, args);
  4334. }
  4335. }
  4336. return NewHqlTransformer::createTransformed(expr);
  4337. }
  4338. IHqlExpression * convertSpillsToActivities(IHqlExpression * expr)
  4339. {
  4340. SpillActivityTransformer transformer;
  4341. transformer.analyse(expr, 0);
  4342. return transformer.transformRoot(expr);
  4343. }