diff --git a/docs/running.md b/docs/running.md index ca7b8ce7b..bb46aae8e 100644 --- a/docs/running.md +++ b/docs/running.md @@ -92,7 +92,12 @@ __jit/hello.ts..o the object __jit/hello.ts..o.deps what it was compiled from ``` +The files that have to be compiled are compiled at the same time, one thread each: after the +program's own file, whose compile finds every module it reaches, all of them start together. + - `--jit-cache-dir=` keeps all the objects in one folder instead; +- `--jit-jobs=` compiles at most `n` files at the same time (default: the number of hardware + threads, at most 12; `--jit-jobs=1` compiles them one after another); - `--jit-cache=false` turns the cache off: everything is compiled into one module on every run. A program whose imports form a cycle is compiled into one object. Its modules can't be compiled diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMTypeConverterHelper.h b/tslang/include/TypeScript/LowerToLLVM/LLVMTypeConverterHelper.h index 6100e3997..661240554 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMTypeConverterHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMTypeConverterHelper.h @@ -24,7 +24,8 @@ namespace typescript static llvm::LLVMContext &getGlobalContext() { - static llvm::LLVMContext GlobalContext; + // one per thread: the JIT cache compiles several files at the same time, and an LLVMContext is not shared between threads + static thread_local llvm::LLVMContext GlobalContext; return GlobalContext; } diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h index 2b29fb627..8e483156f 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h @@ -405,7 +405,8 @@ class MLIRCustomMethods static bool isInternalObjectName (StringRef objectName) { static std::map o { {"Symbol", true}}; - return o[objectName.str()]; + auto it = o.find(objectName.str()); + return it != o.end() && it->second; } static bool isInternalFunctionName (CompileOptions &compileOptions, StringRef functionName) @@ -422,7 +423,8 @@ class MLIRCustomMethods {"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true }, {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuMin", true}, {"gpuMax", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuLocal", true}, {"gpuSync", true}, {"gpuSeed", true}, {"gpuScan", true}, {"gpuSort", true}, {"gpuTime", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true}, {".gpuBack", true} }; - return m[functionName.str()]; + auto it = m.find(functionName.str()); + return it != m.end() && it->second; } static bool isInternalFunctionNameNoBuiltin (StringRef functionName) @@ -432,7 +434,8 @@ class MLIRCustomMethods {"LoadLibraryPermanently", true}, { "SearchForAddressOfSymbol", true }, { "LoadReference", true }, { "ReferenceOf", true }, { "Deref", true }, { "Ref", true }, {"atomicrmw", true}, {"cmpxchg", true}, {"atomicload", true}, {"atomicstore", true}, {"fence", true}, {"inline_asm", true}, {"call_intrinsic", true}, {"linker_options", true}, {"gpuLaunch", true}, {"gpuReduce", true}, {"gpuMin", true}, {"gpuMax", true}, {"gpuBatch", true}, {"gpuThreadIndex", true}, {"gpuBlockIndex", true}, {"gpuBlockSize", true}, {"gpuBarrier", true}, {"gpuShared", true}, {"gpuLocal", true}, {"gpuSync", true}, {"gpuSeed", true}, {"gpuScan", true}, {"gpuSort", true}, {"gpuTime", true}, {"gpuArray", true}, {"gpuRead", true}, {"gpuWrite", true}, {"gpuFree", true}, {"gpuLaneIndex", true}, {"gpuWarpSize", true}, {"gpuShuffle", true}, {"gpuShuffleDown", true}, {"gpuShuffleUp", true}, {"gpuShuffleXor", true}, {"gpuBallot", true}, {"gpuAll", true}, {"gpuAny", true}, {".gpuBack", true} }; - return m[functionName.str()]; + auto it = m.find(functionName.str()); + return it != m.end() && it->second; } ValueOrLogicalResult callMethod(StringRef functionName, mlir::SmallVector typeArgs, ArrayRef operands, std::function castFn, const GenContext &genContext) diff --git a/tslang/include/TypeScript/VisitorAST.h b/tslang/include/TypeScript/VisitorAST.h index 00bc81c3b..1a4476475 100644 --- a/tslang/include/TypeScript/VisitorAST.h +++ b/tslang/include/TypeScript/VisitorAST.h @@ -19,9 +19,9 @@ class VisitorASTBase public: void visit(Node node) { + // No callback for arrays: forEachChild then walks a node's arrays where they are, where one + // made a NodeArray copy of every array it passed - the copies were the most of a walk ts::FuncT<> visitNode; - ts::ArrayFuncT<> visitArray; - visitNode = [&](ts::Node child) -> ts::Node { if (isFiltered(child)) { @@ -29,20 +29,11 @@ class VisitorASTBase } visitTree(child); - ts::forEachChild(child, visitNode, visitArray); - return undefined; - }; - - visitArray = [&](ts::NodeArray array) -> ts::Node { - for (auto node : array) - { - visitNode(node); - } - + ts::forEachChild(child, visitNode); return undefined; }; - auto result = ts::forEachChild(node, visitNode, visitArray); + ts::forEachChild(node, visitNode); } }; diff --git a/tslang/lib/TypeScript/MLIRGen.cpp b/tslang/lib/TypeScript/MLIRGen.cpp index 0c6189d7a..c863653fc 100644 --- a/tslang/lib/TypeScript/MLIRGen.cpp +++ b/tslang/lib/TypeScript/MLIRGen.cpp @@ -1,17 +1,41 @@ #include "MLIRGenImpl.h" +#include "llvm/ADT/DenseMap.h" + +#include +#include + // TODO: optimize of amount of calls to detect return types and if it is was calculated before then do not run it all // the time -static CompileOptions *compileOptionsPtr = nullptr; -CompileOptions& getCompileOptions() +// +// The options a module is compiled with, by its context: an op's verifier has only its context to go by. +// The JIT cache compiles several files at the same time, each in a context of its own and with +// options of its own, so one pointer for the process would give a file the options of another - +// options that may be gone by then. +static std::shared_mutex compileOptionsMutex; +static llvm::DenseMap compileOptionsByContext; +static std::atomic lastCompileOptions{nullptr}; + +CompileOptions &getCompileOptions(mlir::MLIRContext *context) { - return *compileOptionsPtr; + { + std::shared_lock lock(compileOptionsMutex); + auto it = compileOptionsByContext.find(context); + if (it != compileOptionsByContext.end()) + { + return *it->second; + } + } + + return *lastCompileOptions.load(); } -void setCompileOptions(CompileOptions &compileOptions) +void setCompileOptions(mlir::MLIRContext *context, CompileOptions &compileOptions) { - compileOptionsPtr = &compileOptions; + std::unique_lock lock(compileOptionsMutex); + compileOptionsByContext[context] = &compileOptions; + lastCompileOptions = &compileOptions; } SourceMgrDiagnosticHandlerEx::SourceMgrDiagnosticHandlerEx(llvm::SourceMgr &mgr, mlir::MLIRContext *ctx) : mlir::SourceMgrDiagnosticHandler(mgr, ctx) diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index 8b1546a46..4e70a82a8 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -2123,7 +2123,8 @@ namespace mlirgen return {mlir::success(), deferredType}; } - static auto count = 0; + // how deep the specializations go on this thread: the JIT cache compiles files on several + static thread_local auto count = 0; count++; if (count > 99) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index f311caab5..0ecc5348d 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -100,8 +100,8 @@ using llvm::Twine; using DITableScopeT = llvm::ScopedHashTableScope; // Defined in MLIRGen.cpp; also used by TypeScriptOps.cpp. -CompileOptions &getCompileOptions(); -void setCompileOptions(CompileOptions &compileOptions); +CompileOptions &getCompileOptions(mlir::MLIRContext *context); +void setCompileOptions(mlir::MLIRContext *context, CompileOptions &compileOptions); namespace typescript { @@ -178,7 +178,7 @@ class MLIRGenImpl overwriteLoc(mlir::UnknownLoc::get(builder.getContext())), generatedNodesAnchor(mlir::UnknownLoc::get(builder.getContext())) { - setCompileOptions(compileOptions); + setCompileOptions(builder.getContext(), compileOptions); rootNamespace = currentNamespace = std::make_shared(); @@ -4825,7 +4825,7 @@ class MLIRGenImpl {DLL_EXPORT, true }, }; - return funcAttrs[name]; + return funcAttrs.lookup(name); } bool isFuncAttr(StringRef name) @@ -4837,7 +4837,7 @@ class MLIRGenImpl {DLL_EXPORT, true }, }; - return funcAttrs[name]; + return funcAttrs.lookup(name); } void processFunctionAttributes(SmallVector &attrs, const GenContext &genContext) @@ -13254,12 +13254,12 @@ class MLIRGenImpl { ss << S("if (r instanceof TYPE_INST_RIGHT_ALIAS"); ss << index; - ss << S(") return ") << S("l ") << Scanner::tokenStrings[opCode] << S(" r;\n"); + ss << S(") return ") << S("l ") << lookupOrDefault(Scanner::tokenStrings, opCode) << S(" r;\n"); } ss << S("}\n"); } else - ss << S("return ") << S("l ") << Scanner::tokenStrings[opCode] << S(" r;\n"); + ss << S("return ") << S("l ") << lookupOrDefault(Scanner::tokenStrings, opCode) << S(" r;\n"); } }; @@ -13536,12 +13536,12 @@ class MLIRGenImpl if (typeOfName == "class") { ss << S("{ if (l instanceof TYPE_INST_ALIAS") << classInstances.size() << S(") return l ") - << Scanner::tokenStrings[opCode] << S(" r; }\n"); + << lookupOrDefault(Scanner::tokenStrings, opCode) << S(" r; }\n"); classInstances.push_back(member); } else { - ss << S("return l ") << Scanner::tokenStrings[opCode] << S(" r;\n"); + ss << S("return l ") << lookupOrDefault(Scanner::tokenStrings, opCode) << S(" r;\n"); } } diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index 78751ebd2..6fa931a8a 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -1074,8 +1074,7 @@ namespace mlirgen {"Record", true }, }; - auto type = embeddedTypes[name]; - return type; + return embeddedTypes.lookup(name); } bool MLIRGenImpl::isEmbededTypeWithNoBuiltins(mlir::StringRef name) @@ -1151,8 +1150,7 @@ namespace mlirgen //{"Array", true } }; - auto type = embeddedTypes[name]; - return type; + return embeddedTypes.lookup(name); } mlir::Type MLIRGenImpl::getEmbeddedType(mlir::StringRef name) diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index 946eb83e4..fb636b755 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -2,6 +2,8 @@ #include "MLIRGenImpl.h" +#include + namespace typescript { namespace mlirgen @@ -2654,6 +2656,39 @@ namespace mlirgen if (body == SyntaxKind::Block) { auto &statements = body.as()->statements; + + // The names the statements before the one at hand use - anywhere, and inside a function - gathered once + // as the loop moves on: walking every earlier statement again for each declaration took a body of n + // declarations n * n walks. + std::unordered_set namesBefore; + std::unordered_set namesInFunctionsBefore; + size_t namesGathered = 0; + auto gatherNamesBefore = [&](size_t index) { + for (; namesGathered < index; namesGathered++) + { + ts::VisitorAST names([&](ts::Node node) { + if (node == SyntaxKind::Identifier) + { + namesBefore.insert(node.as()->escapedText); + } + + if (node == SyntaxKind::ArrowFunction || node == SyntaxKind::FunctionExpression + || node == SyntaxKind::FunctionDeclaration || node == SyntaxKind::MethodDeclaration + || node == SyntaxKind::GetAccessor || node == SyntaxKind::SetAccessor) + { + ts::VisitorAST inFunction([&](ts::Node inner) { + if (inner == SyntaxKind::Identifier) + { + namesInFunctionsBefore.insert(inner.as()->escapedText); + } + }); + inFunction.visit(node); + } + }); + names.visit(statements[namesGathered]); + } + }; + for (auto [index, statement] : enumerate(statements)) { if (statement != SyntaxKind::VariableStatement) @@ -2696,20 +2731,8 @@ namespace mlirgen continue; } - auto name = declaration->name.as()->escapedText; - auto usedBefore = false; - for (size_t earlier = 0; earlier < index && !usedBefore; earlier++) - { - ts::VisitorAST names([&](ts::Node inner) { - if (inner == SyntaxKind::Identifier && inner.as()->escapedText == name) - { - usedBefore = true; - } - }); - names.visit(statements[earlier]); - } - - if (usedBefore) + gatherNamesBefore(index); + if (namesBefore.count(declaration->name.as()->escapedText)) { forwardReferenced.insert(MLIRHelper::getName(declaration->name)); } @@ -2731,27 +2754,11 @@ namespace mlirgen continue; } - auto name = declaration->name.as()->escapedText; - for (size_t earlier = 0; earlier < index && !readBefore; earlier++) + gatherNamesBefore(index); + if (namesInFunctionsBefore.count(declaration->name.as()->escapedText)) { - ts::VisitorAST functions([&](ts::Node node) { - if (readBefore - || !(node == SyntaxKind::ArrowFunction || node == SyntaxKind::FunctionExpression - || node == SyntaxKind::FunctionDeclaration || node == SyntaxKind::MethodDeclaration - || node == SyntaxKind::GetAccessor || node == SyntaxKind::SetAccessor)) - { - return; - } - - ts::VisitorAST names([&](ts::Node inner) { - if (inner == SyntaxKind::Identifier && inner.as()->escapedText == name) - { - readBefore = true; - } - }); - names.visit(node); - }); - functions.visit(statements[earlier]); + readBefore = true; + break; } } diff --git a/tslang/lib/TypeScript/TypeScriptOps.cpp b/tslang/lib/TypeScript/TypeScriptOps.cpp index a769eb0d2..e16404796 100644 --- a/tslang/lib/TypeScript/TypeScriptOps.cpp +++ b/tslang/lib/TypeScript/TypeScriptOps.cpp @@ -25,7 +25,7 @@ using namespace mlir; namespace mlir_ts = mlir::typescript; -CompileOptions& getCompileOptions(); +CompileOptions &getCompileOptions(mlir::MLIRContext *context); /// Default callback for IfOp builders. Inserts a yield without arguments. void mlir_ts::buildTerminatedBody(OpBuilder &builder, Location loc) @@ -630,7 +630,7 @@ LogicalResult mlir_ts::CastOp::verify() auto resFuncType = dyn_cast(resType); if (inFuncType && resFuncType) { - ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions(getContext())); auto result = mth.TestFunctionTypesMatchWithObjectMethods(getLoc(), inFuncType, resFuncType); if (::typescript::MatchResultType::Match != result.result) { @@ -669,7 +669,7 @@ LogicalResult mlir_ts::CastOp::verify() auto resUnionType = dyn_cast(resType); if (inUnionType || resUnionType) { - ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions(getContext())); auto cmpTypes = [&](mlir::Type t1, mlir::Type t2) { return mth.canCastFromTo(getLoc(), t1, t2); }; if (inUnionType && !resUnionType) @@ -680,7 +680,7 @@ LogicalResult mlir_ts::CastOp::verify() auto types = inUnionType.getTypes(); if (!std::all_of(types.begin(), types.end(), pred)) { - ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions(getContext())); mlir::Type baseType; if (!mth.isUnionTypeNeedsTag(getLoc(), inUnionType, baseType)/* && mth.canCastFromTo(baseType, resType)*/) { @@ -696,7 +696,7 @@ LogicalResult mlir_ts::CastOp::verify() if (!inUnionType && resUnionType) { - ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(getContext(), getCompileOptions(getContext())); mlir::Type baseType; if (!mth.isUnionTypeNeedsTag(getLoc(), resUnionType, baseType)/* && mth.canCastFromTo(baseType, resType)*/) { @@ -805,7 +805,7 @@ struct NormalizeCast : public OpRewritePattern auto inUnionType = dyn_cast(in.getType()); if (resUnionType && !inUnionType) { - ::typescript::MLIRTypeHelper mth(rewriter.getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(rewriter.getContext(), getCompileOptions(rewriter.getContext())); if (mth.isUnionTypeNeedsTag(location, resUnionType)) { // TODO: boxing, finish it, need to send TypeOf @@ -821,7 +821,7 @@ struct NormalizeCast : public OpRewritePattern // TODO: review it, if you still need it as we are should be using "safeCast" if (inUnionType && !resUnionType) { - ::typescript::MLIRTypeHelper mth(rewriter.getContext(), getCompileOptions()); + ::typescript::MLIRTypeHelper mth(rewriter.getContext(), getCompileOptions(rewriter.getContext())); if (mth.isUnionTypeNeedsTag(location, inUnionType)) { auto value = rewriter.create(loc, res.getType(), in); diff --git a/tslang/ts-new-parser/config.h b/tslang/ts-new-parser/config.h index 05f4bb79a..b853aeef9 100644 --- a/tslang/ts-new-parser/config.h +++ b/tslang/ts-new-parser/config.h @@ -33,4 +33,13 @@ using ostream = std::wostream; #define _E(x) data::DiagnosticMessage(x) +// What a constant table maps `key` to, or a value-initialized one: `table[key]` would insert the key +// into a table every thread shares (the JIT cache compiles files on several threads at once). +template +inline auto lookupOrDefault(const Map &table, const Key &key) -> typename Map::mapped_type +{ + auto it = table.find(key); + return it != table.end() ? it->second : typename Map::mapped_type{}; +} + #endif // CONFIG_H \ No newline at end of file diff --git a/tslang/ts-new-parser/dump.h b/tslang/ts-new-parser/dump.h index 3138b8ab3..843892e66 100644 --- a/tslang/ts-new-parser/dump.h +++ b/tslang/ts-new-parser/dump.h @@ -525,7 +525,7 @@ class Printer printText(beforeChild); } - out << Scanner::tokenStrings[withAppend]; + out << lookupOrDefault(Scanner::tokenStrings, withAppend); if (afterChild) { @@ -1009,8 +1009,8 @@ class Printer case SyntaxKind::TypeOperator: { auto typeOperatorNode = node.as(); - assert(Scanner::tokenStrings[typeOperatorNode->_operator].length() > 0); - out << Scanner::tokenStrings[typeOperatorNode->_operator]; + assert(lookupOrDefault(Scanner::tokenStrings, typeOperatorNode->_operator).length() > 0); + out << lookupOrDefault(Scanner::tokenStrings, typeOperatorNode->_operator); out << " "; forEachChildPrint(typeOperatorNode->type); break; @@ -1193,7 +1193,7 @@ class Printer out << " "; } - out << Scanner::tokenStrings[prefixUnaryExpression->_operator]; + out << lookupOrDefault(Scanner::tokenStrings, prefixUnaryExpression->_operator); prefixUnaryExpression->operand->parent = prefixUnaryExpression; forEachChildPrint(prefixUnaryExpression->operand); break; @@ -1216,7 +1216,7 @@ class Printer { auto postfixUnaryExpression = node.as(); forEachChildPrint(postfixUnaryExpression->operand); - out << Scanner::tokenStrings[postfixUnaryExpression->_operator]; + out << lookupOrDefault(Scanner::tokenStrings, postfixUnaryExpression->_operator); break; } case SyntaxKind::BinaryExpression: @@ -1246,8 +1246,8 @@ class Printer auto metaProperty = node.as(); if (metaProperty->keywordToken != SyntaxKind::Unknown) { - assert(Scanner::tokenStrings[metaProperty->keywordToken].length() > 0); - out << Scanner::tokenStrings[metaProperty->keywordToken] << "."; + assert(lookupOrDefault(Scanner::tokenStrings, metaProperty->keywordToken).length() > 0); + out << lookupOrDefault(Scanner::tokenStrings, metaProperty->keywordToken) << "."; } forEachChildPrint(metaProperty->name); @@ -2120,14 +2120,14 @@ class Printer case SyntaxKind::AssertsKeyword: case SyntaxKind::ExportKeyword: { - assert(Scanner::tokenStrings[node->_kind].length() > 0); - out << Scanner::tokenStrings[node->_kind]; + assert(lookupOrDefault(Scanner::tokenStrings, node->_kind).length() > 0); + out << lookupOrDefault(Scanner::tokenStrings, node->_kind); break; } case SyntaxKind::InKeyword: case SyntaxKind::InstanceOfKeyword: { - assert(Scanner::tokenStrings[node->_kind].length() > 0); - out << " " << Scanner::tokenStrings[node->_kind] << " "; + assert(lookupOrDefault(Scanner::tokenStrings, node->_kind).length() > 0); + out << " " << lookupOrDefault(Scanner::tokenStrings, node->_kind) << " "; break; } case SyntaxKind::ColonToken: @@ -2175,8 +2175,8 @@ class Printer case SyntaxKind::PercentToken: case SyntaxKind::PercentEqualsToken: { - assert(Scanner::tokenStrings[node->_kind].length() > 0); - out << " " << Scanner::tokenStrings[node->_kind] << " "; + assert(lookupOrDefault(Scanner::tokenStrings, node->_kind).length() > 0); + out << " " << lookupOrDefault(Scanner::tokenStrings, node->_kind) << " "; break; } case SyntaxKind::ExclamationToken: @@ -2184,8 +2184,8 @@ class Printer case SyntaxKind::QuestionToken: case SyntaxKind::QuestionDotToken: { - assert(Scanner::tokenStrings[node->_kind].length() > 0); - out << Scanner::tokenStrings[node->_kind]; + assert(lookupOrDefault(Scanner::tokenStrings, node->_kind).length() > 0); + out << lookupOrDefault(Scanner::tokenStrings, node->_kind); break; } case SyntaxKind::EmptyStatement: @@ -2193,7 +2193,7 @@ class Printer case SyntaxKind::EndOfFileToken: break; default: - out << "[MISSING " << Scanner::tokenToText[node->_kind] << "]"; + out << "[MISSING " << lookupOrDefault(Scanner::tokenToText, node->_kind) << "]"; break; } } diff --git a/tslang/ts-new-parser/file_helper.h b/tslang/ts-new-parser/file_helper.h index 6e74246e7..4c1a64446 100644 --- a/tslang/ts-new-parser/file_helper.h +++ b/tslang/ts-new-parser/file_helper.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -32,17 +33,183 @@ enum Encoding ENCODING_UTF8 }; -static auto ctow(const char *in) +// What std::wstring_convert does with malformed input: throws std::range_error. Where exceptions are off +// (-fno-exceptions, the Linux build) its throw came out of the C++ library into a frame that cannot unwind, +// and the program terminated: so it does here. +[[noreturn]] static void badConversion() { - std::wstring_convert> converter; - auto wide = converter.from_bytes(in); +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + throw std::range_error("bad conversion"); +#else + std::terminate(); +#endif +} + +// UTF-8 <-> UTF-16 (in wchar_t units, as std::codecvt_utf8_utf16 gives them), written out: +// a std::wstring_convert builds a std::locale, and every std::locale constructed takes the C++ +// runtime's one global lock. The compiler converts names and literals all the time, so threads +// compiling files at the same time (the JIT cache) spent most of their time waiting on that lock. +// Malformed input throws std::range_error, as std::wstring_convert does. +static std::wstring ctow(const char *in) +{ + std::wstring wide; + auto *s = reinterpret_cast(in); + while (*s) + { + char32_t cp; + int extra; + auto c = *s++; + if (c < 0x80) + { + cp = c; + extra = 0; + } + else if ((c & 0xE0) == 0xC0) + { + cp = c & 0x1F; + extra = 1; + } + else if ((c & 0xF0) == 0xE0) + { + cp = c & 0x0F; + extra = 2; + } + else if ((c & 0xF8) == 0xF0) + { + cp = c & 0x07; + extra = 3; + } + // the old five- and six-byte forms: MSVC's codecvt_utf8_utf16 reads them too + else if ((c & 0xFC) == 0xF8) + { + cp = c & 0x03; + extra = 4; + } + else if ((c & 0xFE) == 0xFC) + { + cp = c & 0x01; + extra = 5; + } + else + { + badConversion(); + } + + auto truncated = false; + for (auto i = 0; i < extra; i++) + { + auto next = *s; + if (!next && extra >= 3 && i == extra - 1) + { + // a form of four bytes or more cut before its last byte at the end: MSVC's + // codecvt_utf8_utf16 gives the high surrogate the bytes so far make, and stops there + truncated = true; + cp <<= 6; + break; + } + + if ((next & 0xC0) != 0x80) + { + badConversion(); + } + + cp = (cp << 6) | (next & 0x3F); + s++; + } + + // overlong forms are taken, as MSVC's codecvt_utf8_utf16 takes them + if (cp > 0x10FFFF) + { + badConversion(); + } + + if (truncated) + { + if (cp < 0x10000) + { + badConversion(); + } + + wide.push_back(static_cast(0xD800 + ((cp - 0x10000) >> 10))); + break; + } + + if (cp >= 0x10000) + { + cp -= 0x10000; + wide.push_back(static_cast(0xD800 + (cp >> 10))); + wide.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + else + { + wide.push_back(static_cast(cp)); + } + } + return wide; } -static auto wtoc(const wchar_t *in) +static std::string wtoc(const wchar_t *in) { - std::wstring_convert> converter; - auto chars = converter.to_bytes(in); + std::string chars; + auto put = [&](char32_t cp) { + if (cp < 0x80) + { + chars.push_back(static_cast(cp)); + } + else if (cp < 0x800) + { + chars.push_back(static_cast(0xC0 | (cp >> 6))); + chars.push_back(static_cast(0x80 | (cp & 0x3F))); + } + else if (cp < 0x10000) + { + chars.push_back(static_cast(0xE0 | (cp >> 12))); + chars.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + chars.push_back(static_cast(0x80 | (cp & 0x3F))); + } + else + { + chars.push_back(static_cast(0xF0 | (cp >> 18))); + chars.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + chars.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + chars.push_back(static_cast(0x80 | (cp & 0x3F))); + } + }; + + for (auto *s = in; *s; s++) + { + auto unit = static_cast(*s); + if (unit >= 0xD800 && unit <= 0xDBFF) + { + auto low = static_cast(s[1]); + auto cp = 0x10000 + ((unit - 0xD800) << 10); + if (!low) + { + // a high surrogate last: MSVC's codecvt_utf8_utf16 writes the lead byte of its + // code point and stops there; kept so that nothing compiles differently + chars.push_back(static_cast(0xF0 | (cp >> 18))); + break; + } + + if (low < 0xDC00 || low > 0xDFFF) + { + badConversion(); + } + + put(cp + (low - 0xDC00)); + s++; + } + else if (unit > 0x10FFFF) + { + badConversion(); + } + else + { + put(unit); + } + } + return chars; } diff --git a/tslang/ts-new-parser/parser.cpp b/tslang/ts-new-parser/parser.cpp index 411455eed..f438ff007 100644 --- a/tslang/ts-new-parser/parser.cpp +++ b/tslang/ts-new-parser/parser.cpp @@ -8911,7 +8911,7 @@ struct Parser {S("strict-null"), 10}}; /*JSDocTag*/ Node tag; - auto index = cases[key]; + auto index = lookupOrDefault(cases, key); switch (index) { case 1: { @@ -9085,7 +9085,7 @@ struct Parser auto name = match[1].str(); // Technically unsafe cast, but we do it so // they below check to make it safe typechecks std::transform(name.begin(), name.end(), name.begin(), [](auto c){ return std::tolower(c); }); - auto pragma = commentPragmas[name]; + auto pragma = lookupOrDefault(commentPragmas, name); if ((((int)pragma.kind) & (int)kind) != (int)kind) { return; } diff --git a/tslang/ts-new-parser/parser_jdoc.cpp b/tslang/ts-new-parser/parser_jdoc.cpp index 248faadc3..f9597d18e 100644 --- a/tslang/ts-new-parser/parser_jdoc.cpp +++ b/tslang/ts-new-parser/parser_jdoc.cpp @@ -213,7 +213,7 @@ struct ParseJSDocCommentClass {S("template"), 19}, {S("type"), 20}, {S("typedef"), 21}, {S("callback"), 22}, {S("see"), 23}}; /*JSDocTag*/Node tag; - auto index = m[tagName->escapedText]; + auto index = lookupOrDefault(m, tagName->escapedText); switch (index) { case 1: tag = parseAuthorTag(start, tagName, margin, indentText); diff --git a/tslang/ts-new-parser/parser_types.h b/tslang/ts-new-parser/parser_types.h index 7e12da5bf..2d33e03c5 100644 --- a/tslang/ts-new-parser/parser_types.h +++ b/tslang/ts-new-parser/parser_types.h @@ -92,7 +92,7 @@ template struct NodeArray : ReadonlyArray, Text } template - NodeArray(NodeArray other) + NodeArray(const NodeArray &other) : ReadonlyArray(other.begin(), other.end()), TextRange(other.pos, other._end), isUndefined(other.isUndefined), hasTrailingComma(other.hasTrailingComma), isMissingList(other.isMissingList), transformFlags(other.transformFlags) diff --git a/tslang/ts-new-parser/scanner.cpp b/tslang/ts-new-parser/scanner.cpp index 8109f9dd3..54246547d 100644 --- a/tslang/ts-new-parser/scanner.cpp +++ b/tslang/ts-new-parser/scanner.cpp @@ -1106,12 +1106,12 @@ std::map Scanner::tokenStrings = makeReverseMap(textToToken) auto Scanner::tokenToString(SyntaxKind t) -> string { - return tokenStrings[t]; + return lookupOrDefault(tokenStrings, t); } auto Scanner::syntaxKindString(SyntaxKind t) -> string { - return tokenToText[t]; + return lookupOrDefault(tokenToText, t); } /* @internal */ @@ -2360,7 +2360,7 @@ auto Scanner::getIdentifierToken() -> SyntaxKind auto ch = (CharacterCodes)tokenValue[0]; if (ch >= CharacterCodes::a && ch <= CharacterCodes::z) { - auto keyword = textToKeyword[tokenValue]; + auto keyword = lookupOrDefault(textToKeyword, tokenValue); if (keyword != SyntaxKind::Unknown) { return token = keyword; @@ -3209,7 +3209,7 @@ auto Scanner::reScanSlashToken() -> SyntaxKind return token; } -auto Scanner::appendIfCommentDirective(std::vector commentDirectives, string text, regex commentDirectiveRegEx, +auto Scanner::appendIfCommentDirective(std::vector commentDirectives, string text, const regex &commentDirectiveRegEx, pos_type lineStart) -> std::vector { auto type = getDirectiveFromComment(text, commentDirectiveRegEx); diff --git a/tslang/ts-new-parser/scanner.h b/tslang/ts-new-parser/scanner.h index 1becc3f20..b6707312b 100644 --- a/tslang/ts-new-parser/scanner.h +++ b/tslang/ts-new-parser/scanner.h @@ -95,6 +95,18 @@ static void debug(bool cond, string msg) assert(cond); } +// a literal message: the string overload made a std::wstring of it on every call, an allocation in +// computeLineOfPosition, which every source location the compiler makes goes through +static void debug(bool cond, const char_t *msg) +{ + if (!cond) + { + std::wcerr << msg; + } + + assert(cond); +} + static void error(string msg) { std::wcerr << msg; @@ -629,7 +641,7 @@ class Scanner auto reScanSlashToken() -> SyntaxKind; - auto appendIfCommentDirective(std::vector commentDirectives, string text, regex commentDirectiveRegEx, + auto appendIfCommentDirective(std::vector commentDirectives, string text, const regex &commentDirectiveRegEx, pos_type lineStart) -> std::vector; auto getDirectiveFromComment(string &text, const regex &commentDirectiveRegEx) -> CommentDirectiveType; diff --git a/tslang/ts-new-parser/utilities.h b/tslang/ts-new-parser/utilities.h index ac1f2f178..a84720c06 100644 --- a/tslang/ts-new-parser/utilities.h +++ b/tslang/ts-new-parser/utilities.h @@ -290,13 +290,13 @@ inline static auto isJSDocNode(Node node) -> boolean return node >= SyntaxKind::FirstJSDocNode && node <= SyntaxKind::LastJSDocNode; } -template static auto visitNode(FuncT cbNode, T node) -> R +template static auto visitNode(const FuncT &cbNode, T node) -> R { return node ? cbNode(node) : T{}; } template -static auto visitNodes(FuncT cbNode, ArrayFuncT cbNodes, NodeArray nodes) -> R +static auto visitNodes(const FuncT &cbNode, const ArrayFuncT &cbNodes, const NodeArray &nodes) -> R { if (!!nodes) { @@ -304,7 +304,7 @@ static auto visitNodes(FuncT cbNode, ArrayFuncT cbNodes, NodeArray cbNode, ArrayFuncT cbNodes, NodeArray static auto visitNodes(FuncT cbNode, ArrayFuncT cbNodes, NodeArray nodes) -> R +template static auto visitNodes(const FuncT &cbNode, const ArrayFuncT &cbNodes, const NodeArray &nodes) -> R { if (!!nodes) { @@ -352,7 +352,7 @@ template static auto visitNodes(FuncT * that they appear in the source code. The language service depends on this property to locate nodes by position. */ template -static auto forEachChild(T node, FuncT cbNode, ArrayFuncT cbNodes = nullptr) -> R +static auto forEachChild(T node, const FuncT &cbNode, const ArrayFuncT &cbNodes = nullptr) -> R { if (!node || node <= SyntaxKind::LastToken) { @@ -2589,7 +2589,7 @@ static auto getJSDocTypeAliasName(JSDocNamespaceBody fullName) -> Identifier return undefined; } -inline static auto regex_exec(string &text, regex regEx) -> boolean +inline static auto regex_exec(string &text, const regex ®Ex) -> boolean { auto words_begin = sregex_iterator(text.begin(), text.end(), regEx); auto words_end = sregex_iterator(); diff --git a/tslang/tslang/jitcache.cpp b/tslang/tslang/jitcache.cpp index 8f7623851..582db2118 100644 --- a/tslang/tslang/jitcache.cpp +++ b/tslang/tslang/jitcache.cpp @@ -40,6 +40,8 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" +#include "llvm/Support/ThreadPool.h" +#include "llvm/Support/Threading.h" #include "llvm/Support/Program.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/WithColor.h" @@ -52,6 +54,9 @@ #include "jitcache.h" #include +#include +#include +#include #define DEBUG_TYPE "tslang" @@ -67,6 +72,7 @@ extern cl::opt noStackPromotion; extern cl::opt stackPromotionMaxObject; extern cl::opt stackPromotionMaxFrame; extern cl::opt jitCacheDir; +extern cl::opt jitJobs; std::unique_ptr createMLIRContext(); int compileTypeScriptFileIntoMLIR(mlir::MLIRContext &, llvm::StringRef, llvm::SourceMgr &, mlir::OwningOpRef &, CompileOptions &); @@ -296,16 +302,128 @@ class JitUnitBuilder { } - int add(llvm::StringRef sourcePath, bool isMain) + // Every file the program needs, each loaded from the cache or compiled. The files are + // independent of one another - each is compiled from its sources alone, what it imports only + // declared - so they are compiled at the same time (--jit-jobs), each in a context of its own: + // a file's imports are known once it is done (its manifest; the program's lists every module + // it reaches), and each of them is put on the pool as it is found. Then the units are put in + // the order the loader needs, by the walk a sequential build made: what a file imports before + // the file, the program last. + int build(llvm::StringRef mainFile) { - auto path = canonicalPath(sourcePath); - if (!visited.insert(path).second) + auto mainPath = canonicalPath(mainFile); + unsigned jobs = jitJobs ? jitJobs.getValue() : std::min(llvm::hardware_concurrency().compute_thread_count(), 12u); + if (jobs < 1) { + jobs = 1; + } + + { + llvm::StdThreadPool pool(llvm::hardware_concurrency(jobs)); + this->pool = &pool; + schedule(mainPath, /*isMain=*/true); + pool.wait(); + this->pool = nullptr; + } + + if (failed) + { + return failure; + } + + llvm::StringSet<> placed; + place(mainPath, placed); + return 0; + } + + private: + struct Node + { + JitUnit unit; + std::vector imports; + }; + + void schedule(const std::string &path, bool isMain) + { + { + std::lock_guard lock(mutex); // loaded already, or on the way: an import cycle, or a module importing the program - return 0; + if (failed || !nodes.try_emplace(path).second) + { + return; + } + } + + pool->async([this, path, isMain] { + Node node; + int result; + // the pool keeps what a task throws in a future nobody reads: said here instead, or the + // file would be left without an object (a build without exceptions has none to catch) +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try + { + result = produce(path, isMain, node.unit, node.imports); + } + catch (const std::exception &e) + { + llvm::WithColor::error(llvm::errs(), "tslang") << "failed to compile '" << path << "', error: " << e.what() << "\n"; + result = -1; + } + catch (...) + { + llvm::WithColor::error(llvm::errs(), "tslang") << "failed to compile '" << path << "'\n"; + result = -1; + } +#else + result = produce(path, isMain, node.unit, node.imports); +#endif + + std::vector next; + { + std::lock_guard lock(mutex); + if (result) + { + if (!failed) + { + failed = true; + failure = result; + } + + return; + } + + next = node.imports; + nodes[path] = std::move(node); + } + + for (auto &import : next) + { + schedule(canonicalPath(import), /*isMain=*/false); + } + }); + } + + void place(const std::string &path, llvm::StringSet<> &placed) + { + if (!placed.insert(path).second) + { + return; } - if (!tm) + auto &node = nodes[path]; + // what it imports first: their objects are loaded, and their constructors run, before its own + for (auto &import : node.imports) + { + place(canonicalPath(import), placed); + } + + units.push_back(std::move(node.unit)); + } + + // the unit of one file, from the cache or compiled, and what it imports + int produce(const std::string &path, bool isMain, JitUnit &unit, std::vector &imports) + { + std::unique_ptr tm; { auto tmOrError = tmBuilder.createTargetMachine(); if (!tmOrError) @@ -319,7 +437,6 @@ class JitUnitBuilder tm = std::move(*tmOrError); } - JitUnit unit; unit.sourcePath = path; unit.isMain = isMain; @@ -329,7 +446,7 @@ class JitUnitBuilder auto onDisk = loadFromCache(objectPath, manifestPath, manifest, unit); if (!onDisk) { - if (auto result = compile(path, isMain, manifest, unit)) + if (auto result = compile(*tm, path, isMain, manifest, unit)) { return result; } @@ -345,21 +462,10 @@ class JitUnitBuilder unit.objectHash = manifest.objectHash; unit.initFunction = manifest.initFunction; unit.hasGCtorsMethod = manifest.hasGCtorsMethod; - - // what it imports first: their objects are loaded, and their constructors run, before its own - for (auto &import : manifest.imports) - { - if (auto result = add(import, /*isMain=*/false)) - { - return result; - } - } - - units.push_back(std::move(unit)); + imports = manifest.imports; return 0; } - private: // Everything that changes what a file compiles into, but the files themselves (the manifest's // deps) and the compiler (its `compiler`). std::string optionsKey(bool isMain) @@ -405,7 +511,7 @@ class JitUnitBuilder } auto name = llvm::sys::path::filename(path).str() + "." + hashString(path.str() + "\n" + optionsKey(isMain)); - name += tm->getTargetTriple().isOSBinFormatCOFF() ? ".obj" : ".o"; + name += tmBuilder.getTargetTriple().isOSBinFormatCOFF() ? ".obj" : ".o"; llvm::sys::path::append(objectPath, name); auto objectPathStr = objectPath.str().str(); @@ -415,10 +521,13 @@ class JitUnitBuilder // the hash of a file's content, or empty if it cannot be read; once per file and run std::string fileHash(llvm::StringRef path) { - auto it = fileHashes.find(path); - if (it != fileHashes.end()) { - return it->second; + std::lock_guard lock(hashMutex); + auto it = fileHashes.find(path); + if (it != fileHashes.end()) + { + return it->second; + } } std::string hash; @@ -428,6 +537,7 @@ class JitUnitBuilder hash = hashString((*fileOrErr)->getBuffer()); } + std::lock_guard lock(hashMutex); fileHashes[path] = hash; return hash; } @@ -498,7 +608,7 @@ class JitUnitBuilder return true; } - int compile(llvm::StringRef path, bool isMain, Manifest &manifest, JitUnit &unit) + int compile(llvm::TargetMachine &tm, llvm::StringRef path, bool isMain, Manifest &manifest, JitUnit &unit) { LLVM_DEBUG(llvm::dbgs() << "JIT cache: compiling " << path << "\n";); @@ -521,6 +631,13 @@ class JitUnitBuilder options.importCycle = false; module = nullptr; context = createMLIRContext(); + // The program's file compiles alone - what else there is to compile is known from its + // manifest - so its passes keep the context's threads. The modules are compiled at the + // same time, one thread each: no pool of threads of their own. + if (!isMain) + { + context->disableMultithreading(); + } sourceMgr = std::make_unique(); auto generationTiming = compileTiming().nest("MLIR generation"); return compileTypeScriptFileIntoMLIR(*context, path, *sourceMgr, module, options); @@ -619,11 +736,11 @@ class JitUnitBuilder // what an importer of a library would read: a module run here is in no library takeLibraryDeclarations(*llvmModule, ""); - llvmModule->setDataLayout(tm->createDataLayout()); - llvmModule->setTargetTriple(tm->getTargetTriple()); + llvmModule->setDataLayout(tm.createDataLayout()); + llvmModule->setTargetTriple(tm.getTargetTriple()); auto optimizationTiming = compileTiming().nest("LLVM optimization"); - auto optPipeline = getTransformer(enableOpt, optLevel, sizeLevel, options, tm.get()); + auto optPipeline = getTransformer(enableOpt, optLevel, sizeLevel, options, &tm); auto optimizationError = optPipeline(llvmModule.get()); optimizationTiming.stop(); if (auto err = std::move(optimizationError)) @@ -649,7 +766,7 @@ class JitUnitBuilder weakenComdatDefinitions(*llvmModule); manifest.initFunction = moveGlobalCtorsIntoFunction(*llvmModule, JIT_INIT_PREFIX + hashString(path)); - llvm::orc::SimpleCompiler compiler(*tm); + llvm::orc::SimpleCompiler compiler(tm); auto objectOrErr = compiler(*llvmModule); if (!objectOrErr) { @@ -666,11 +783,16 @@ class JitUnitBuilder const CompileOptions &compileOptions; llvm::orc::JITTargetMachineBuilder &tmBuilder; - std::unique_ptr tm; std::vector &units; std::string compilerId; - llvm::StringSet<> visited; llvm::StringMap fileHashes; + std::mutex hashMutex; + + llvm::ThreadPoolInterface *pool = nullptr; + std::mutex mutex; + std::map nodes; + bool failed = false; + int failure = 0; }; } // namespace @@ -693,5 +815,5 @@ int buildJitUnits(const char *argv0, llvm::StringRef mainFile, const CompileOpti llvm::orc::JITTargetMachineBuilder &tmBuilder, std::vector &units) { JitUnitBuilder builder(argv0, compileOptions, tmBuilder, units); - return builder.add(mainFile, /*isMain=*/true); + return builder.build(mainFile); } diff --git a/tslang/tslang/tslang.cpp b/tslang/tslang/tslang.cpp index f529c6675..72d3ea262 100644 --- a/tslang/tslang/tslang.cpp +++ b/tslang/tslang/tslang.cpp @@ -172,6 +172,8 @@ cl::opt jitCache{"jit-cache", cl::desc("--emit=jit: compile the program an cl::opt jitNative{"jit-native", cl::desc("--emit=jit on Windows: link the JIT cache's objects into a DLL with a PDB and load it with the system loader, so that WinDbg and Visual Studio can debug the program with its symbols and source (implies --di unless --opt is given; needs a linker and the JIT cache)"), cl::cat(TypeScriptCompilerCategory)}; cl::opt jitCacheDir{"jit-cache-dir", cl::desc("--emit=jit: the folder the JIT cache keeps its objects in (default: '__jit' beside each source file)"), cl::value_desc("folder"), cl::cat(TypeScriptCompilerCategory)}; +cl::opt jitJobs{"jit-jobs", cl::desc("--emit=jit: how many files of the program the JIT cache compiles at the same time (default: the number of hardware threads, at most 12)"), cl::value_desc("n"), cl::init(0), cl::cat(TypeScriptCompilerCategory)}; + cl::opt verbose{"verbose", cl::desc("Verbose output: print the linker's command line and what else is run"), cl::init(false), cl::cat(TypeScriptCompilerDebugCategory)}; // the linker's own failure message says "use -v to see invocation" (TSLANG_ISSUES 36) cl::alias verboseShort{"v", cl::desc("Alias for --verbose"), cl::aliasopt(verbose)};