hqlresource.cpp 154 KB

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