hqlresource.cpp 183 KB

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