hqlresource.cpp 180 KB

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