hqlresource.cpp 199 KB

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