hqlresource.cpp 168 KB

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