hqlecl.cpp 25 KB

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