hqlresource.cpp 182 KB

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