hqlresource.cpp 164 KB

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