hqlecl.cpp 25 KB

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