hqlcse.cpp 46 KB

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