hqlecl.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "build-config.h"
  14. #include "jliball.hpp"
  15. #include "jmisc.hpp"
  16. #include "jstream.hpp"
  17. #include "hql.hpp"
  18. #include "hqlexpr.hpp"
  19. #include "hqlecl.hpp"
  20. #include "hqlthql.hpp"
  21. #include "hqlcerrors.hpp"
  22. #include "hqlcatom.hpp"
  23. #include "hqllib.ipp"
  24. #include "hqlutil.hpp"
  25. #include "hqlhtcpp.ipp"
  26. #include "hqlwcpp.hpp"
  27. #include "hqllib.ipp"
  28. #include "hqlttcpp.ipp"
  29. #include "workunit.hpp"
  30. #include "thorplugin.hpp"
  31. #ifdef _DEBUG
  32. #define IS_DEBUG_BUILD true
  33. #else
  34. #define IS_DEBUG_BUILD false
  35. #endif
  36. #define MAIN_MODULE_TEMPLATE "thortpl.cpp"
  37. #define HEADER_TEMPLATE "thortpl.hpp"
  38. #define CHILD_MODULE_TEMPLATE "childtpl.cpp"
  39. #define PROTO_TEMPLATE "prototpl.cpp"
  40. class NullContextCallback : public CInterface, implements ICodegenContextCallback
  41. {
  42. IMPLEMENT_IINTERFACE
  43. virtual void noteCluster(const char *clusterName) {}
  44. virtual bool allowAccess(const char * category) { return true; }
  45. };
  46. class HqlDllGenerator : public CInterface, implements IHqlExprDllGenerator, implements IAbortRequestCallback
  47. {
  48. public:
  49. HqlDllGenerator(IErrorReceiver * _errs, const char * _wuname, const char * _targetdir, IWorkUnit * _wu, const char * _template_dir, ClusterType _targetClusterType, ICodegenContextCallback * _ctxCallback, bool _checkForLocalFileUploads, bool _okToAbort) :
  50. errs(_errs), wuname(_wuname), targetDir(_targetdir), wu(_wu), template_dir(_template_dir), targetClusterType(_targetClusterType), ctxCallback(_ctxCallback), checkForLocalFileUploads(_checkForLocalFileUploads), okToAbort(_okToAbort)
  51. {
  52. if (!ctxCallback)
  53. ctxCallback.setown(new NullContextCallback);
  54. noOutput = true;
  55. defaultMaxCompileThreads = 1;
  56. generateTarget = EclGenerateNone;
  57. code.setown(createCppInstance(wu, wuname));
  58. deleteGenerated = false;
  59. totalGeneratedSize = 0;
  60. }
  61. IMPLEMENT_IINTERFACE
  62. virtual void addLibrary(const char * name);
  63. virtual bool processQuery(OwnedHqlExpr & parsedQuery, EclGenerateTarget _generateTarget);
  64. virtual bool generateDll(ICppCompiler * compiler);
  65. virtual bool generateExe(ICppCompiler * compiler);
  66. virtual bool generatePackage(const char * packageName);
  67. virtual void setMaxCompileThreads(unsigned value) { defaultMaxCompileThreads = value; }
  68. virtual void addManifest(const char *filename) { code->addManifest(filename); }
  69. virtual void addManifestFromArchive(IPropertyTree *archive) { code->addManifestFromArchive(archive); }
  70. virtual void addWebServiceInfo(IPropertyTree *wsinfo){ code->addWebServiceInfo(wsinfo); }
  71. virtual double getECLcomplexity(IHqlExpression * exprs);
  72. virtual void setSaveGeneratedFiles(bool value) { deleteGenerated = !value; }
  73. protected:
  74. void addCppName(const char * filename);
  75. void addLibrariesToCompiler();
  76. void addWorkUnitAsResource();
  77. void calculateHash(IHqlExpression * expr);
  78. bool doCompile(ICppCompiler * compiler);
  79. void doExpand(HqlCppTranslator & translator);
  80. void expandCode(const char * templateName, const char * ext, IHqlCppInstance * code, bool multiFile, unsigned pass, CompilerType compiler);
  81. void flushResources();
  82. bool generateCode(HqlQueryContext & query);
  83. bool generateFullFieldUsageStatistics(HqlCppTranslator & translator, IHqlExpression * query);
  84. IPropertyTree * generateSingleFieldUsageStatistics(IHqlExpression * expr, const char * variety, const IPropertyTree * exclude);
  85. offset_t getGeneratedSize() const;
  86. void insertStandAloneCode();
  87. void setWuState(bool ok);
  88. inline bool abortRequested();
  89. protected:
  90. Linked<IErrorReceiver> errs;
  91. const char * wuname;
  92. StringAttr targetDir;
  93. Linked<IWorkUnit> wu;
  94. Owned<IHqlCppInstance> code;
  95. const char * template_dir;
  96. ClusterType targetClusterType;
  97. Linked<ICodegenContextCallback> ctxCallback;
  98. unsigned defaultMaxCompileThreads;
  99. StringArray sourceFiles;
  100. StringArray libraries;
  101. offset_t totalGeneratedSize;
  102. bool checkForLocalFileUploads;
  103. bool noOutput;
  104. EclGenerateTarget generateTarget;
  105. bool deleteGenerated;
  106. bool okToAbort;
  107. };
  108. //---------------------------------------------------------------------------
  109. static void processMetaCommands(HqlCppTranslator & translator, IWorkUnit * wu, HqlQueryContext & query, ICodegenContextCallback *ctxCallback);
  110. void HqlDllGenerator::addCppName(const char * filename)
  111. {
  112. if (wu)
  113. {
  114. Owned<IWUQuery> query = wu->updateQuery();
  115. associateLocalFile(query, FileTypeCpp, filename, pathTail(filename), 0);
  116. }
  117. }
  118. void HqlDllGenerator::addLibrary(const char * name)
  119. {
  120. libraries.append(name);
  121. }
  122. void HqlDllGenerator::addLibrariesToCompiler()
  123. {
  124. unsigned idx=0;
  125. loop
  126. {
  127. const char * lib = code->queryLibrary(idx);
  128. if (!lib)
  129. break;
  130. PrintLog("Adding library: %s", lib);
  131. addLibrary(lib);
  132. idx++;
  133. }
  134. }
  135. void HqlDllGenerator::expandCode(const char * templateName, const char * ext, IHqlCppInstance * code, bool multiFile, unsigned pass, CompilerType compiler)
  136. {
  137. StringBuffer fullname;
  138. addDirectoryPrefix(fullname, targetDir).append(wuname).append(ext);
  139. Owned<IFile> out = createIFile(fullname.str());
  140. Owned<ITemplateExpander> expander = createTemplateExpander(out, templateName, template_dir);
  141. if (!expander)
  142. throwError2(HQLERR_CouldNotOpenTemplateXatY, templateName, template_dir ? template_dir : ".");
  143. Owned<ISectionWriter> writer = createCppWriter(*code, compiler);
  144. Owned<IProperties> props = createProperties(true);
  145. if (multiFile)
  146. {
  147. props->setProp("multiFile", true);
  148. props->setProp("pass", pass);
  149. }
  150. StringBuffer headerName;
  151. headerName.append(wuname).append(".hpp");
  152. props->setProp("headerName", headerName.str());
  153. props->setProp("outputName", fullname.str());
  154. expander->generate(*writer, pass, props);
  155. totalGeneratedSize += out->size();
  156. if (!deleteGenerated)
  157. addCppName(fullname);
  158. }
  159. //---------------------------------------------------------------------------
  160. bool HqlDllGenerator::processQuery(OwnedHqlExpr & parsedQuery, EclGenerateTarget _generateTarget)
  161. {
  162. generateTarget = _generateTarget;
  163. assertex(wu->getHash());
  164. unsigned prevCount = errs->errCount();
  165. HqlQueryContext query;
  166. query.expr.setown(parsedQuery.getClear());
  167. bool ok = generateCode(query);
  168. code->flushHints();
  169. wu->commit();
  170. if (!ok)
  171. return false;
  172. if (errs->errCount() != prevCount)
  173. return false;
  174. switch (generateTarget)
  175. {
  176. case EclGenerateNone:
  177. case EclGenerateCpp:
  178. return true;
  179. }
  180. flushResources();
  181. addLibrariesToCompiler();
  182. // Free up memory before the c++ compile occurs
  183. code.clear();
  184. return true;
  185. }
  186. bool HqlDllGenerator::generateDll(ICppCompiler * compiler)
  187. {
  188. if (noOutput || !compiler)
  189. return true;
  190. bool ok = doCompile(compiler);
  191. setWuState(ok);
  192. return ok;
  193. }
  194. bool HqlDllGenerator::generateExe(ICppCompiler * compiler)
  195. {
  196. if (noOutput || !compiler)
  197. return true;
  198. compiler->setCreateExe(true);
  199. bool ok = doCompile(compiler);
  200. setWuState(ok);
  201. return ok;
  202. }
  203. bool HqlDllGenerator::generatePackage(const char * packageName)
  204. {
  205. return false;
  206. }
  207. static bool isSetMeta(IHqlExpression * expr)
  208. {
  209. switch (expr->getOperator())
  210. {
  211. case no_compound:
  212. case no_comma:
  213. return isSetMeta(expr->queryChild(0)) && isSetMeta(expr->queryChild(1));
  214. case no_setmeta:
  215. return true;
  216. default:
  217. return false;
  218. }
  219. }
  220. IPropertyTree * HqlDllGenerator::generateSingleFieldUsageStatistics(IHqlExpression * expr, const char * variety, const IPropertyTree * exclude)
  221. {
  222. //Generate each into a new workunit
  223. // Owned<IWorkUnit> localWu = createLocalWorkUnit();
  224. IWorkUnit * localWu = wu;
  225. //Generate the code into a new instance each time so it doesn't hang around eating memory
  226. Owned<IHqlCppInstance> localCode = createCppInstance(localWu, wuname);
  227. HqlQueryContext query;
  228. query.expr.set(expr);
  229. resetUniqueId();
  230. wu->resetBeforeGeneration();
  231. HqlCppTranslator translator(errs, wuname, localCode, targetClusterType, ctxCallback);
  232. try
  233. {
  234. translator.buildCpp(*localCode, query);
  235. return translator.gatherFieldUsage(variety, exclude);
  236. }
  237. catch (IException * e)
  238. {
  239. if (e->errorCode() != HQLERR_ErrorAlreadyReported)
  240. {
  241. unsigned errcode = e->errorCode() ? e->errorCode() : 1;
  242. StringBuffer s;
  243. errs->reportError(errcode, e->errorMessage(s).str(), NULL, 0, 0, 1);
  244. }
  245. e->Release();
  246. return NULL;
  247. }
  248. catch (RELEASE_CATCH_ALL)
  249. {
  250. errs->reportError(99, "Unknown error", NULL, 0, 0, 1);
  251. return NULL;
  252. }
  253. }
  254. bool HqlDllGenerator::generateFullFieldUsageStatistics(HqlCppTranslator & translator, IHqlExpression* query)
  255. {
  256. LinkedHqlExpr savedQuery = query;
  257. //Strip any #options etc. and check that the query consists of a single OUTPUT() action
  258. while ((savedQuery->getOperator() == no_compound) && isSetMeta(savedQuery->queryChild(0)))
  259. savedQuery.set(savedQuery->queryChild(1));
  260. if (savedQuery->getOperator() != no_output)
  261. throw MakeStringException(0, "#option('GenerateFullFieldUsage') requires the query to be a single OUTPUT()");
  262. Owned<IPropertyTree> allFields = createPTree("usage");
  263. IHqlExpression * dataset = savedQuery->queryChild(0);
  264. //First calculate which files are used if no fields are extracted from the output i.e. shared by all output fields
  265. //Use COUNT(dataset) as the query to test that
  266. OwnedHqlExpr countDataset = createValue(no_count, makeIntType(8, false), LINK(dataset));
  267. Owned<IPropertyTree> countFilesUsed = generateSingleFieldUsageStatistics(countDataset, "__shared__", NULL);
  268. if (countFilesUsed)
  269. allFields->addPropTree(countFilesUsed->queryName(), LINK(countFilesUsed));
  270. //Now project the output dataset down to a single field, and generate the file/field dependencies for each of those
  271. OwnedHqlExpr selSeq = createUniqueSelectorSequence();
  272. OwnedHqlExpr left = createSelector(no_left, dataset, selSeq);
  273. RecordSelectIterator iter(dataset->queryRecord(), left);
  274. ForEach(iter)
  275. {
  276. IHqlExpression * cur = iter.query();
  277. IHqlExpression * field = cur->queryChild(1);
  278. OwnedHqlExpr record = createRecord(field);
  279. OwnedHqlExpr self = getSelf(record);
  280. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), LINK(cur));
  281. OwnedHqlExpr transform = createValue(no_transform, makeTransformType(record->getType()), LINK(assign), NULL);
  282. HqlExprArray args;
  283. args.append(*LINK(dataset));
  284. args.append(*LINK(transform));
  285. args.append(*LINK(selSeq));
  286. OwnedHqlExpr project = createDataset(no_hqlproject,args);
  287. OwnedHqlExpr projectedOutput = replaceChildDataset(savedQuery, project, 0);
  288. StringBuffer variety;
  289. getExprIdentifier(variety, cur);
  290. //Generate each into a new property tree, and only include fields not shared by all other output fields.
  291. Owned<IPropertyTree> filesUsed = generateSingleFieldUsageStatistics(projectedOutput, variety.str(), countFilesUsed);
  292. if (filesUsed)
  293. allFields->addPropTree(filesUsed->queryName(), LINK(filesUsed));
  294. //Generate progress so far
  295. translator.writeFieldUsage(targetDir, allFields, NULL);
  296. }
  297. translator.writeFieldUsage(targetDir, allFields, NULL);
  298. return false;
  299. }
  300. bool HqlDllGenerator::generateCode(HqlQueryContext & query)
  301. {
  302. noOutput = true;
  303. {
  304. // ensure warnings/errors are available before we do the processing...
  305. wu->commit();
  306. cycle_t startCycles = get_cycles_now();
  307. HqlCppTranslator translator(errs, wuname, code, targetClusterType, ctxCallback);
  308. processMetaCommands(translator, wu, query, ctxCallback);
  309. if (wu->getDebugValueBool("generateFullFieldUsage", false))
  310. {
  311. //Ensure file information is generated. It only partially works with field information at the moment.
  312. //(The merging/difference logic would need to improve, but would be relatively simple if it was useful.)
  313. wu->setDebugValueInt("reportFileUsage", 1, true);
  314. return generateFullFieldUsageStatistics(translator, query.expr);
  315. }
  316. bool ok = false;
  317. try
  318. {
  319. if (!translator.buildCpp(*code, query))
  320. {
  321. wu->setState(WUStateCompleted);
  322. return true;
  323. }
  324. translator.generateStatistics(targetDir, NULL);
  325. translator.finalizeResources();
  326. translator.expandFunctions(true);
  327. }
  328. catch (IError * e)
  329. {
  330. if (e->errorCode() != HQLERR_ErrorAlreadyReported)
  331. {
  332. StringBuffer s;
  333. errs->reportError(e->errorCode(), e->errorMessage(s).str(), e->getFilename(), e->getLine(), e->getColumn(), e->getPosition());
  334. }
  335. e->Release();
  336. return false;
  337. }
  338. catch (IException * e)
  339. {
  340. if (e->errorCode() != HQLERR_ErrorAlreadyReported)
  341. {
  342. unsigned errcode = e->errorCode() ? e->errorCode() : 1;
  343. StringBuffer s;
  344. errs->reportError(errcode, e->errorMessage(s).str(), NULL, 0, 0, 1);
  345. }
  346. e->Release();
  347. return false;
  348. }
  349. catch (RELEASE_CATCH_ALL)
  350. {
  351. errs->reportError(99, "Unknown error", NULL, 0, 0, 1);
  352. return false;
  353. }
  354. if (generateTarget == EclGenerateExe)
  355. insertStandAloneCode();
  356. wu->commit();
  357. //Commit work unit so can view graphs etc. while compiling the C++
  358. if ((generateTarget == EclGenerateNone) || wu->getDebugValueBool("OnlyCheckQuery", false))
  359. {
  360. wu->setState(WUStateCompleted);
  361. return false;
  362. }
  363. if (wu->getDebugValueBool("saveEclTempFiles", false) || wu->getDebugValueBool("saveCppTempFiles", false))
  364. setSaveGeneratedFiles(true);
  365. doExpand(translator);
  366. if (wu->getDebugValueBool("addTimingToWorkunit", true))
  367. {
  368. unsigned __int64 elapsed = cycle_to_nanosec(get_cycles_now() - startCycles);
  369. updateWorkunitTimeStat(wu, SSTcompilestage, "compile:generate c++", StTimeElapsed, NULL, elapsed);
  370. }
  371. if (wu->getDebugValueBool("addMemoryToWorkunit", true))
  372. {
  373. memsize_t peakVm, peakResident;
  374. getPeakMemUsage(peakVm, peakResident);
  375. if (peakResident)
  376. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), SSTcompilestage, "compile", StSizePeakMemory, NULL, peakResident, 1, 0, StatsMergeReplace);
  377. }
  378. wu->commit();
  379. addWorkUnitAsResource();
  380. }
  381. noOutput = false;
  382. return true;
  383. }
  384. void HqlDllGenerator::addWorkUnitAsResource()
  385. {
  386. SCMStringBuffer wuXML;
  387. exportWorkUnitToXML(wu, wuXML, false, false);
  388. code->addCompressResource("WORKUNIT", wuXML.length(), wuXML.str(), NULL, 1000);
  389. }
  390. void HqlDllGenerator::insertStandAloneCode()
  391. {
  392. BuildCtx ctx(static_cast<HqlCppInstance &>(*code), goAtom);
  393. ctx.addQuotedCompound("int main(int argc, const char *argv[])");
  394. ctx.addQuotedLiteral("return start_query(argc, argv);\n");
  395. }
  396. void HqlDllGenerator::doExpand(HqlCppTranslator & translator)
  397. {
  398. cycle_t startCycles = get_cycles_now();
  399. unsigned numExtraFiles = translator.getNumExtraCppFiles();
  400. bool isMultiFile = translator.spanMultipleCppFiles() && (numExtraFiles != 0);
  401. expandCode(MAIN_MODULE_TEMPLATE, ".cpp", code, isMultiFile, 0, translator.queryOptions().targetCompiler);
  402. if (isMultiFile)
  403. {
  404. expandCode(HEADER_TEMPLATE, ".hpp", code, true, 0, translator.queryOptions().targetCompiler);
  405. for (unsigned i= 0; i < translator.getNumExtraCppFiles(); i++)
  406. {
  407. StringBuffer fullext;
  408. fullext.append("_").append(i+1).append(".cpp");
  409. expandCode(CHILD_MODULE_TEMPLATE, fullext, code, true, i+1, translator.queryOptions().targetCompiler);
  410. StringBuffer fullname;
  411. fullname.append(wuname).append("_").append(i+1);
  412. sourceFiles.append(fullname);
  413. }
  414. }
  415. cycle_t elapsedCycles = get_cycles_now() - startCycles;
  416. if (wu->getDebugValueBool("addTimingToWorkunit", true))
  417. updateWorkunitTimeStat(wu, SSTcompilestage, "compile:write c++", StTimeElapsed, NULL, cycle_to_nanosec(elapsedCycles));
  418. }
  419. bool HqlDllGenerator::abortRequested()
  420. {
  421. return (wu && wu->aborting());
  422. }
  423. bool HqlDllGenerator::doCompile(ICppCompiler * compiler)
  424. {
  425. cycle_t startCycles = get_cycles_now();
  426. ForEachItemIn(i, sourceFiles)
  427. compiler->addSourceFile(sourceFiles.item(i));
  428. unsigned maxThreads = wu->getDebugValueInt("maxCompileThreads", defaultMaxCompileThreads);
  429. compiler->setMaxCompileThreads(maxThreads);
  430. bool debug = wu->getDebugValueBool("debugQuery", false);
  431. bool debugLibrary = debug; // should be wu->getDebugValueBool("debugLibrary", IS_DEBUG_BUILD); change for 3.8
  432. compiler->setDebug(debug);
  433. compiler->setDebugLibrary(debugLibrary);
  434. if (!debug)
  435. {
  436. int optimizeLevel = wu->getDebugValueInt("optimizeLevel", targetClusterType == RoxieCluster ? 3 : -1);
  437. if (optimizeLevel != -1)
  438. compiler->setOptimizeLevel(optimizeLevel);
  439. }
  440. #ifdef __64BIT__
  441. // ARMFIX: Map all the uses of this property and make sure
  442. // they're not used to mean x86_64 (it shouldn't, though)
  443. bool target64bit = wu->getDebugValueBool("target64bit", true);
  444. #else
  445. bool target64bit = wu->getDebugValueBool("target64bit", false);
  446. #endif
  447. compiler->setTargetBitLength(target64bit ? 64 : 32);
  448. ForEachItemIn(idx, libraries)
  449. compiler->addLibrary(libraries.item(idx));
  450. StringBuffer options;
  451. StringBufferAdaptor linkOptionAdaptor(options);
  452. wu->getDebugValue("linkOptions", linkOptionAdaptor);
  453. compiler->addLinkOption(options.str());
  454. options.clear();
  455. StringBufferAdaptor optionAdaptor(options);
  456. wu->getDebugValue("compileOptions", optionAdaptor);
  457. compiler->addCompileOption(options.str());
  458. if (okToAbort)
  459. compiler->setAbortChecker(this);
  460. PrintLog("Compiling %s", wuname);
  461. bool ok = compiler->compile();
  462. if(ok)
  463. PrintLog("Compiled %s", wuname);
  464. else
  465. PrintLog("Failed to compile %s", wuname);
  466. bool reportCppWarnings = wu->getDebugValueBool("reportCppWarnings", false);
  467. IArrayOf<IError> errors;
  468. compiler->extractErrors(errors);
  469. ForEachItemIn(iErr, errors)
  470. {
  471. IError & cur = errors.item(iErr);
  472. if (isError(&cur) || reportCppWarnings)
  473. errs->report(&cur);
  474. }
  475. cycle_t elapsedCycles = get_cycles_now() - startCycles;
  476. //For eclcc the workunit has been written to the resource - so any further timings will not be preserved -> need to report differently
  477. queryActiveTimer()->addTiming("compile:compile c++", elapsedCycles);
  478. //Keep the files if there was a compile error.
  479. if (ok && deleteGenerated)
  480. {
  481. StringBuffer temp;
  482. remove(temp.clear().append(wuname).append(".cpp").str());
  483. remove(temp.clear().append(wuname).append(".hpp").str());
  484. ForEachItemIn(i, sourceFiles)
  485. {
  486. temp.clear().append(sourceFiles.item(i)).append(".cpp");
  487. remove(temp.str());
  488. }
  489. }
  490. return ok;
  491. }
  492. void HqlDllGenerator::flushResources()
  493. {
  494. StringBuffer resname(wuname);
  495. #ifdef _WIN32
  496. resname.append(".res");
  497. #else
  498. resname.append(".res.o");
  499. #endif
  500. if (code)
  501. code->flushResources(resname.str(), ctxCallback);
  502. }
  503. void HqlDllGenerator::setWuState(bool ok)
  504. {
  505. if(ok)
  506. {
  507. if(checkForLocalFileUploads && wu->requiresLocalFileUpload())
  508. wu->setState(WUStateUploadingFiles);
  509. else
  510. wu->setState(WUStateCompiled);
  511. }
  512. else
  513. wu->setState(WUStateFailed);
  514. }
  515. double HqlDllGenerator::getECLcomplexity(IHqlExpression * exprs)
  516. {
  517. Owned<IHqlCppInstance> code = createCppInstance(wu, NULL);
  518. HqlCppTranslator translator(errs, "temp", code, targetClusterType, NULL);
  519. HqlQueryContext query;
  520. query.expr.set(exprs);
  521. processMetaCommands(translator, wu, query, ctxCallback);
  522. return translator.getComplexity(*code, query.expr);
  523. }
  524. offset_t HqlDllGenerator::getGeneratedSize() const
  525. {
  526. return totalGeneratedSize;
  527. }
  528. extern HQLCPP_API double getECLcomplexity(IHqlExpression * exprs, IErrorReceiver * errs, IWorkUnit *wu, ClusterType targetClusterType)
  529. {
  530. HqlDllGenerator generator(errs, "unknown", NULL, wu, NULL, targetClusterType, NULL, false, false);
  531. return generator.getECLcomplexity(exprs);
  532. }
  533. extern HQLCPP_API IHqlExprDllGenerator * createDllGenerator(IErrorReceiver * errs, const char *wuname, const char * targetdir, IWorkUnit *wu, const char * template_dir, ClusterType targetClusterType, ICodegenContextCallback *ctxCallback, bool checkForLocalFileUploads, bool okToAbort)
  534. {
  535. return new HqlDllGenerator(errs, wuname, targetdir, wu, template_dir, targetClusterType, ctxCallback, checkForLocalFileUploads, okToAbort);
  536. }
  537. /*
  538. extern HQLCPP_API void addLibraryReference(IWorkUnit * wu, IHqlLibraryInfo * library, const char * lid)
  539. {
  540. StringBuffer libraryName;
  541. library->getName(libraryName);
  542. Owned<IWULibrary> entry = wu->updateLibraryByName(libraryName.str());
  543. entry->setMajorVersion(library->queryMajorVersion());
  544. entry->setMinorVersion(library->queryMinorVersion());
  545. entry->setCrc(library->queryInterfaceCrc());
  546. if (lid && *lid)
  547. entry->setLID(lid);
  548. }
  549. */
  550. extern HQLCPP_API ClusterType queryClusterType(IConstWorkUnit * wu, ClusterType prevType)
  551. {
  552. ClusterType targetClusterType = prevType;
  553. if (wu->getDebugValueBool("forceRoxie", false))
  554. targetClusterType = RoxieCluster;
  555. else if (prevType == NoCluster)
  556. targetClusterType = ThorLCRCluster;
  557. SCMStringBuffer targetText;
  558. wu->getDebugValue("targetClusterType", targetText);
  559. targetClusterType = getClusterType(targetText.s.str(), targetClusterType);
  560. if ((targetClusterType != RoxieCluster) && wu->getDebugValueBool("forceFakeThor", false))
  561. targetClusterType = HThorCluster;
  562. return targetClusterType;
  563. }
  564. static void processMetaCommands(HqlCppTranslator & translator, IWorkUnit * wu, HqlQueryContext & query, ICodegenContextCallback *ctxCallback)
  565. {
  566. NewThorStoredReplacer transformer(translator, wu, ctxCallback);
  567. translator.traceExpression("before process meta commands", query.expr);
  568. transformer.analyse(query.expr);
  569. if (transformer.needToTransform())
  570. query.expr.setown(transformer.transform(query.expr));
  571. }
  572. extern HQLCPP_API unsigned getLibraryCRC(IHqlExpression * library)
  573. {
  574. assertex(library->getOperator() == no_funcdef);
  575. return getExpressionCRC(library->queryChild(0));
  576. }
  577. void setWorkunitHash(IWorkUnit * wu, IHqlExpression * expr)
  578. {
  579. //Assuming builds come from different branches this will change the crc for each one.
  580. unsigned cacheCRC = crc32(BUILD_TAG, strlen(BUILD_TAG), ACTIVITY_INTERFACE_VERSION);
  581. cacheCRC += getExpressionCRC(expr);
  582. #ifdef _WIN32
  583. cacheCRC++; // make sure CRC is different in windows/linux
  584. #endif
  585. // make sure CRC is different for different host platform
  586. // shouldn't really matter if cross-compiling working properly,
  587. // but fairly harmless.
  588. #ifdef _ARCH_X86_
  589. cacheCRC += 1;
  590. #endif
  591. #ifdef _ARCH_X86_64_
  592. cacheCRC += 2;
  593. #endif
  594. // In theory, ARM and x86 workunits should be totally different, but...
  595. #ifdef _ARCH_ARM32_
  596. cacheCRC += 3;
  597. #endif
  598. #ifdef _ARCH_ARM64_
  599. cacheCRC += 4;
  600. #endif
  601. IExtendedWUInterface *ewu = queryExtendedWU(wu);
  602. cacheCRC = ewu->calculateHash(cacheCRC);
  603. wu->setHash(cacheCRC);
  604. }