hqlcse.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jlib.hpp"
  16. #include "jmisc.hpp"
  17. #include "jstream.ipp"
  18. #include "hql.hpp"
  19. #include "hqlcse.ipp"
  20. #include "hqlutil.hpp"
  21. #include "hqlcpputil.hpp"
  22. #include "hqlthql.hpp"
  23. #include "hqlcatom.hpp"
  24. #include "hqlfold.hpp"
  25. #include "hqlpmap.hpp"
  26. #include "hqlopt.hpp"
  27. #include "hqlcerrors.hpp"
  28. #include "hqlttcpp.ipp"
  29. #ifdef _DEBUG
  30. //#define TRACE_CSE
  31. #endif
  32. //The following allows x != y and x == y to be commoned up. It works, but currently disabled
  33. //because cse doesn't preserve short circuit of AND and OR, and some examples mean it will do more
  34. //work because the alias will always be evaluated. (e.g., salt1.xhql)
  35. //Really aliases need to be functional and executed on demand or something similar.
  36. //#define OPTIMIZE_INVERSE
  37. //---------------------------------------------------------------------------
  38. inline bool canWrapWithCSE(IHqlExpression * expr)
  39. {
  40. switch (expr->getOperator())
  41. {
  42. case no_mapto:
  43. return false;
  44. }
  45. return true;
  46. }
  47. bool canCreateTemporary(IHqlExpression * expr)
  48. {
  49. switch (expr->getOperator())
  50. {
  51. case no_range:
  52. case no_rangefrom:
  53. case no_rangeto:
  54. case no_rangecommon:
  55. case no_constant:
  56. case no_all:
  57. case no_mapto:
  58. case no_record:
  59. case no_attr:
  60. case no_attr_expr:
  61. case no_attr_link:
  62. case no_joined:
  63. case no_sizeof:
  64. case no_offsetof:
  65. case no_newtransform:
  66. case no_transform:
  67. case no_assign:
  68. case no_assignall:
  69. case no_left:
  70. case no_right:
  71. case no_self:
  72. case no_top:
  73. case no_activetable:
  74. case no_alias:
  75. case no_skip:
  76. case no_assert:
  77. case no_counter:
  78. case no_sortlist:
  79. case no_matched:
  80. case no_matchtext:
  81. case no_matchunicode:
  82. case no_matchposition:
  83. case no_matchlength:
  84. case no_matchattr:
  85. case no_matchrow:
  86. case no_matchutf8:
  87. case no_recordlist:
  88. case no_transformlist:
  89. case no_rowvalue:
  90. case no_pipe:
  91. case no_colon:
  92. case no_globalscope:
  93. case no_subgraph:
  94. case no_forcelocal:
  95. case no_forcenolocal:
  96. case no_allnodes:
  97. case no_thisnode:
  98. case no_libraryscopeinstance:
  99. case no_loopbody:
  100. return false;
  101. }
  102. return !expr->isAction() && !expr->isTransform();
  103. }
  104. //---------------------------------------------------------------------------
  105. /*
  106. Cse spotting...
  107. * Don't remove named symbols from items that aren't transformed.
  108. * Common items up regardless of the named symbol used to reference it.
  109. */
  110. CseSpotterInfo::CseSpotterInfo(IHqlExpression * expr) : NewTransformInfo(expr)
  111. {
  112. numRefs = 0;
  113. numAssociatedRefs = 0;
  114. alreadyAliased = false;
  115. canAlias = false;
  116. dontTransform = false;
  117. dontTransformSelector = false;
  118. treatAsAliased = false;
  119. inverse = NULL;
  120. annotatedExpr = NULL;
  121. }
  122. //worth aliasing if referenced more than once, and used more than once in the expressions that are going to be evaluated now
  123. bool CseSpotterInfo::worthAliasingOnOwn()
  124. {
  125. return numRefs > 1 && (numRefs != numAssociatedRefs);
  126. }
  127. bool CseSpotterInfo::worthAliasing()
  128. {
  129. if (!inverse)
  130. return worthAliasingOnOwn();
  131. //no_not will always traverse the inverse (at least once), so don't sum the two counts - just use the non inverted count
  132. if (original->getOperator() == no_not)
  133. return worthAliasingOnOwn() || inverse->worthAliasingOnOwn();
  134. if (inverse->original->getOperator() == no_not)
  135. return worthAliasingOnOwn();
  136. unsigned totalRefs = numRefs + inverse->numRefs;
  137. unsigned totalAssociatedRefs = numAssociatedRefs + inverse->numAssociatedRefs;
  138. if ((totalRefs > 1) && (totalRefs != totalAssociatedRefs))
  139. return true;
  140. return false;
  141. }
  142. //Do we create an alias for this node, or the other one?
  143. bool CseSpotterInfo::useInverseForAlias()
  144. {
  145. if (!inverse)
  146. return false;
  147. if (numRefs == numAssociatedRefs)
  148. return true;
  149. node_operator op = original->getOperator();
  150. switch (op)
  151. {
  152. case no_not:
  153. case no_ne:
  154. case no_notin:
  155. case no_notbetween:
  156. case no_notexists:
  157. return inverse->worthAliasingOnOwn();
  158. }
  159. node_operator invOp = inverse->original->getOperator();
  160. switch (invOp)
  161. {
  162. case no_not: return false; //No otherwise we'll expand recursively!
  163. case no_ne:
  164. case no_notin:
  165. case no_notbetween:
  166. case no_notexists:
  167. return !worthAliasingOnOwn();
  168. }
  169. return op > invOp;
  170. }
  171. static HqlTransformerInfo cseSpotterInfo("CseSpotter");
  172. CseSpotter::CseSpotter()
  173. : NewHqlTransformer(cseSpotterInfo)
  174. {
  175. canAlias = true;
  176. isAssociated = false;
  177. spottedCandidate = false;
  178. invariantSelector = NULL;
  179. createLocalAliases = false;
  180. createdAlias = false;
  181. }
  182. void CseSpotter::analyseAssociated(IHqlExpression * expr, unsigned pass)
  183. {
  184. isAssociated = true;
  185. analyse(expr, pass);
  186. isAssociated = false;
  187. }
  188. void CseSpotter::analyseExpr(IHqlExpression * expr)
  189. {
  190. CseSpotterInfo * extra = queryBodyExtra(expr);
  191. if (!extra->annotatedExpr && expr->isAnnotation())
  192. extra->annotatedExpr = expr;
  193. if (isAssociated)
  194. extra->numAssociatedRefs++;
  195. node_operator op = expr->getOperator();
  196. #ifdef OPTIMIZE_INVERSE
  197. if (getInverseOp(op) != no_none)
  198. {
  199. OwnedHqlExpr inverse = getInverse(expr);
  200. CseSpotterInfo * inverseExtra = queryBodyExtra(inverse);
  201. extra->inverse = inverseExtra;
  202. inverseExtra->inverse = extra;
  203. }
  204. #endif
  205. if (op == no_alias)
  206. {
  207. queryBodyExtra(expr->queryChild(0))->alreadyAliased = true;
  208. extra->alreadyAliased = true;
  209. }
  210. if (extra->numRefs++ != 0)
  211. {
  212. if (!spottedCandidate && extra->worthAliasing() && (op != no_alias))
  213. spottedCandidate = true;
  214. //if (canCreateTemporary(expr))
  215. return;
  216. }
  217. if (!containsPotentialCSE(expr))
  218. return;
  219. if (canAlias && !expr->isDataset())
  220. extra->canAlias = true;
  221. bool savedCanAlias = canAlias;
  222. if (expr->isDataset() && (op != no_select))// && (op != no_if))
  223. {
  224. //There is little point looking for CSEs within dataset expressions, because only a very small
  225. //minority which would correctly cse, and it can cause lots of problems - e.g., join conditions.
  226. unsigned first = getFirstActivityArgument(expr);
  227. unsigned num = getNumActivityArguments(expr);
  228. HqlExprArray children;
  229. bool defaultCanAlias = canAlias;
  230. ForEachChild(i, expr)
  231. {
  232. IHqlExpression * cur = expr->queryChild(i);
  233. if (i >= first && i < first+num)
  234. canAlias = defaultCanAlias;
  235. else
  236. canAlias = false;
  237. analyseExpr(cur);
  238. }
  239. }
  240. else
  241. PARENT::analyseExpr(expr);
  242. canAlias = savedCanAlias;
  243. }
  244. IHqlExpression * CseSpotter::createAliasOwn(IHqlExpression * expr, CseSpotterInfo * extra)
  245. {
  246. #ifdef TRACE_CSE
  247. StringBuffer s;
  248. DBGLOG("Create alias for %s (%d refs)", getExprIdentifier(s, expr).str(), extra->numRefs);
  249. #endif
  250. extra->alreadyAliased = true;
  251. if (createLocalAliases)
  252. return ::createAliasOwn(expr, createLocalAttribute());
  253. return ::createAliasOwn(expr, NULL);
  254. }
  255. IHqlExpression * CseSpotter::createTransformed(IHqlExpression * expr)
  256. {
  257. node_operator op = expr->getOperator();
  258. switch (op)
  259. {
  260. case no_matched:
  261. case no_matchtext:
  262. case no_matchunicode:
  263. case no_matchposition:
  264. case no_matchlength:
  265. case no_matchrow:
  266. case no_matchutf8:
  267. //These actually go wrong if we remove the named symbols, so traverse under no circumstances.
  268. //others can be traversed to patch up references to datasets that have changed.
  269. case no_translated:
  270. return LINK(expr);
  271. }
  272. OwnedHqlExpr transformed = PARENT::createTransformed(expr);
  273. CseSpotterInfo * splitter = queryBodyExtra(expr);
  274. //MORE: Possibly add a unique number to the alias when this starts worrying about child scopes.
  275. if (splitter->canAlias && splitter->worthAliasing() && checkPotentialCSE(expr, splitter))
  276. {
  277. if (splitter->useInverseForAlias())
  278. {
  279. OwnedHqlExpr inverse = getInverse(expr);
  280. OwnedHqlExpr transformedInverse = transform(inverse);
  281. return getInverse(transformedInverse);
  282. }
  283. createdAlias = true;
  284. //Use the transformed body to ensure that any cses only create a single instance,
  285. //But annotate with first annotation spotted, try and retain the symbols to aid debugging.
  286. LinkedHqlExpr aliasValue = transformed->queryBody();
  287. // if (splitter->annotatedExpr)
  288. // aliasValue.setown(splitter->annotatedExpr->cloneAllAnnotations(aliasValue));
  289. OwnedHqlExpr alias = createAliasOwn(aliasValue.getClear(), splitter);
  290. return alias.getClear();
  291. return expr->cloneAllAnnotations(alias);
  292. }
  293. return transformed.getClear();
  294. }
  295. ANewTransformInfo * CseSpotter::createTransformInfo(IHqlExpression * expr)
  296. {
  297. return CREATE_NEWTRANSFORMINFO(CseSpotterInfo, expr);
  298. }
  299. bool CseSpotter::containsPotentialCSE(IHqlExpression * expr)
  300. {
  301. switch (expr->getOperator())
  302. {
  303. case no_record:
  304. case no_attr:
  305. case no_attr_expr:
  306. case no_attr_link:
  307. case no_joined:
  308. case no_sizeof:
  309. case no_offsetof:
  310. case no_field:
  311. case no_evaluate: // MORE: This is an example of introducing a new scope...
  312. case no_translated: // Causes recursion otherwise....
  313. case no_left:
  314. case no_right:
  315. case no_top:
  316. case no_self:
  317. case no_selfref:
  318. case no_activetable:
  319. case no_filepos:
  320. case no_file_logicalname:
  321. case no_matched:
  322. case no_matchtext:
  323. case no_matchunicode:
  324. case no_matchposition:
  325. case no_matchrow:
  326. case no_matchlength:
  327. case no_matchutf8:
  328. case no_catch:
  329. case no_projectrow:
  330. // case no_evalonce:
  331. return false;
  332. case no_select:
  333. return false; //isNewSelector(expr);
  334. case NO_AGGREGATE:
  335. //There may possibly be cses, but we would need to do lots of scoping analysis to work out whether they were
  336. //really common.
  337. return false;
  338. case no_assign:
  339. case no_assignall:
  340. case no_transform:
  341. case no_newtransform:
  342. case no_range:
  343. case no_rangefrom:
  344. case no_rangeto:
  345. case no_rangecommon:
  346. case no_skip:
  347. return true;
  348. case no_compound_diskread:
  349. case no_compound_indexread:
  350. case no_compound_disknormalize:
  351. case no_compound_diskaggregate:
  352. case no_compound_diskcount:
  353. case no_compound_diskgroupaggregate:
  354. case no_compound_indexnormalize:
  355. case no_compound_indexaggregate:
  356. case no_compound_indexcount:
  357. case no_compound_indexgroupaggregate:
  358. case no_compound_childread:
  359. case no_compound_childnormalize:
  360. case no_compound_childaggregate:
  361. case no_compound_childcount:
  362. case no_compound_childgroupaggregate:
  363. case no_compound_selectnew:
  364. case no_compound_inline:
  365. return false;
  366. #if 0
  367. //Strictly speaking, we shouldn't common up conditional expressions, but it generally provides such a reduction in code
  368. //that it will stay enabled until I come up with a better scheme.
  369. case no_if:
  370. case no_rejected:
  371. case no_which:
  372. case no_case:
  373. case no_map:
  374. return false;
  375. #endif
  376. }
  377. ITypeInfo * type = expr->queryType();
  378. if (type && type->getTypeCode() == type_void)
  379. return false;
  380. return !expr->isConstant();// || expr->isDataset() || expr->isDatarow();
  381. }
  382. bool CseSpotter::checkPotentialCSE(IHqlExpression * expr, CseSpotterInfo * extra)
  383. {
  384. if (extra->alreadyAliased)
  385. return false;
  386. if (!expr->isPure() || !canCreateTemporary(expr))
  387. return false;
  388. if (invariantSelector && exprReferencesDataset(expr, invariantSelector))
  389. return false;
  390. switch (expr->getOperator())
  391. {
  392. case no_eq:
  393. case no_ne:
  394. case no_gt:
  395. case no_ge:
  396. case no_lt:
  397. case no_le:
  398. {
  399. //Don't combine integer comparisons into a CSE - not worth it...
  400. ITypeInfo * type = expr->queryChild(0)->queryType();
  401. switch (type->getTypeCode())
  402. {
  403. case type_boolean:
  404. case type_int:
  405. return false;
  406. }
  407. return true;
  408. }
  409. case no_not:
  410. {
  411. IHqlExpression * child = expr->queryChild(0);
  412. if (queryBodyExtra(child)->isAliased())
  413. return false;
  414. break;
  415. }
  416. case no_charlen:
  417. {
  418. IHqlExpression * child = expr->queryChild(0);
  419. if (queryBodyExtra(child)->isAliased() || child->getOperator() == no_select)
  420. {
  421. type_t tc = child->queryType()->getTypeCode();
  422. switch (tc)
  423. {
  424. case type_varstring:
  425. case type_varunicode:
  426. return true;
  427. }
  428. //prevent (trivial-cast)length(x) from being serialized etc.
  429. extra->treatAsAliased = true;
  430. return false;
  431. }
  432. break;
  433. }
  434. case no_field:
  435. throwUnexpected();
  436. case no_select:
  437. return false; //expr->hasProperty(newAtom);
  438. case no_list:
  439. case no_datasetlist:
  440. case no_getresult: // these are commoned up in the code generator, so don't do it twice.
  441. case no_getgraphresult:
  442. case no_getgraphloopresult:
  443. case no_translated: // Causes recursion otherwise....
  444. case no_random:
  445. return false;
  446. case no_call:
  447. case no_externalcall:
  448. case no_libraryinput:
  449. case no_counter:
  450. return true;
  451. case no_substring:
  452. {
  453. IHqlExpression * child = expr->queryChild(0);
  454. // if (queryBodyExtra(child)->isAliased())
  455. {
  456. SubStringHelper helper(expr);
  457. return !helper.canGenerateInline();
  458. }
  459. return true;
  460. }
  461. case no_cast:
  462. case no_implicitcast:
  463. {
  464. ITypeInfo * exprType = expr->queryType();
  465. if (exprType->getTypeCode() == type_set)
  466. return false;
  467. IHqlExpression * uncast = expr->queryChild(0);
  468. if (uncast->queryValue())
  469. return false;
  470. //Ignore integral casts of items that have already been aliased
  471. if (queryBodyExtra(uncast)->isAliased())
  472. {
  473. if (exprType->isInteger() && uncast->queryType()->isInteger())
  474. {
  475. if (extra->numRefs < 5)
  476. return false;
  477. }
  478. }
  479. break;
  480. }
  481. //Following are all source datasets - no point in commoning them up
  482. //although probably exceptions e.g., table(,pipe)
  483. case no_none:
  484. case no_null:
  485. case no_anon:
  486. case no_pseudods:
  487. case no_all:
  488. // case no_table: - normally work commoning up
  489. case no_temptable:
  490. case no_inlinetable:
  491. case no_xmlproject:
  492. case no_datasetfromrow:
  493. case no_preservemeta:
  494. case no_dataset_alias:
  495. case no_workunit_dataset:
  496. case no_left:
  497. case no_right:
  498. case no_top:
  499. case no_self:
  500. case no_selfref:
  501. case no_keyindex:
  502. case no_newkeyindex:
  503. case no_fail:
  504. case no_activetable:
  505. case no_soapcall:
  506. case no_newsoapcall:
  507. case no_id2blob:
  508. case no_cppbody:
  509. case no_rows:
  510. return false;
  511. }
  512. if (!expr->queryType())
  513. return false;
  514. return (expr->numChildren() > 0);
  515. }
  516. IHqlExpression * CseSpotter::transform(IHqlExpression * expr)
  517. {
  518. return PARENT::transform(expr);
  519. }
  520. IHqlExpression * CseSpotter::queryAlreadyTransformed(IHqlExpression * expr)
  521. {
  522. CseSpotterInfo * extra = queryBodyExtra(expr);
  523. if (extra->dontTransform)
  524. return expr;
  525. IHqlExpression * ret = PARENT::queryAlreadyTransformed(expr);
  526. if (!ret)
  527. {
  528. IHqlExpression * body = expr->queryBody();
  529. if (body != expr)
  530. {
  531. ret = PARENT::queryAlreadyTransformed(body);
  532. if (ret == body)
  533. return NULL;
  534. }
  535. }
  536. return ret;
  537. }
  538. IHqlExpression * CseSpotter::queryAlreadyTransformedSelector(IHqlExpression * expr)
  539. {
  540. CseSpotterInfo * extra = queryBodyExtra(expr);
  541. if (extra->dontTransformSelector)
  542. return expr;
  543. return PARENT::queryAlreadyTransformedSelector(expr);
  544. }
  545. void CseSpotter::stopTransformation(IHqlExpression * expr)
  546. {
  547. IHqlExpression * normalized = expr->queryNormalizedSelector();
  548. queryBodyExtra(expr)->dontTransform = true;
  549. queryBodyExtra(normalized)->dontTransformSelector = true;
  550. }
  551. //---------------------------------------------------------------------------
  552. static HqlTransformerInfo conjunctionTransformerInfo("ConjunctionTransformer");
  553. ConjunctionTransformer::ConjunctionTransformer() : NewHqlTransformer(conjunctionTransformerInfo)
  554. {
  555. }
  556. IHqlExpression * ConjunctionTransformer::createTransformed(IHqlExpression * expr)
  557. {
  558. node_operator op = expr->getOperator();
  559. OwnedHqlExpr transformed;
  560. switch (op)
  561. {
  562. case no_matched:
  563. case no_matchtext:
  564. case no_matchunicode:
  565. case no_matchlength:
  566. case no_matchposition:
  567. case no_matchrow:
  568. case no_matchutf8:
  569. return LINK(expr);
  570. //not so sure why the following causes problems - because the tables get changed I think.
  571. case no_filepos:
  572. case no_file_logicalname:
  573. case no_sizeof:
  574. case no_offsetof:
  575. return LINK(expr);
  576. case no_and:
  577. case no_or:
  578. {
  579. IHqlExpression * left = expr->queryChild(0);
  580. if (left->getOperator() == op)
  581. {
  582. HqlExprArray args, transformedArgs;
  583. left->unwindList(args, op);
  584. ForEachItemIn(i, args)
  585. transformedArgs.append(*transform(&args.item(i)));
  586. transformedArgs.append(*transform(expr->queryChild(1)));
  587. transformed.setown(createLeftBinaryList(op, transformedArgs));
  588. // return expr->cloneAllAnnotations(transformed);
  589. }
  590. break;
  591. }
  592. }
  593. if (!transformed)
  594. transformed.setown(NewHqlTransformer::createTransformed(expr));
  595. return transformed.getClear();
  596. }
  597. //---------------------------------------------------------------------------
  598. #ifdef NEW_CSE_PROCESSING
  599. inline bool canInsertCodeAlias(IHqlExpression * expr)
  600. {
  601. switch (expr->getOperator())
  602. {
  603. case no_range:
  604. case no_rangefrom:
  605. case no_rangeto:
  606. case no_rangecommon:
  607. case no_mapto:
  608. case no_recordlist:
  609. case no_transformlist:
  610. case no_rowvalue:
  611. case no_sortlist:
  612. return false;
  613. default:
  614. return true;
  615. }
  616. }
  617. static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
  618. CseScopeTransformer::CseScopeTransformer()
  619. : NewHqlTransformer(cseScopeTransformerInfo)
  620. {
  621. activeParent = NULL;
  622. seq = 0;
  623. conditionDepth = 0;
  624. }
  625. void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
  626. {
  627. expr = expr->queryBody();
  628. if (!containsNonGlobalAlias(expr))
  629. return;
  630. node_operator op = expr->getOperator();
  631. CseScopeInfo * splitter = queryExtra(expr);
  632. if (splitter->seq)
  633. {
  634. splitter->hasSharedParent = true;
  635. splitter->addParent(activeParent);
  636. return;
  637. }
  638. splitter->firstParent = activeParent;
  639. splitter->seq = ++seq;
  640. splitter->isUnconditional = (conditionDepth == 0);
  641. {
  642. IHqlExpression * savedParent = activeParent;
  643. activeParent = expr;
  644. switch (op)
  645. {
  646. case no_if:
  647. case no_or:
  648. case no_and:
  649. case no_case:
  650. {
  651. analyseExpr(expr->queryChild(0));
  652. conditionDepth++;
  653. ForEachChildFrom(i, expr, 1)
  654. analyseExpr(expr->queryChild(i));
  655. conditionDepth--;
  656. break;
  657. }
  658. default:
  659. NewHqlTransformer::analyseExpr(expr);
  660. break;
  661. }
  662. activeParent = savedParent;
  663. }
  664. //Add here so the cse are in the correct order to cope with dependencies...
  665. if (op == no_alias)
  666. {
  667. assertex(!expr->hasProperty(globalAtom));
  668. allCSEs.append(*LINK(splitter));
  669. }
  670. }
  671. bool CseScopeTransformer::attachCSEs(IHqlExpression * root)
  672. {
  673. bool changed = false;
  674. ForEachItemIn(idx, allCSEs)
  675. {
  676. CseScopeInfo& cur = allCSEs.item(idx);
  677. IHqlExpression * aliasLocation = findAliasLocation(&cur);
  678. if (!aliasLocation && cur.isUnconditional)
  679. aliasLocation = root;
  680. if (aliasLocation && aliasLocation != cur.original)
  681. {
  682. queryExtra(aliasLocation)->aliasesToDefine.append(*LINK(cur.original));
  683. changed = true;
  684. }
  685. }
  686. return changed;
  687. }
  688. IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
  689. {
  690. //Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
  691. IHqlExpression * body = expr->queryBody(true);
  692. if (body != expr)
  693. {
  694. OwnedHqlExpr ret = transform(body);
  695. return expr->cloneAnnotation(ret);
  696. }
  697. //slight difference from before...
  698. IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
  699. CseScopeInfo * splitter = queryExtra(expr);
  700. if (splitter->aliasesToDefine.ordinality())
  701. {
  702. HqlExprArray args;
  703. args.append(*transformed);
  704. ForEachItemIn(idx, splitter->aliasesToDefine)
  705. {
  706. IHqlExpression * value = &splitter->aliasesToDefine.item(idx);
  707. args.append(*transform(value));
  708. }
  709. if (expr->isDataset())
  710. transformed = createDataset(no_alias_scope, args);
  711. else if (expr->isDatarow())
  712. transformed = createRow(no_alias_scope, args);
  713. else
  714. transformed = createValue(no_alias_scope, transformed->getType(), args);
  715. }
  716. return transformed;
  717. }
  718. ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
  719. {
  720. return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
  721. }
  722. //First find the highest shared parent node (or this if no parents are shared)
  723. CseScopeInfo * CseScopeTransformer::calcCommonLocation(CseScopeInfo * extra)
  724. {
  725. if (extra->calcedCommonLocation)
  726. return extra->commonLocation;
  727. CseScopeInfo * commonLocation = extra;
  728. if (extra->firstParent)
  729. {
  730. CseScopeInfo * firstParentExtra = queryExtra(extra->firstParent);
  731. CseScopeInfo * commonParent = calcCommonLocation(firstParentExtra);
  732. if ((extra->parents.ordinality() == 0) && (!firstParentExtra->hasSharedParent || extra->firstParent->getOperator() == no_alias))
  733. // if ((extra->parents.ordinality() == 0) && !firstParentExtra->hasSharedParent)
  734. {
  735. //assertex(commonParent == firstParentExtra);
  736. //commonParent = extra;
  737. }
  738. else
  739. {
  740. extra->hasSharedParent = true;
  741. commonLocation = commonParent;
  742. ForEachItemIn(i, extra->parents)
  743. {
  744. CseScopeInfo * nextExtra = calcCommonLocation(queryExtra(extra->parents.item(i)));
  745. if (nextExtra->isUnconditional)
  746. extra->isUnconditional = true;
  747. commonLocation = findCommonPath(commonLocation, nextExtra);
  748. if (!commonLocation && extra->isUnconditional)
  749. break;
  750. }
  751. }
  752. }
  753. else
  754. {
  755. if (extra->hasSharedParent)
  756. commonLocation = NULL;
  757. }
  758. extra->calcedCommonLocation = true;
  759. extra->commonLocation = commonLocation;
  760. return commonLocation;
  761. }
  762. IHqlExpression * CseScopeTransformer::findAliasLocation(CseScopeInfo * extra)
  763. {
  764. CseScopeInfo * best = calcCommonLocation(extra);
  765. loop
  766. {
  767. if (!best)
  768. return NULL;
  769. IHqlExpression * bestLocation = best->original;
  770. if (canInsertCodeAlias(bestLocation))
  771. return bestLocation;
  772. best = selectParent(best);
  773. }
  774. }
  775. CseScopeInfo * CseScopeTransformer::selectParent(CseScopeInfo * info)
  776. {
  777. if (info->hasSharedParent)
  778. return info->commonLocation;
  779. if (!info->firstParent)
  780. return NULL;
  781. return queryExtra(info->firstParent);
  782. }
  783. CseScopeInfo * CseScopeTransformer::findCommonPath(CseScopeInfo * left, CseScopeInfo * right)
  784. {
  785. loop
  786. {
  787. if (!left || !right)
  788. return NULL;
  789. if (left == right)
  790. return left;
  791. if (left->seq > right->seq)
  792. left = selectParent(left);
  793. else
  794. right = selectParent(right);
  795. }
  796. }
  797. #else
  798. CSEentry::CSEentry(IHqlExpression * _value, PathArray & _path)
  799. {
  800. value.set(_value);
  801. unsigned depth=_path.ordinality();
  802. path.ensure(depth);
  803. ForEachItemIn(idx, _path)
  804. path.append(_path.item(idx));
  805. ensurePathValid();
  806. }
  807. void CSEentry::ensurePathValid()
  808. {
  809. //It is not valid to insert a no_code_alias at certain points....
  810. while (path.ordinality())
  811. {
  812. switch (path.tos().getOperator())
  813. {
  814. case no_range:
  815. case no_rangefrom:
  816. case no_rangeto:
  817. case no_rangecommon:
  818. case no_mapto:
  819. case no_recordlist:
  820. case no_transformlist:
  821. case no_rowvalue:
  822. case no_sortlist:
  823. path.pop();
  824. break;
  825. default:
  826. return;
  827. }
  828. }
  829. }
  830. void CSEentry::findCommonPath(PathArray & otherPath)
  831. {
  832. unsigned prevPath = path.ordinality();
  833. unsigned maxPath = path.ordinality();
  834. if (maxPath > otherPath.ordinality())
  835. maxPath = otherPath.ordinality();
  836. unsigned idx;
  837. for (idx = 0; idx < maxPath; idx++)
  838. {
  839. IHqlExpression * l = &path.item(idx);
  840. IHqlExpression * r = &otherPath.item(idx);
  841. if (l != r)
  842. break;
  843. }
  844. //Ensure the new location is valid for receiving the CSE
  845. while (idx != 0)
  846. {
  847. if (canWrapWithCSE(&path.item(idx-1)))
  848. break;
  849. idx--;
  850. }
  851. path.trunc(idx);
  852. if (prevPath != path.ordinality())
  853. {
  854. ForEachItemIn(idx2, dependsOn)
  855. dependsOn.item(idx2).findCommonPath(path);
  856. }
  857. ensurePathValid();
  858. }
  859. static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
  860. CseScopeTransformer::CseScopeTransformer()
  861. : NewHqlTransformer(cseScopeTransformerInfo)
  862. {
  863. }
  864. void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
  865. {
  866. expr = expr->queryBody();
  867. if (!containsNonGlobalAlias(expr))
  868. return;
  869. CSEentry * cse = NULL;
  870. node_operator op = expr->getOperator();
  871. if (op == no_alias)
  872. {
  873. assertex(!expr->hasProperty(globalAtom));
  874. CseScopeInfo * splitter = queryExtra(expr);
  875. //PrintLog("splitter: %s", expr->toString(StringBuffer()).str());
  876. if (splitter->cseUse)
  877. {
  878. //Find the common path, and map the alias.
  879. CSEentry * cse = splitter->cseUse;
  880. cse->findCommonPath(path);
  881. if (activeCSE.ordinality())
  882. activeCSE.tos().dependsOn.append(*LINK(cse));
  883. return;
  884. }
  885. cse = new CSEentry(expr, path);
  886. splitter->cseUse.setown(cse);
  887. if (activeCSE.ordinality())
  888. activeCSE.tos().dependsOn.append(*LINK(cse));
  889. activeCSE.append(*LINK(cse));
  890. }
  891. #if 0
  892. if ((op == no_transform) || (op == no_newtransform))
  893. {
  894. //For a transform add each assignment as a path point - so the aliases for assignments don't end up
  895. //before aliases for skip attributes.
  896. path.append(*expr);
  897. ForEachChild(i, expr)
  898. {
  899. IHqlExpression * cur = expr->queryChild(i);
  900. analyseExpr(cur);
  901. path.append(*cur);
  902. }
  903. ForEachChild(i2, expr)
  904. path.pop();
  905. path.pop();
  906. }
  907. else
  908. #endif
  909. {
  910. path.append(*expr);
  911. NewHqlTransformer::analyseExpr(expr);
  912. path.pop();
  913. }
  914. //Add here so the cse are in the correct order to cope with dependencies...
  915. if (cse)
  916. {
  917. allCSEs.append(*LINK(cse));
  918. activeCSE.pop();
  919. }
  920. }
  921. bool CseScopeTransformer::attachCSEs(IHqlExpression * /*root*/)
  922. {
  923. bool changed = false;
  924. ForEachItemIn(idx, allCSEs)
  925. {
  926. CSEentry & cur = allCSEs.item(idx);
  927. if (cur.path.ordinality())
  928. {
  929. IHqlExpression & location = cur.path.tos();
  930. queryExtra(&location)->cseDefine.append(OLINK(cur));
  931. changed = true;
  932. }
  933. }
  934. return changed;
  935. }
  936. IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
  937. {
  938. //Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
  939. IHqlExpression * body = expr->queryBody(true);
  940. if (body != expr)
  941. {
  942. OwnedHqlExpr ret = transform(body);
  943. return expr->cloneAnnotation(ret);
  944. }
  945. //slight difference from before...
  946. IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
  947. CseScopeInfo * splitter = queryExtra(expr);
  948. if (splitter->cseDefine.ordinality())
  949. {
  950. HqlExprArray args;
  951. args.append(*transformed);
  952. ForEachItemIn(idx, splitter->cseDefine)
  953. {
  954. CSEentry & cur = splitter->cseDefine.item(idx);
  955. args.append(*transform(cur.value));
  956. }
  957. if (expr->isDataset())
  958. transformed = createDataset(no_alias_scope, args);
  959. else if (expr->isDatarow())
  960. transformed = createRow(no_alias_scope, args);
  961. else
  962. transformed = createValue(no_alias_scope, transformed->getType(), args);
  963. }
  964. return transformed;
  965. }
  966. ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
  967. {
  968. return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
  969. }
  970. #endif
  971. IHqlExpression * spotScalarCSE(IHqlExpression * expr, IHqlExpression * limit)
  972. {
  973. if (expr->isConstant())
  974. return LINK(expr);
  975. switch (expr->getOperator())
  976. {
  977. case no_select:
  978. if (!expr->hasProperty(newAtom))
  979. return LINK(expr);
  980. break;
  981. }
  982. OwnedHqlExpr transformed = LINK(expr); //removeNamedSymbols(expr);
  983. bool addedAliases = false;
  984. //First spot the aliases - so that restructuring the ands doesn't lose any existing aliases.
  985. {
  986. CseSpotter spotter;
  987. spotter.analyse(transformed, 0);
  988. if (spotter.foundCandidates())
  989. {
  990. if (limit)
  991. spotter.stopTransformation(limit);
  992. transformed.setown(spotter.transformRoot(transformed));
  993. addedAliases = spotter.createdNewAliases();
  994. }
  995. }
  996. if (!containsAlias(transformed))
  997. return transformed.getClear();
  998. //Transform conjunctions so they are (a AND (b AND (c AND d))) not (((a AND b) AND c) AND d)
  999. //so that alias scope can be introduced in a better place.
  1000. {
  1001. ConjunctionTransformer tr;
  1002. transformed.setown(tr.transformRoot(transformed));
  1003. }
  1004. if (!addedAliases)
  1005. return transformed.getClear();
  1006. //Now work out where in the tree the aliases should be evaluated.
  1007. {
  1008. CseScopeTransformer scoper;
  1009. scoper.analyse(transformed, 0);
  1010. if (scoper.attachCSEs(transformed))
  1011. transformed.setown(scoper.transformRoot(transformed));
  1012. }
  1013. return transformed.getClear();
  1014. }
  1015. void spotScalarCSE(SharedHqlExpr & expr, SharedHqlExpr & associated, IHqlExpression * limit, IHqlExpression * invariantSelector)
  1016. {
  1017. CseSpotter spotter;
  1018. spotter.analyse(expr, 0);
  1019. if (associated)
  1020. spotter.analyseAssociated(associated, 0);
  1021. if (!spotter.foundCandidates())
  1022. return;
  1023. if (limit)
  1024. spotter.stopTransformation(limit);
  1025. if (invariantSelector)
  1026. spotter.setInvariantSelector(invariantSelector);
  1027. expr.setown(spotter.transformRoot(expr));
  1028. associated.setown(spotter.transformRoot(associated));
  1029. }
  1030. void spotScalarCSE(HqlExprArray & exprs, HqlExprArray & associated, IHqlExpression * limit, IHqlExpression * invariantSelector)
  1031. {
  1032. CseSpotter spotter;
  1033. spotter.analyseArray(exprs, 0);
  1034. ForEachItemIn(ia, associated)
  1035. spotter.analyseAssociated(&associated.item(ia), 0);
  1036. if (!spotter.foundCandidates())
  1037. return;
  1038. if (limit)
  1039. spotter.stopTransformation(limit);
  1040. if (invariantSelector)
  1041. spotter.setInvariantSelector(invariantSelector);
  1042. HqlExprArray newExprs;
  1043. HqlExprArray newAssociated;
  1044. spotter.transformRoot(exprs, newExprs);
  1045. spotter.transformRoot(associated, newAssociated);
  1046. replaceArray(exprs, newExprs);
  1047. replaceArray(associated, newAssociated);
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. //The TableInvariantTransformer is important for ensuring that getResultXXX code is executed in the code context, amongst other things
  1051. //It must ensure that any global aliases couldn't contain some other global aliases inside a child query, otherwise when the child query is
  1052. //evaluated the result won't be in the correct place.
  1053. //
  1054. //MORE: This could be improved to work out whether it is worth creating an alias (which will then be serialized...)
  1055. //e.g., don't alias i) <alias<n>> +- offset or ii) extension of an alias's size., iii) substring of a fixed size string. iv) length(string
  1056. //however it is pretty good as it stands.
  1057. //ideally it would need information about how many times the expression is likely to be evaluated (e.g., 1/many)
  1058. //so that could be taken into account (e.g, filenames which are 'string' + conditional)
  1059. static bool canHoistInvariant(IHqlExpression * expr)
  1060. {
  1061. if (!canCreateTemporary(expr))
  1062. {
  1063. if ((expr->getOperator() != no_alias) || expr->hasProperty(globalAtom))
  1064. return false;
  1065. }
  1066. if (!expr->isPure())
  1067. return false;
  1068. switch (expr->getOperator())
  1069. {
  1070. case no_list:
  1071. case no_datasetlist:
  1072. return false; // probably don't want to hoist these
  1073. }
  1074. return true;
  1075. }
  1076. static HqlTransformerInfo tableInvariantTransformerInfo("TableInvariantTransformer");
  1077. TableInvariantTransformer::TableInvariantTransformer() : NewHqlTransformer(tableInvariantTransformerInfo)
  1078. {
  1079. canAlias = true;
  1080. }
  1081. bool TableInvariantTransformer::isInvariant(IHqlExpression * expr)
  1082. {
  1083. TableInvariantInfo * extra = queryBodyExtra(expr);
  1084. if (extra->cachedInvariant)
  1085. return extra->isInvariant;
  1086. bool invariant = false;
  1087. node_operator op = expr->getOperator();
  1088. switch (op)
  1089. {
  1090. case no_record:
  1091. case no_null:
  1092. case no_activetable:
  1093. case no_activerow:
  1094. case no_left:
  1095. case no_right:
  1096. case no_self:
  1097. case no_top:
  1098. case no_selfref:
  1099. case no_filepos:
  1100. case no_file_logicalname:
  1101. case no_joined:
  1102. case no_offsetof:
  1103. case no_sizeof:
  1104. case NO_AGGREGATE:
  1105. break;
  1106. case no_preservemeta:
  1107. invariant = isInvariant(expr->queryChild(0));
  1108. break;
  1109. case no_constant:
  1110. case no_workunit_dataset:
  1111. case no_getresult:
  1112. case no_getgraphresult:
  1113. invariant = true;
  1114. break;
  1115. case no_select:
  1116. {
  1117. IHqlExpression * ds = expr->queryChild(0);
  1118. if ((expr->hasProperty(newAtom) || ds->isDatarow()) && !expr->isDataset())
  1119. invariant = isInvariant(ds);
  1120. break;
  1121. }
  1122. case no_newaggregate:
  1123. {
  1124. //Allow these on a very strict subset of the datasets - to ensure that no potential globals can be included in the dataset
  1125. if (!isInvariant(expr->queryChild(0)))
  1126. break;
  1127. switch (querySimpleAggregate(expr, false, true))
  1128. {
  1129. case no_existsgroup:
  1130. case no_countgroup:
  1131. invariant = true;
  1132. break;
  1133. }
  1134. break;
  1135. }
  1136. case no_selectnth:
  1137. switch (expr->queryChild(1)->getOperator())
  1138. {
  1139. case no_constant:
  1140. case no_counter:
  1141. invariant = isInvariant(expr->queryChild(0));
  1142. break;
  1143. }
  1144. break;
  1145. default:
  1146. if (!isContextDependent(expr))
  1147. {
  1148. if (!expr->isAction())// && !expr->isDataset() && !expr->isDatarow())
  1149. {
  1150. invariant = true;
  1151. ForEachChild(i, expr)
  1152. {
  1153. IHqlExpression * cur = expr->queryChild(i);
  1154. if (!isInvariant(cur))
  1155. {
  1156. invariant = false;
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. }
  1162. break;
  1163. }
  1164. extra->cachedInvariant = true;
  1165. extra->isInvariant = invariant;
  1166. return invariant;
  1167. }
  1168. #if 0
  1169. void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
  1170. {
  1171. expr = expr->queryBody();
  1172. if (alreadyVisited(expr))
  1173. return;
  1174. node_operator op = expr->getOperator();
  1175. switch (op)
  1176. {
  1177. case no_record:
  1178. case no_constant:
  1179. return;
  1180. }
  1181. if (isInvariant(expr) && !expr->isAttribute() && !expr->isConstant() && canHoistInvariant(expr))
  1182. {
  1183. TableInvariantInfo * extra = queryBodyExtra(expr);
  1184. if (op == no_alias)
  1185. {
  1186. if (!expr->hasProperty(globalAtom))
  1187. extra->createAlias = true;
  1188. }
  1189. else
  1190. extra->createAlias = true;
  1191. return;
  1192. }
  1193. if (op == no_attr_expr)
  1194. analyseChildren(expr);
  1195. else
  1196. NewHqlTransformer::analyseExpr(expr);
  1197. }
  1198. #else
  1199. void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
  1200. {
  1201. expr = expr->queryBody();
  1202. TableInvariantInfo * extra = queryBodyExtra(expr);
  1203. if (alreadyVisited(expr))
  1204. return;
  1205. //More - these need to be handled properly...
  1206. node_operator op = expr->getOperator();
  1207. switch (op)
  1208. {
  1209. case no_record:
  1210. case no_constant:
  1211. return;
  1212. }
  1213. //We are trying to ensure that any expressions that don't access fields that are dependent on the activeDatasets/context are only
  1214. //evaluated once => check for active dataset rather than any dataset
  1215. bool candidate = false;
  1216. if (!isContextDependent(expr) && !expr->isAttribute())
  1217. {
  1218. if (isInlineTrivialDataset(expr) && !expr->isConstant())
  1219. {
  1220. candidate = (op != no_null);
  1221. }
  1222. else
  1223. {
  1224. if (!containsActiveDataset(expr))
  1225. {
  1226. //MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
  1227. //e.g., stops items it contains from being aliased. So
  1228. if (!expr->isAction() && !expr->isDataset() && !expr->isDatarow())
  1229. {
  1230. switch (op)
  1231. {
  1232. case no_alias:
  1233. if (!expr->hasProperty(globalAtom))
  1234. extra->createAlias = true;
  1235. return;
  1236. default:
  1237. //MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
  1238. //e.g., stops items it contains from being aliased.
  1239. candidate = !expr->isConstant();
  1240. break;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. if (candidate && canHoistInvariant(expr))
  1246. {
  1247. extra->createAlias = true;
  1248. return;
  1249. }
  1250. }
  1251. if (op == no_attr_expr)
  1252. analyseChildren(expr);
  1253. else
  1254. NewHqlTransformer::analyseExpr(expr);
  1255. }
  1256. #endif
  1257. bool TableInvariantTransformer::isTrivialAlias(IHqlExpression * expr)
  1258. {
  1259. switch (expr->getOperator())
  1260. {
  1261. case no_cast:
  1262. case no_implicitcast:
  1263. //Don't create aliases for items that are simply integral casts of other aliases.
  1264. {
  1265. ITypeInfo * type = expr->queryType();
  1266. if (type->isInteger())
  1267. {
  1268. IHqlExpression * cast = expr->queryChild(0);
  1269. ITypeInfo * castType = cast->queryType();
  1270. if (castType->isInteger() && (queryBodyExtra(cast)->createAlias || cast->getOperator() == no_alias))
  1271. {
  1272. switch (type->getSize())
  1273. {
  1274. case 1: case 2: case 4: case 8:
  1275. return true;
  1276. }
  1277. }
  1278. }
  1279. break;
  1280. }
  1281. case no_not:
  1282. {
  1283. IHqlExpression * child = expr->queryChild(0);
  1284. if (queryBodyExtra(child)->createAlias || child->getOperator() == no_alias)
  1285. return true;
  1286. break;
  1287. }
  1288. }
  1289. return false;
  1290. }
  1291. IHqlExpression * TableInvariantTransformer::createTransformed(IHqlExpression * expr)
  1292. {
  1293. if (expr->getOperator() == no_alias)
  1294. {
  1295. OwnedHqlExpr newChild = transform(expr->queryChild(0));
  1296. if (newChild->getOperator() == no_alias)
  1297. return newChild.getClear();
  1298. }
  1299. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  1300. if (queryBodyExtra(expr)->createAlias)
  1301. {
  1302. if (!isTrivialAlias(expr))
  1303. {
  1304. OwnedHqlExpr attr = createAttribute(globalAtom);
  1305. if (transformed->getOperator() == no_alias)
  1306. transformed.set(transformed->queryChild(0));
  1307. return createAlias(transformed->queryBody(), attr);
  1308. }
  1309. }
  1310. return transformed.getClear();
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. IHqlExpression * spotTableInvariant(IHqlExpression * expr)
  1314. {
  1315. TableInvariantTransformer transformer;
  1316. transformer.analyse(expr, 0);
  1317. return transformer.transformRoot(expr);
  1318. }
  1319. IHqlExpression * spotTableInvariantChildren(IHqlExpression * expr)
  1320. {
  1321. TableInvariantTransformer transformer;
  1322. ForEachChild(i1, expr)
  1323. transformer.analyse(expr->queryChild(i1), 0);
  1324. return transformer.transformRoot(expr);
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. static HqlTransformerInfo globalAliasTransformerInfo("GlobalAliasTransformer");
  1328. GlobalAliasTransformer::GlobalAliasTransformer() : NewHqlTransformer(globalAliasTransformerInfo)
  1329. {
  1330. insideGlobal = false;
  1331. }
  1332. void GlobalAliasTransformer::analyseExpr(IHqlExpression * expr)
  1333. {
  1334. if (!containsAlias(expr))
  1335. return;
  1336. bool wasInsideGlobal = insideGlobal;
  1337. GlobalAliasInfo * extra = queryBodyExtra(expr);
  1338. extra->numUses++;
  1339. if (expr->getOperator() == no_alias)
  1340. {
  1341. if (expr->hasProperty(globalAtom))
  1342. {
  1343. // assertex(!containsActiveDataset(expr) || isInlineTrivialDataset(expr));
  1344. if (!insideGlobal)
  1345. extra->isOuter = true;
  1346. }
  1347. if (extra->numUses > 1)
  1348. return;
  1349. if (extra->isOuter)
  1350. insideGlobal = true;
  1351. }
  1352. else
  1353. {
  1354. //ugly, but we need to walk children more than once even if we've already been here.
  1355. //What is important is if visited >1 or occur globally, so can short circuit based on that condition.
  1356. //This currently links too many times because subsequent cse generation may common up multiple uses of the same item
  1357. //but it's not too bad.
  1358. //We could rerun this again if that was a major issue.
  1359. if (insideGlobal)
  1360. {
  1361. if (extra->numUses > 2)
  1362. return; // may need to visit children more than once so that alias is linked twice.
  1363. }
  1364. else
  1365. {
  1366. if (extra->isOuter && (extra->numUses > 2))
  1367. return;
  1368. extra->isOuter = true;
  1369. }
  1370. }
  1371. if (expr->getOperator() == no_attr_expr)
  1372. analyseChildren(expr);
  1373. else
  1374. NewHqlTransformer::analyseExpr(expr);
  1375. insideGlobal = wasInsideGlobal;
  1376. }
  1377. IHqlExpression * GlobalAliasTransformer::createTransformed(IHqlExpression * expr)
  1378. {
  1379. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  1380. if ((expr->getOperator() == no_alias))
  1381. {
  1382. GlobalAliasInfo * extra = queryBodyExtra(expr);
  1383. if (expr->hasProperty(globalAtom))
  1384. {
  1385. if (!extra->isOuter)
  1386. {
  1387. if (extra->numUses == 1)
  1388. return LINK(transformed->queryChild(0));
  1389. if (!expr->hasProperty(localAtom))
  1390. return appendLocalAttribute(transformed);
  1391. }
  1392. else if (expr->hasProperty(localAtom))
  1393. {
  1394. //Should never occur - but just about conceivable that some kind of constant folding
  1395. //might cause a surrounding global alias to be removed.
  1396. return removeLocalAttribute(transformed);
  1397. }
  1398. }
  1399. else
  1400. {
  1401. if ((extra->numUses == 1) && !expr->hasProperty(internalAtom))
  1402. return LINK(transformed->queryChild(0));
  1403. }
  1404. }
  1405. return transformed.getClear();
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. IHqlExpression * optimizeActivityAliasReferences(IHqlExpression * expr)
  1409. {
  1410. if (!containsAlias(expr))
  1411. return LINK(expr);
  1412. unsigned first = getFirstActivityArgument(expr);
  1413. unsigned last = first + getNumActivityArguments(expr);
  1414. bool foundAlias = false;
  1415. ForEachChild(i1, expr)
  1416. {
  1417. IHqlExpression * cur = expr->queryChild(i1);
  1418. if (((i1 < first) || (i1 >= last)) && containsAlias(cur))
  1419. {
  1420. foundAlias = true;
  1421. break;
  1422. }
  1423. }
  1424. if (!foundAlias)
  1425. return LINK(expr);
  1426. GlobalAliasTransformer transformer;
  1427. ForEachChild(i2, expr)
  1428. {
  1429. IHqlExpression * cur = expr->queryChild(i2);
  1430. if (((i2 < first) || (i2 >= last)) && containsAlias(cur))
  1431. transformer.analyse(cur, 0);
  1432. }
  1433. HqlExprArray args;
  1434. ForEachChild(i3, expr)
  1435. {
  1436. IHqlExpression * cur = expr->queryChild(i3);
  1437. if ((i3 < first) || (i3 >= last))
  1438. args.append(*transformer.transformRoot(cur));
  1439. else
  1440. args.append(*LINK(cur));
  1441. }
  1442. return cloneOrLink(expr, args);
  1443. }