Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/tools/clang/tools/clang-format
repos/DirectXShaderCompiler/tools/clang/tools/clang-format/fuzzer/CMakeLists.txt
set(LLVM_LINK_COMPONENTS support) add_clang_executable(clang-format-fuzzer EXCLUDE_FROM_ALL ClangFormatFuzzer.cpp ) target_link_libraries(clang-format-fuzzer ${CLANG_FORMAT_LIB_DEPS} LLVMFuzzer )
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcompilerobj.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcompilerobj.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Compiler. // // // /////////////////////////////////////////////////////////////////////////////// #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/HLSLMacroExpander.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/SemaHLSL.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/TimeProfiler.h" #include "llvm/Support/Timer.h" #include "llvm/Transforms/Utils/Cloning.h" #include "dxc/DXIL/DxilModule.h" #include "dxc/DXIL/DxilPDB.h" #include "dxc/DxcBindingTable/DxcBindingTable.h" #include "dxc/DxilContainer/DxilContainerAssembler.h" #include "dxc/DxilRootSignature/DxilRootSignature.h" #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h" #include "dxc/Support/Path.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcfilesystem.h" #include "dxc/dxcapi.internal.h" #include "dxcutil.h" #include "dxc/Support/DxcLangExtensionsHelper.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/dxcapi.impl.h" #include "dxc/Support/dxcapi.use.h" #include "dxc/Support/microcom.h" #ifdef _WIN32 #include "dxcetw.h" #endif #include "dxcompileradapter.h" #include "dxcshadersourceinfo.h" #include "dxcversion.inc" #include "dxillib.h" #include <algorithm> #include <cfloat> // SPIRV change starts #ifdef ENABLE_SPIRV_CODEGEN #include "clang/SPIRV/EmitSpirvAction.h" #include "clang/SPIRV/FeatureManager.h" #endif // SPIRV change ends #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO #include "clang/Basic/Version.h" #endif // SUPPORT_QUERY_GIT_COMMIT_INFO #define CP_UTF16 1200 using namespace llvm; using namespace clang; using namespace hlsl; using std::string; static bool ShouldBeCopiedIntoPDB(UINT32 FourCC) { switch (FourCC) { case hlsl::DFCC_ShaderDebugName: case hlsl::DFCC_ShaderHash: return true; } return false; } static HRESULT CreateContainerForPDB(IMalloc *pMalloc, IDxcBlob *pOldContainer, IDxcBlob *pDebugBlob, IDxcVersionInfo *pVersionInfo, const hlsl::DxilSourceInfo *pSourceInfo, AbstractMemoryStream *pReflectionStream, IDxcBlob **ppNewContainer) { // If the pContainer is not a valid container, give up. if (!hlsl::IsValidDxilContainer( (hlsl::DxilContainerHeader *)pOldContainer->GetBufferPointer(), pOldContainer->GetBufferSize())) return E_FAIL; hlsl::DxilContainerHeader *DxilHeader = (hlsl::DxilContainerHeader *)pOldContainer->GetBufferPointer(); hlsl::DxilProgramHeader *ProgramHeader = nullptr; std::unique_ptr<DxilContainerWriter> containerWriter( NewDxilContainerWriter(false)); std::unique_ptr<DxilPartWriter> pDxilVersionWriter( NewVersionWriter(pVersionInfo)); for (unsigned i = 0; i < DxilHeader->PartCount; i++) { hlsl::DxilPartHeader *PartHeader = GetDxilContainerPart(DxilHeader, i); if (ShouldBeCopiedIntoPDB(PartHeader->PartFourCC)) { UINT32 uSize = PartHeader->PartSize; const void *pPartData = PartHeader + 1; containerWriter->AddPart( PartHeader->PartFourCC, uSize, [pPartData, uSize](AbstractMemoryStream *pStream) { ULONG uBytesWritten = 0; IFR(pStream->Write(pPartData, uSize, &uBytesWritten)); return S_OK; }); } // Could use any of these. We're mostly after the header version and all // that. if (PartHeader->PartFourCC == hlsl::DFCC_DXIL || PartHeader->PartFourCC == hlsl::DFCC_ShaderDebugInfoDXIL) { ProgramHeader = (hlsl::DxilProgramHeader *)(PartHeader + 1); } } if (!ProgramHeader) return E_FAIL; if (pSourceInfo) { const UINT32 uPartSize = pSourceInfo->AlignedSizeInBytes; containerWriter->AddPart(hlsl::DFCC_ShaderSourceInfo, uPartSize, [pSourceInfo](IStream *pStream) { ULONG uBytesWritten = 0; pStream->Write(pSourceInfo, pSourceInfo->AlignedSizeInBytes, &uBytesWritten); return S_OK; }); } if (pReflectionStream) { const hlsl::DxilPartHeader *pReflectionPartHeader = (const hlsl::DxilPartHeader *)pReflectionStream->GetPtr(); containerWriter->AddPart( hlsl::DFCC_ShaderStatistics, pReflectionPartHeader->PartSize, [pReflectionPartHeader](IStream *pStream) { ULONG uBytesWritten = 0; pStream->Write(pReflectionPartHeader + 1, pReflectionPartHeader->PartSize, &uBytesWritten); return S_OK; }); } if (pVersionInfo) { containerWriter->AddPart( hlsl::DFCC_CompilerVersion, pDxilVersionWriter->size(), [&pDxilVersionWriter](AbstractMemoryStream *pStream) { pDxilVersionWriter->write(pStream); return S_OK; }); } if (pDebugBlob) { static auto AlignByDword = [](UINT32 uSize, UINT32 *pPaddingBytes) { UINT32 uRem = uSize % sizeof(UINT32); UINT32 uResult = (uSize / sizeof(UINT32) + (uRem ? 1 : 0)) * sizeof(UINT32); *pPaddingBytes = uRem ? (sizeof(UINT32) - uRem) : 0; return uResult; }; UINT32 uPaddingSize = 0; UINT32 uPartSize = AlignByDword(sizeof(hlsl::DxilProgramHeader) + pDebugBlob->GetBufferSize(), &uPaddingSize); containerWriter->AddPart( hlsl::DFCC_ShaderDebugInfoDXIL, uPartSize, [uPartSize, ProgramHeader, pDebugBlob, uPaddingSize](IStream *pStream) { hlsl::DxilProgramHeader Header = *ProgramHeader; Header.BitcodeHeader.BitcodeSize = pDebugBlob->GetBufferSize(); Header.BitcodeHeader.BitcodeOffset = sizeof(hlsl::DxilBitcodeHeader); Header.SizeInUint32 = uPartSize / sizeof(UINT32); ULONG uBytesWritten = 0; IFR(pStream->Write(&Header, sizeof(Header), &uBytesWritten)); IFR(pStream->Write(pDebugBlob->GetBufferPointer(), pDebugBlob->GetBufferSize(), &uBytesWritten)); if (uPaddingSize) { UINT32 uPadding = 0; assert(uPaddingSize <= sizeof(uPadding) && "Padding size calculation is wrong."); IFR(pStream->Write(&uPadding, uPaddingSize, &uBytesWritten)); } return S_OK; }); } CComPtr<hlsl::AbstractMemoryStream> pStrippedContainerStream; IFR(hlsl::CreateMemoryStream(pMalloc, &pStrippedContainerStream)); containerWriter->write(pStrippedContainerStream); IFR(pStrippedContainerStream.QueryInterface(ppNewContainer)); return S_OK; } #ifdef _WIN32 #pragma fenv_access(on) struct DefaultFPEnvScope { // _controlfp_s is non-standard and <cfenv>.feholdexceptions doesn't work on // windows...? unsigned int previousValue; DefaultFPEnvScope() { // _controlfp_s returns the value of the control word as it is after // the call, not before the call. This is the proper way to get the // previous value. errno_t error = _controlfp_s(&previousValue, 0, 0); IFT(error == 0 ? S_OK : E_FAIL); // No exceptions, preserve denormals & round to nearest. unsigned int newValue; error = _controlfp_s(&newValue, _MCW_EM | _DN_SAVE | _RC_NEAR, _MCW_EM | _MCW_DN | _MCW_RC); IFT(error == 0 ? S_OK : E_FAIL); } ~DefaultFPEnvScope() { _clearfp(); unsigned int newValue; errno_t error = _controlfp_s(&newValue, previousValue, _MCW_EM | _MCW_DN | _MCW_RC); // During cleanup we can't throw as we might already be handling another // one. DXASSERT_LOCALVAR(error, error == 0, "Failed to restore floating-point environment."); } }; #else // _WIN32 struct DefaultFPEnvScope { DefaultFPEnvScope() {} // Dummy ctor to avoid unused local warning }; #endif // _WIN32 class HLSLExtensionsCodegenHelperImpl : public HLSLExtensionsCodegenHelper { private: CompilerInstance &m_CI; DxcLangExtensionsHelper &m_langExtensionsHelper; std::string m_rootSigDefine; // The metadata format is a root node that has pointers to metadata // nodes for each define. The metatdata node for a define is a pair // of (name, value) metadata strings. // // Example: // !hlsl.semdefs = {!0, !1} // !0 = !{!"FOO", !"BAR"} // !1 = !{!"BOO", !"HOO"} void WriteSemanticDefines(llvm::Module *M, const ParsedSemanticDefineList &defines) { // Create all metadata nodes for each define. Each node is a (name, value) // pair. std::vector<MDNode *> mdNodes; const std::string enableStr("_ENABLE_"); const std::string disableStr("_DISABLE_"); const std::string selectStr("_SELECT_"); auto &optToggles = m_CI.getCodeGenOpts().HLSLOptimizationToggles.Toggles; auto &optSelects = m_CI.getCodeGenOpts().HLSLOptimizationToggles.Selects; const llvm::SmallVector<std::string, 2> &semDefPrefixes = m_langExtensionsHelper.GetSemanticDefines(); // Add semantic defines to mdNodes and also to codeGenOpts for (const ParsedSemanticDefine &define : defines) { MDString *name = MDString::get(M->getContext(), define.Name); MDString *value = MDString::get(M->getContext(), define.Value); mdNodes.push_back(MDNode::get(M->getContext(), {name, value})); // Find index for end of matching semantic define prefix size_t prefixPos = 0; for (auto prefix : semDefPrefixes) { if (IsMacroMatch(define.Name, prefix)) { prefixPos = prefix.length() - 1; break; } } // Add semantic defines to option flag equivalents // Convert define-style '_' into option-style '-' and lowercase everything if (!define.Name.compare(prefixPos, enableStr.length(), enableStr)) { std::string optName = define.Name.substr(prefixPos + enableStr.length()); std::replace(optName.begin(), optName.end(), '_', '-'); optToggles[StringRef(optName).lower()] = true; } else if (!define.Name.compare(prefixPos, disableStr.length(), disableStr)) { std::string optName = define.Name.substr(prefixPos + disableStr.length()); std::replace(optName.begin(), optName.end(), '_', '-'); optToggles[StringRef(optName).lower()] = false; } else if (!define.Name.compare(prefixPos, selectStr.length(), selectStr)) { std::string optName = define.Name.substr(prefixPos + selectStr.length()); std::replace(optName.begin(), optName.end(), '_', '-'); optSelects[StringRef(optName).lower()] = define.Value; } } // Add root node with pointers to all define metadata nodes. NamedMDNode *Root = M->getOrInsertNamedMetadata( m_langExtensionsHelper.GetSemanticDefineMetadataName()); for (MDNode *node : mdNodes) Root->addOperand(node); } SemanticDefineErrorList GetValidatedSemanticDefines(const ParsedSemanticDefineList &defines, ParsedSemanticDefineList &validated, SemanticDefineErrorList &errors) { for (const ParsedSemanticDefine &define : defines) { DxcLangExtensionsHelper::SemanticDefineValidationResult result = m_langExtensionsHelper.ValidateSemanticDefine(define.Name, define.Value); if (result.HasError()) errors.emplace_back(SemanticDefineError( define.Location, SemanticDefineError::Level::Error, result.Error)); if (result.HasWarning()) errors.emplace_back(SemanticDefineError( define.Location, SemanticDefineError::Level::Warning, result.Warning)); if (!result.HasError()) validated.emplace_back(define); } return errors; } public: HLSLExtensionsCodegenHelperImpl(CompilerInstance &CI, DxcLangExtensionsHelper &langExtensionsHelper, StringRef rootSigDefine) : m_CI(CI), m_langExtensionsHelper(langExtensionsHelper), m_rootSigDefine(rootSigDefine) {} // Write semantic defines as metadata in the module. virtual void WriteSemanticDefines(llvm::Module *M) override { // Grab the semantic defines seen by the parser. ParsedSemanticDefineList defines = CollectSemanticDefinesParsedByCompiler(m_CI, &m_langExtensionsHelper); // Nothing to do if we have no defines. SemanticDefineErrorList errors; if (!defines.size()) return; ParsedSemanticDefineList validated; GetValidatedSemanticDefines(defines, validated, errors); WriteSemanticDefines(M, validated); auto &Diags = m_CI.getDiagnostics(); for (const auto &error : errors) { clang::DiagnosticsEngine::Level level = clang::DiagnosticsEngine::Error; if (error.IsWarning()) level = clang::DiagnosticsEngine::Warning; unsigned DiagID = Diags.getCustomDiagID(level, "%0"); Diags.Report(clang::SourceLocation::getFromRawEncoding(error.Location()), DiagID) << error.Message(); } } // Update CodeGenOption based on HLSLOptimizationToggles. void UpdateCodeGenOptions(clang::CodeGenOptions &CGO) override { auto &CodeGenOpts = m_CI.getCodeGenOpts(); CGO.HLSLEnableLifetimeMarkers &= CodeGenOpts.HLSLOptimizationToggles.IsEnabled( hlsl::options::TOGGLE_LIFETIME_MARKERS); } virtual bool IsOptionEnabled(hlsl::options::Toggle toggle) override { return m_CI.getCodeGenOpts().HLSLOptimizationToggles.IsEnabled(toggle); } virtual std::string GetIntrinsicName(UINT opcode) override { return m_langExtensionsHelper.GetIntrinsicName(opcode); } virtual bool GetDxilOpcode(UINT opcode, OP::OpCode &dxilOpcode) override { UINT dop = static_cast<UINT>(OP::OpCode::NumOpCodes); if (m_langExtensionsHelper.GetDxilOpCode(opcode, dop)) { if (dop < static_cast<UINT>(OP::OpCode::NumOpCodes)) { dxilOpcode = static_cast<OP::OpCode>(dop); return true; } } return false; } virtual HLSLExtensionsCodegenHelper::CustomRootSignature::Status GetCustomRootSignature(CustomRootSignature *out) override { // Find macro definition in preprocessor. Preprocessor &pp = m_CI.getPreprocessor(); MacroInfo *macro = MacroExpander::FindMacroInfo(pp, m_rootSigDefine); if (!macro) return CustomRootSignature::NOT_FOUND; // Combine tokens into single string MacroExpander expander(pp, MacroExpander::STRIP_QUOTES); if (!expander.ExpandMacro(macro, &out->RootSignature)) return CustomRootSignature::NOT_FOUND; // Record source location of root signature macro. out->EncodedSourceLocation = macro->getDefinitionLoc().getRawEncoding(); return CustomRootSignature::FOUND; } }; static void CreateDefineStrings(const DxcDefine *pDefines, UINT defineCount, std::vector<std::string> &defines) { // Not very efficient but also not very important. for (UINT32 i = 0; i < defineCount; i++) { CW2A utf8Name(pDefines[i].Name); CW2A utf8Value(pDefines[i].Value); std::string val(utf8Name.m_psz); val += "="; val += (pDefines[i].Value) ? utf8Value.m_psz : "1"; defines.push_back(val); } } static HRESULT ErrorWithString(const std::string &error, REFIID riid, void **ppResult) { CComPtr<IDxcResult> pResult; IFT(DxcResult::Create( E_FAIL, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput(CP_UTF8, error.data(), error.size())}, &pResult)); IFT(pResult->QueryInterface(riid, ppResult)); return S_OK; } class DxcCompiler : public IDxcCompiler3, public IDxcLangExtensions3, public IDxcContainerEvent, public IDxcVersionInfo3, #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO public IDxcVersionInfo2 #else public IDxcVersionInfo #endif // SUPPORT_QUERY_GIT_COMMIT_INFO { private: DXC_MICROCOM_TM_REF_FIELDS() DxcLangExtensionsHelper m_langExtensionsHelper; CComPtr<IDxcContainerEventsHandler> m_pDxcContainerEventsHandler; DxcCompilerAdapter m_DxcCompilerAdapter; public: DxcCompiler(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_DxcCompilerAdapter(this, pMalloc) {} DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcCompiler) DXC_LANGEXTENSIONS_HELPER_IMPL(m_langExtensionsHelper) HRESULT STDMETHODCALLTYPE RegisterDxilContainerEventHandler( IDxcContainerEventsHandler *pHandler, UINT64 *pCookie) override { DXASSERT(m_pDxcContainerEventsHandler == nullptr, "else events handler is already registered"); *pCookie = 1; // Only one EventsHandler supported m_pDxcContainerEventsHandler = pHandler; return S_OK; }; HRESULT STDMETHODCALLTYPE UnRegisterDxilContainerEventHandler(UINT64 cookie) override { DXASSERT(m_pDxcContainerEventsHandler != nullptr, "else unregister should not have been called"); m_pDxcContainerEventsHandler.Release(); return S_OK; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { HRESULT hr = DoBasicQueryInterface<IDxcCompiler3, IDxcLangExtensions, IDxcLangExtensions2, IDxcLangExtensions3, IDxcContainerEvent, IDxcVersionInfo #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO , IDxcVersionInfo2 #endif // SUPPORT_QUERY_GIT_COMMIT_INFO , IDxcVersionInfo3>(this, iid, ppvObject); if (FAILED(hr)) { return DoBasicQueryInterface<IDxcCompiler, IDxcCompiler2>( &m_DxcCompilerAdapter, iid, ppvObject); } return hr; } // Compile a single entry point to the target shader model with debug // information. HRESULT STDMETHODCALLTYPE Compile( const DxcBuffer *pSource, // Source text to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) REFIID riid, LPVOID *ppResult // IDxcResult: status, buffer, and errors ) override { llvm::TimeTraceScope TimeScope("Compile", StringRef("")); if (pSource == nullptr || ppResult == nullptr || (argCount > 0 && pArguments == nullptr)) return E_INVALIDARG; if (!(IsEqualIID(riid, __uuidof(IDxcResult)) || IsEqualIID(riid, __uuidof(IDxcOperationResult)))) return E_INVALIDARG; *ppResult = nullptr; HRESULT hr = S_OK; CComPtr<IDxcBlobUtf8> utf8Source; CComPtr<AbstractMemoryStream> pOutputStream; CComPtr<IDxcOperationResult> pDxcOperationResult; bool bCompileStarted = false; bool bPreprocessStarted = false; DxilShaderHash ShaderHashContent; DxcThreadMalloc TM(m_pMalloc); try { DefaultFPEnvScope fpEnvScope; IFT(CreateMemoryStream(m_pMalloc, &pOutputStream)); // Parse command-line options into DxcOpts int argCountInt; IFT(UIntToInt(argCount, &argCountInt)); hlsl::options::MainArgs mainArgs(argCountInt, pArguments, 0); hlsl::options::DxcOpts opts; std::string warnings; raw_string_ostream w(warnings); { bool finished = false; CComPtr<AbstractMemoryStream> pOptionErrorStream; IFT(CreateMemoryStream(m_pMalloc, &pOptionErrorStream)); dxcutil::ReadOptsAndValidate(mainArgs, opts, pOptionErrorStream, &pDxcOperationResult, finished); if (finished) { IFT(pDxcOperationResult->QueryInterface(riid, ppResult)); hr = S_OK; goto Cleanup; } if (pOptionErrorStream->GetPtrSize() > 0) { w << StringRef((const char *)pOptionErrorStream->GetPtr(), (size_t)pOptionErrorStream->GetPtrSize()); } } bool isPreprocessing = !opts.Preprocess.empty(); if (isPreprocessing) { DxcEtw_DXCompilerPreprocess_Start(); bPreprocessStarted = true; } else { DxcEtw_DXCompilerCompile_Start(); bCompileStarted = true; } CComPtr<DxcResult> pResult = DxcResult::Alloc(m_pMalloc); IFT(pResult->SetEncoding(opts.DefaultTextCodePage)); DxcOutputObject primaryOutput; // Formerly API values. const char *pUtf8SourceName = opts.InputFile.empty() ? "hlsl.hlsl" : opts.InputFile.data(); CA2W pWideSourceName(pUtf8SourceName); const char *pUtf8EntryPoint = opts.EntryPoint.empty() ? "main" : opts.EntryPoint.data(); const char *pUtf8OutputName = isPreprocessing ? opts.Preprocess.data() : opts.OutputObject.empty() ? "" : opts.OutputObject.data(); CA2W pWideOutputName(isPreprocessing ? opts.Preprocess.data() : pUtf8OutputName); LPCWSTR pObjectName = (!isPreprocessing && opts.OutputObject.empty()) ? nullptr : pWideOutputName.m_psz; IFT(primaryOutput.SetName(pObjectName)); // Wrap source in blob CComPtr<IDxcBlobEncoding> pSourceEncoding; IFT(hlsl::DxcCreateBlob(pSource->Ptr, pSource->Size, true, false, pSource->Encoding != 0, pSource->Encoding, nullptr, &pSourceEncoding)); #ifdef ENABLE_SPIRV_CODEGEN // We want to embed the original source code in the final SPIR-V if // debug information is enabled. But the compiled source requires // pre-seeding with #line directives. We invoke Preprocess() here // first for such case. Then we invoke the compilation process over the // preprocessed source code. if (!isPreprocessing && opts.GenSPIRV && opts.DebugInfo && !opts.SpirvOptions.debugInfoVulkan) { // Convert source code encoding CComPtr<IDxcBlobUtf8> pOrigUtf8Source; IFC(hlsl::DxcGetBlobAsUtf8(pSourceEncoding, m_pMalloc, &pOrigUtf8Source)); opts.SpirvOptions.origSource.assign( static_cast<const char *>(pOrigUtf8Source->GetStringPointer()), pOrigUtf8Source->GetStringLength()); CComPtr<IDxcResult> pSrcCodeResult; std::vector<LPCWSTR> PreprocessArgs; PreprocessArgs.reserve(argCount + 1); PreprocessArgs.assign(pArguments, pArguments + argCount); PreprocessArgs.push_back(L"-P"); PreprocessArgs.push_back(L"-Fi"); PreprocessArgs.push_back(L"preprocessed.hlsl"); IFT(Compile(pSource, PreprocessArgs.data(), PreprocessArgs.size(), pIncludeHandler, IID_PPV_ARGS(&pSrcCodeResult))); HRESULT status; IFT(pSrcCodeResult->GetStatus(&status)); if (SUCCEEDED(status)) { pSourceEncoding.Release(); IFT(pSrcCodeResult->GetOutput( DXC_OUT_HLSL, IID_PPV_ARGS(&pSourceEncoding), nullptr)); } } #endif // ENABLE_SPIRV_CODEGEN // Convert source code encoding IFC(hlsl::DxcGetBlobAsUtf8(pSourceEncoding, m_pMalloc, &utf8Source, opts.DefaultTextCodePage)); CComPtr<IDxcBlob> pOutputBlob; dxcutil::DxcArgsFileSystem *msfPtr = dxcutil::CreateDxcArgsFileSystem( utf8Source, pWideSourceName.m_psz, pIncludeHandler, opts.DefaultTextCodePage); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); IFT(pOutputStream.QueryInterface(&pOutputBlob)); primaryOutput.kind = DXC_OUT_OBJECT; if (opts.AstDump || opts.OptDump || opts.DumpDependencies || opts.VerifyDiagnostics) primaryOutput.kind = DXC_OUT_TEXT; else if (isPreprocessing) primaryOutput.kind = DXC_OUT_HLSL; IFT(pResult->SetOutputName(DXC_OUT_REFLECTION, opts.OutputReflectionFile)); IFT(pResult->SetOutputName(DXC_OUT_SHADER_HASH, opts.OutputShaderHashFile)); IFT(pResult->SetOutputName(DXC_OUT_ERRORS, opts.OutputWarningsFile)); IFT(pResult->SetOutputName(DXC_OUT_ROOT_SIGNATURE, opts.OutputRootSigFile)); if (opts.DisplayIncludeProcess) msfPtr->EnableDisplayIncludeProcess(); IFT(msfPtr->RegisterOutputStream(L"output.bc", pOutputStream)); IFT(msfPtr->CreateStdStreams(m_pMalloc)); StringRef Data(utf8Source->GetStringPointer(), utf8Source->GetStringLength()); // Not very efficient but also not very important. std::vector<std::string> defines; CreateDefineStrings(opts.Defines.data(), opts.Defines.size(), defines); // Setup a compiler instance. raw_stream_ostream outStream(pOutputStream.p); llvm::LLVMContext llvmContext; // LLVMContext should outlive CompilerInstance std::unique_ptr<llvm::Module> debugModule; CComPtr<AbstractMemoryStream> pReflectionStream; CompilerInstance compiler; std::unique_ptr<TextDiagnosticPrinter> diagPrinter = llvm::make_unique<TextDiagnosticPrinter>( w, &compiler.getDiagnosticOpts()); SetupCompilerForCompile(compiler, &m_langExtensionsHelper, pUtf8SourceName, diagPrinter.get(), defines, opts, pArguments, argCount); msfPtr->SetupForCompilerInstance(compiler); // The clang entry point (cc1_main) would now create a compiler invocation // from arguments, but depending on the Preprocess option, we either // compile to LLVM bitcode and then package that into a DXBC blob, or // preprocess to HLSL text. // // With the compiler invocation built from command line arguments, the // next step is to call ExecuteCompilerInvocation, which creates a // FrontendAction* of EmitBCAction, which is a CodeGenAction, which is an // ASTFrontendAction. That sets up a BackendConsumer as the ASTConsumer. compiler.getFrontendOpts().OutputFile = "output.bc"; compiler.WriteDefaultOutputDirectly = true; compiler.setOutStream(&outStream); unsigned rootSigMajor = 0; unsigned rootSigMinor = 0; // NOTE: this calls the validation component from dxil.dll; the built-in // validator can be used as a fallback. bool produceFullContainer = false; bool needsValidation = false; bool validateRootSigContainer = false; if (isPreprocessing) { // These settings are back-compatible with fxc. clang::PreprocessorOutputOptions &PPOutOpts = compiler.getPreprocessorOutputOpts(); PPOutOpts.ShowCPP = 1; // Print normal preprocessed output. PPOutOpts.ShowComments = 0; // Show comments. PPOutOpts.ShowLineMarkers = 1; // Show \#line markers. PPOutOpts.UseLineDirectives = 1; // Use \#line instead of GCC-style \# N. PPOutOpts.ShowMacroComments = 0; // Show comments, even in macros. PPOutOpts.ShowMacros = 0; // Print macro definitions. PPOutOpts.RewriteIncludes = 0; // Preprocess include directives only. FrontendInputFile file(pUtf8SourceName, IK_HLSL); clang::PrintPreprocessedAction action; if (action.BeginSourceFile(compiler, file)) { action.Execute(); action.EndSourceFile(); } outStream.flush(); } else { compiler.getLangOpts().HLSLEntryFunction = compiler.getCodeGenOpts().HLSLEntryFunction = pUtf8EntryPoint; // Parse and apply if (opts.BindingTableDefine.size()) { // Just pas the define for now because preprocessor is not available // yet. struct BindingTableParserImpl : public CodeGenOptions::BindingTableParserType { CompilerInstance &compiler; std::string define; BindingTableParserImpl(CompilerInstance &compiler, StringRef define) : compiler(compiler), define(define.str()) {} bool Parse(llvm::raw_ostream &os, hlsl::DxcBindingTable *outBindingTable) override { Preprocessor &pp = compiler.getPreprocessor(); MacroInfo *macro = MacroExpander::FindMacroInfo(pp, define); if (!macro) { os << Twine("Binding table define'") + define + "' not found."; os.flush(); return false; } std::string bindingTableStr; // Combine tokens into single string MacroExpander expander(pp, MacroExpander::STRIP_QUOTES); if (!expander.ExpandMacro(macro, &bindingTableStr)) { os << Twine("Binding table define'") + define + "' failed to expand."; os.flush(); return false; } return hlsl::ParseBindingTable(define, StringRef(bindingTableStr), os, outBindingTable); } }; compiler.getCodeGenOpts().BindingTableParser.reset( new BindingTableParserImpl(compiler, opts.BindingTableDefine)); } else if (opts.ImportBindingTable.size()) { hlsl::options::StringRefWide wstrRef(opts.ImportBindingTable); CComPtr<IDxcBlob> pBlob; std::string error; llvm::raw_string_ostream os(error); if (!pIncludeHandler) { os << Twine("Binding table binding file '") + opts.ImportBindingTable + "' specified, but no include handler was given."; os.flush(); return ErrorWithString(error, riid, ppResult); } else if (SUCCEEDED(pIncludeHandler->LoadSource(wstrRef, &pBlob))) { bool succ = hlsl::ParseBindingTable( opts.ImportBindingTable, StringRef((const char *)pBlob->GetBufferPointer(), pBlob->GetBufferSize()), os, &compiler.getCodeGenOpts().HLSLBindingTable); if (!succ) { os.flush(); return ErrorWithString(error, riid, ppResult); } } else { os << Twine("Could not load binding table file '") + opts.ImportBindingTable + "'."; os.flush(); return ErrorWithString(error, riid, ppResult); } } if (compiler.getCodeGenOpts().HLSLProfile == "rootsig_1_1") { rootSigMajor = 1; rootSigMinor = 1; } else if (compiler.getCodeGenOpts().HLSLProfile == "rootsig_1_0") { rootSigMajor = 1; rootSigMinor = 0; } compiler.getLangOpts().IsHLSLLibrary = opts.IsLibraryProfile(); // Clear entry function if library target if (compiler.getLangOpts().IsHLSLLibrary) compiler.getLangOpts().HLSLEntryFunction = compiler.getCodeGenOpts().HLSLEntryFunction = ""; // NOTE: this calls the validation component from dxil.dll; the built-in // validator can be used as a fallback. produceFullContainer = !opts.CodeGenHighLevel && !opts.AstDump && !opts.OptDump && rootSigMajor == 0 && !opts.DumpDependencies && !opts.VerifyDiagnostics; needsValidation = produceFullContainer && !opts.DisableValidation; if (compiler.getCodeGenOpts().HLSLProfile == "lib_6_x") { // Currently do not support stripping reflection from offline linking // target. opts.KeepReflectionInDxil = true; } if (opts.ValVerMajor != UINT_MAX) { // user-specified validator version override compiler.getCodeGenOpts().HLSLValidatorMajorVer = opts.ValVerMajor; compiler.getCodeGenOpts().HLSLValidatorMinorVer = opts.ValVerMinor; } else { // Version from dxil.dll, or internal validator if unavailable dxcutil::GetValidatorVersion( &compiler.getCodeGenOpts().HLSLValidatorMajorVer, &compiler.getCodeGenOpts().HLSLValidatorMinorVer, opts.SelectValidator); } // Root signature-only container validation is only supported on 1.5 and // above. validateRootSigContainer = DXIL::CompareVersions( compiler.getCodeGenOpts().HLSLValidatorMajorVer, compiler.getCodeGenOpts().HLSLValidatorMinorVer, 1, 5) >= 0; } compiler.getTarget().adjust(compiler.getLangOpts()); if (opts.AstDump) { clang::ASTDumpAction dumpAction; // Consider - ASTDumpFilter, ASTDumpLookups compiler.getFrontendOpts().ASTDumpDecls = true; FrontendInputFile file(pUtf8SourceName, IK_HLSL); dumpAction.BeginSourceFile(compiler, file); dumpAction.Execute(); dumpAction.EndSourceFile(); outStream.flush(); } else if (opts.DumpDependencies) { auto dependencyCollector = std::make_shared<DependencyCollector>(); compiler.addDependencyCollector(dependencyCollector); compiler.createPreprocessor(clang::TranslationUnitKind::TU_Complete); clang::PreprocessOnlyAction preprocessAction; FrontendInputFile file(pUtf8SourceName, IK_HLSL); preprocessAction.BeginSourceFile(compiler, file); preprocessAction.Execute(); preprocessAction.EndSourceFile(); outStream << (opts.OutputObject.empty() ? opts.InputFile : opts.OutputObject); bool firstDependency = true; for (auto &dependency : dependencyCollector->getDependencies()) { if (firstDependency) { outStream << ": " << dependency; firstDependency = false; continue; } outStream << " \\\n " << dependency; } outStream << "\n"; outStream.flush(); } else if (opts.OptDump) { EmitOptDumpAction action(&llvmContext); FrontendInputFile file(pUtf8SourceName, IK_HLSL); action.BeginSourceFile(compiler, file); action.Execute(); action.EndSourceFile(); outStream.flush(); } else if (rootSigMajor) { HLSLRootSignatureAction action( compiler.getCodeGenOpts().HLSLEntryFunction, rootSigMajor, rootSigMinor); FrontendInputFile file(pUtf8SourceName, IK_HLSL); action.BeginSourceFile(compiler, file); action.Execute(); action.EndSourceFile(); outStream.flush(); // Don't do work to put in a container if an error has occurred bool compileOK = !compiler.getDiagnostics().hasErrorOccurred(); if (compileOK) { auto rootSigHandle = action.takeRootSigHandle(); CComPtr<AbstractMemoryStream> pContainerStream; IFT(CreateMemoryStream(m_pMalloc, &pContainerStream)); SerializeDxilContainerForRootSignature(rootSigHandle.get(), pContainerStream); pOutputBlob.Release(); IFT(pContainerStream.QueryInterface(&pOutputBlob)); if (validateRootSigContainer && !opts.DisableValidation) { CComPtr<IDxcBlobEncoding> pValErrors; // Validation failure communicated through diagnostic error dxcutil::ValidateRootSignatureInContainer( pOutputBlob, &compiler.getDiagnostics(), opts.SelectValidator); } } } else if (opts.VerifyDiagnostics) { SyntaxOnlyAction action; FrontendInputFile file(pUtf8SourceName, IK_HLSL); if (action.BeginSourceFile(compiler, file)) { action.Execute(); action.EndSourceFile(); } } // SPIRV change starts #ifdef ENABLE_SPIRV_CODEGEN else if (!isPreprocessing && opts.GenSPIRV) { // Since SpirvOptions is passed to the SPIR-V CodeGen as a whole // structure, we need to copy a few non-spirv-specific options into the // structure. opts.SpirvOptions.enable16BitTypes = opts.Enable16BitTypes; opts.SpirvOptions.codeGenHighLevel = opts.CodeGenHighLevel; opts.SpirvOptions.defaultRowMajor = opts.DefaultRowMajor; opts.SpirvOptions.disableValidation = opts.DisableValidation; opts.SpirvOptions.IEEEStrict = opts.IEEEStrict; // Save a string representation of command line options and // input file name. if (opts.DebugInfo) { opts.SpirvOptions.inputFile = opts.InputFile; for (auto opt : mainArgs.getArrayRef()) { if (opts.InputFile.compare(opt) != 0) { opts.SpirvOptions.clOptions += " " + std::string(opt); } } } compiler.getCodeGenOpts().SpirvOptions = opts.SpirvOptions; clang::EmitSpirvAction action; FrontendInputFile file(pUtf8SourceName, IK_HLSL); action.BeginSourceFile(compiler, file); action.Execute(); action.EndSourceFile(); outStream.flush(); } #endif // SPIRV change ends else if (!isPreprocessing) { EmitBCAction action(&llvmContext); FrontendInputFile file(pUtf8SourceName, IK_HLSL); bool compileOK; if (action.BeginSourceFile(compiler, file)) { action.Execute(); action.EndSourceFile(); compileOK = !compiler.getDiagnostics().hasErrorOccurred(); } else { compileOK = false; } outStream.flush(); SerializeDxilFlags SerializeFlags = hlsl::options::ComputeSerializeDxilFlags(opts); CComPtr<IDxcBlob> pRootSignatureBlob = nullptr; CComPtr<IDxcBlob> pPrivateBlob = nullptr; if (!opts.RootSignatureSource.empty()) { hlsl::options::StringRefWide wstrRef(opts.RootSignatureSource); std::string error; llvm::raw_string_ostream os(error); if (!pIncludeHandler) { os << Twine("Root Signature file '") + opts.RootSignatureSource + "' specified, but no include handler was given."; os.flush(); return ErrorWithString(error, riid, ppResult); } else if (SUCCEEDED(pIncludeHandler->LoadSource( wstrRef, &pRootSignatureBlob))) { } else { os << Twine("Could not load root signature file '") + opts.RootSignatureSource + "'."; os.flush(); return ErrorWithString(error, riid, ppResult); } } if (!opts.PrivateSource.empty()) { hlsl::options::StringRefWide wstrRef(opts.PrivateSource); std::string error; llvm::raw_string_ostream os(error); if (!pIncludeHandler) { os << Twine("Private file '") + opts.PrivateSource + "' specified, but no include handler was given."; os.flush(); return ErrorWithString(error, riid, ppResult); } else if (SUCCEEDED( pIncludeHandler->LoadSource(wstrRef, &pPrivateBlob))) { } else { os << Twine("Could not load root signature file '") + opts.PrivateSource + "'."; os.flush(); return ErrorWithString(error, riid, ppResult); } } // Don't do work to put in a container if an error has occurred // Do not create a container when there is only a a high-level // representation in the module. if (compileOK && !opts.CodeGenHighLevel) { HRESULT valHR = S_OK; CComPtr<AbstractMemoryStream> pRootSigStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pReflectionStream)); IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pRootSigStream)); std::unique_ptr<llvm::Module> serializeModule(action.takeModule()); // Clone and save the copy. if (opts.GenerateFullDebugInfo()) { debugModule.reset(llvm::CloneModule(serializeModule.get())); } dxcutil::AssembleInputs inputs( std::move(serializeModule), pOutputBlob, m_pMalloc, SerializeFlags, pOutputStream, 0, opts.GetPDBName(), &compiler.getDiagnostics(), &ShaderHashContent, pReflectionStream, pRootSigStream, pRootSignatureBlob, pPrivateBlob, opts.SelectValidator); inputs.pVersionInfo = static_cast<IDxcVersionInfo *>(this); if (needsValidation) { valHR = dxcutil::ValidateAndAssembleToContainer(inputs); } else { dxcutil::AssembleToContainer(inputs); } // Callback after valid DXIL is produced if (SUCCEEDED(valHR)) { CComPtr<IDxcBlob> pTargetBlob; if (m_pDxcContainerEventsHandler != nullptr) { HRESULT hr = m_pDxcContainerEventsHandler->OnDxilContainerBuilt( pOutputBlob, &pTargetBlob); if (SUCCEEDED(hr) && pTargetBlob != nullptr) { std::swap(pOutputBlob, pTargetBlob); } } if (pOutputBlob && produceFullContainer && (SerializeFlags & SerializeDxilFlags::IncludeDebugNamePart) != 0) { const DxilContainerHeader *pContainer = reinterpret_cast<DxilContainerHeader *>( pOutputBlob->GetBufferPointer()); DXASSERT(IsValidDxilContainer(pContainer, pOutputBlob->GetBufferSize()), "else invalid container generated"); auto it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_ShaderDebugName)); if (it != end(pContainer)) { const char *pDebugName; if (GetDxilShaderDebugName(*it, &pDebugName, nullptr) && pDebugName && *pDebugName) { IFT(pResult->SetOutputName(DXC_OUT_PDB, pDebugName)); } } } if (pReflectionStream && pReflectionStream->GetPtrSize()) { CComPtr<IDxcBlob> pReflection; IFT(pReflectionStream->QueryInterface(&pReflection)); IFT(pResult->SetOutputObject(DXC_OUT_REFLECTION, pReflection)); } if (pRootSigStream && pRootSigStream->GetPtrSize()) { CComPtr<IDxcBlob> pRootSignature; IFT(pRootSigStream->QueryInterface(&pRootSignature)); if (validateRootSigContainer && needsValidation) { CComPtr<IDxcBlobEncoding> pValErrors; // Validation failure communicated through diagnostic error dxcutil::ValidateRootSignatureInContainer( pRootSignature, &compiler.getDiagnostics(), opts.SelectValidator); } IFT(pResult->SetOutputObject(DXC_OUT_ROOT_SIGNATURE, pRootSignature)); } CComPtr<IDxcBlob> pHashBlob; IFT(hlsl::DxcCreateBlobOnHeapCopy(&ShaderHashContent, (UINT32)sizeof(ShaderHashContent), &pHashBlob)); IFT(pResult->SetOutputObject(DXC_OUT_SHADER_HASH, pHashBlob)); } // SUCCEEDED(valHR) } // compileOK && !opts.CodeGenHighLevel } std::string remarks; raw_string_ostream r(remarks); msfPtr->WriteStdOutToStream(r); CComPtr<IStream> pErrorStream; msfPtr->GetStdErrorHandleStream(&pErrorStream); CComPtr<IDxcBlob> pErrorBlob; IFT(pErrorStream.QueryInterface(&pErrorBlob)); if (IsBlobNullOrEmpty(pErrorBlob)) { // Add std err to warnings. IFT(pResult->SetOutputString(DXC_OUT_ERRORS, warnings.c_str(), warnings.size())); // Add std out to remarks. IFT(pResult->SetOutputString(DXC_OUT_REMARKS, remarks.c_str(), remarks.size())); } else { IFT(pResult->SetOutputObject(DXC_OUT_ERRORS, pErrorBlob)); } bool hasErrorOccurred = compiler.getDiagnostics().hasErrorOccurred(); bool writePDB = opts.GeneratePDB() && produceFullContainer; // SPIRV change starts #if defined(ENABLE_SPIRV_CODEGEN) writePDB &= !opts.GenSPIRV; #endif // SPIRV change ends if (!hasErrorOccurred && writePDB) { CComPtr<IDxcBlob> pStrippedContainer; { // Create the shader source information for PDB hlsl::SourceInfoWriter debugSourceInfoWriter; const hlsl::DxilSourceInfo *pSourceInfo = nullptr; if (!opts.SourceInDebugModule) { // If we are using old PDB format // where sources are in debug module, // do not generate source info at all debugSourceInfoWriter.Write(opts.TargetProfile, opts.EntryPoint, compiler.getCodeGenOpts(), compiler.getSourceManager()); pSourceInfo = debugSourceInfoWriter.GetPart(); } CComPtr<IDxcBlob> pDebugProgramBlob; CComPtr<AbstractMemoryStream> pReflectionInPdb; // Don't include the debug part if using source only PDB if (opts.SourceOnlyDebug) { assert(pSourceInfo); pReflectionInPdb = pReflectionStream; } else { if (!opts.SourceInDebugModule) { // Strip out the source related metadata debugModule->GetOrCreateDxilModule() .StripShaderSourcesAndCompileOptions( /* bReplaceWithDummyData */ true); } CComPtr<AbstractMemoryStream> pDebugBlobStorage; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pDebugBlobStorage)); raw_stream_ostream outStream(pDebugBlobStorage.p); WriteBitcodeToFile(debugModule.get(), outStream, true); outStream.flush(); IFT(pDebugBlobStorage.QueryInterface(&pDebugProgramBlob)); } IFT(CreateContainerForPDB(m_pMalloc, pOutputBlob, pDebugProgramBlob, static_cast<IDxcVersionInfo *>(this), pSourceInfo, pReflectionInPdb, &pStrippedContainer)); } // Create the final PDB Blob CComPtr<IDxcBlob> pPdbBlob; IFT(hlsl::pdb::WriteDxilPDB(m_pMalloc, pStrippedContainer, ShaderHashContent.Digest, &pPdbBlob)); IFT(pResult->SetOutputObject(DXC_OUT_PDB, pPdbBlob)); // If option Qpdb_in_private given, add the PDB to the DXC_OUT_OBJECT // container output as a DFCC_PrivateData part. if (opts.PdbInPrivate) { CComPtr<IDxcBlobEncoding> pContainerBlob; hlsl::DxcCreateBlobWithEncodingFromPinned( pOutputBlob->GetBufferPointer(), pOutputBlob->GetBufferSize(), CP_ACP, &pContainerBlob); CComPtr<IDxcContainerBuilder> pContainerBuilder; DxcCreateInstance2(this->m_pMalloc, CLSID_DxcContainerBuilder, IID_PPV_ARGS(&pContainerBuilder)); IFT(pContainerBuilder->Load(pOutputBlob)); IFT(pContainerBuilder->AddPart(hlsl::DFCC_PrivateData, pPdbBlob)); CComPtr<IDxcOperationResult> pReserializeResult; IFT(pContainerBuilder->SerializeContainer(&pReserializeResult)); CComPtr<IDxcBlob> pNewOutput; IFT(pReserializeResult->GetResult(&pNewOutput)); pOutputBlob = pNewOutput; } // PDB in private } // Write PDB IFT(primaryOutput.SetObject(pOutputBlob, opts.DefaultTextCodePage)); IFT(pResult->SetOutput(primaryOutput)); // It is possible for errors to occur, but the diagnostic or AST consumers // can recover from them, or translate them to mean something different. // This happens with the `-verify` flag where an error may be expected. // The correct way to identify errors in this case is to query the // DiagnosticClient for the number of errors. unsigned NumErrors = compiler.getDiagnostics().getClient()->getNumErrors(); IFT(pResult->SetStatusAndPrimaryResult(NumErrors > 0 ? E_FAIL : S_OK, primaryOutput.kind)); IFT(pResult->QueryInterface(riid, ppResult)); hr = S_OK; } catch (std::bad_alloc &) { hr = E_OUTOFMEMORY; } catch (hlsl::Exception &e) { assert(DXC_FAILED(e.hr)); CComPtr<IDxcResult> pResult; hr = e.hr; std::string msg("Internal Compiler error: "); switch (hr) { case DXC_E_VALIDATOR_MISSING: msg = "Error: external validator selected, but DXIL.dll not found."; break; default: break; } msg += e.msg; if (SUCCEEDED(DxcResult::Create( e.hr, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput(CP_UTF8, msg.c_str(), msg.size())}, &pResult)) && SUCCEEDED(pResult->QueryInterface(riid, ppResult))) { hr = S_OK; } } catch (...) { hr = E_FAIL; } Cleanup: if (bPreprocessStarted) { DxcEtw_DXCompilerPreprocess_Stop(hr); } if (bCompileStarted) { DxcEtw_DXCompilerCompile_Stop(hr); } return hr; } // Disassemble a program. virtual HRESULT STDMETHODCALLTYPE Disassemble( const DxcBuffer *pObject, // Program to disassemble: dxil container or bitcode. REFIID riid, LPVOID *ppResult // IDxcResult: status, disassembly text, and errors ) override { if (pObject == nullptr || ppResult == nullptr) return E_INVALIDARG; if (!(IsEqualIID(riid, __uuidof(IDxcResult)) || IsEqualIID(riid, __uuidof(IDxcOperationResult)))) return E_INVALIDARG; *ppResult = nullptr; CComPtr<IDxcResult> pResult; HRESULT hr = S_OK; DxcEtw_DXCompilerDisassemble_Start(); DxcThreadMalloc TM(m_pMalloc); try { DefaultFPEnvScope fpEnvScope; ::llvm::sys::fs::MSFileSystem *msfPtr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); std::string StreamStr; raw_string_ostream Stream(StreamStr); CComPtr<IDxcBlobEncoding> pProgram; IFT(hlsl::DxcCreateBlob(pObject->Ptr, pObject->Size, true, false, false, 0, nullptr, &pProgram)) IFC(dxcutil::Disassemble(pProgram, Stream)); IFT(DxcResult::Create(S_OK, DXC_OUT_DISASSEMBLY, {DxcOutputObject::StringOutput( DXC_OUT_DISASSEMBLY, CP_UTF8, StreamStr.c_str(), StreamStr.size(), DxcOutNoName)}, &pResult)); IFT(pResult->QueryInterface(riid, ppResult)); return S_OK; } catch (std::bad_alloc &) { hr = E_OUTOFMEMORY; } catch (hlsl::Exception &e) { assert(DXC_FAILED(e.hr)); hr = e.hr; if (SUCCEEDED( DxcResult::Create(e.hr, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput( CP_UTF8, e.msg.c_str(), e.msg.size())}, &pResult)) && SUCCEEDED(pResult->QueryInterface(riid, ppResult))) { hr = S_OK; } } catch (...) { hr = E_FAIL; } Cleanup: DxcEtw_DXCompilerDisassemble_Stop(hr); return hr; } void SetupCompilerForCompile(CompilerInstance &compiler, DxcLangExtensionsHelper *helper, LPCSTR pMainFile, TextDiagnosticPrinter *diagPrinter, std::vector<std::string> &defines, hlsl::options::DxcOpts &Opts, LPCWSTR *pArguments, UINT32 argCount) { // Setup a compiler instance. std::shared_ptr<TargetOptions> targetOptions(new TargetOptions); targetOptions->Triple = "dxil-ms-dx"; if (helper) { targetOptions->Triple = helper->GetTargetTriple(); } targetOptions->DescriptionString = Opts.Enable16BitTypes ? hlsl::DXIL::kNewLayoutString : hlsl::DXIL::kLegacyLayoutString; compiler.HlslLangExtensions = helper; compiler.getDiagnosticOpts().ShowOptionNames = Opts.ShowOptionNames ? 1 : 0; compiler.getDiagnosticOpts().Warnings = std::move(Opts.Warnings); compiler.getDiagnosticOpts().VerifyDiagnostics = Opts.VerifyDiagnostics; compiler.createDiagnostics(diagPrinter, false); // don't output warning to stderr/file if "/no-warnings" is present. compiler.getDiagnostics().setIgnoreAllWarnings(!Opts.OutputWarnings); if (Opts.DiagnosticsFormat.equals_lower("msvc") || Opts.DiagnosticsFormat.equals_lower("msvc-fallback")) compiler.getDiagnosticOpts().setFormat(DiagnosticOptions::MSVC); else if (Opts.DiagnosticsFormat.equals_lower("vi")) compiler.getDiagnosticOpts().setFormat(DiagnosticOptions::Vi); else if (!Opts.DiagnosticsFormat.equals_lower("clang")) { auto const ID = compiler.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Warning, "invalid option %0 to -fdiagnostics-format: supported values are " "clang, msvc, msvc-fallback, and vi"); compiler.getDiagnostics().Report(ID) << Opts.DiagnosticsFormat; } compiler.createFileManager(); compiler.createSourceManager(compiler.getFileManager()); compiler.setTarget( TargetInfo::CreateTargetInfo(compiler.getDiagnostics(), targetOptions)); if (Opts.EnableDX9CompatMode) { auto const ID = compiler.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Warning, "/Gec flag is a deprecated functionality."); compiler.getDiagnostics().Report(ID); } compiler.getFrontendOpts().Inputs.push_back( FrontendInputFile(pMainFile, IK_HLSL)); compiler.getFrontendOpts().ShowTimers = Opts.TimeReport ? 1 : 0; // Setup debug information. if (Opts.GenerateFullDebugInfo()) { CodeGenOptions &CGOpts = compiler.getCodeGenOpts(); // HLSL Change - begin CGOpts.setDebugInfo(CodeGenOptions::FullDebugInfo); CGOpts.HLSLEmbedSourcesInModule = true; // HLSL Change - end // CGOpts.setDebugInfo(CodeGenOptions::FullDebugInfo); // HLSL change CGOpts.DebugColumnInfo = 1; CGOpts.DwarfVersion = 4; // Latest version. // TODO: consider // DebugPass, DebugCompilationDir, DwarfDebugFlags, SplitDwarfFile } else if (!Opts.ForceDisableLocTracking) { CodeGenOptions &CGOpts = compiler.getCodeGenOpts(); CGOpts.setDebugInfo(CodeGenOptions::LocTrackingOnly); CGOpts.DebugColumnInfo = 1; } clang::PreprocessorOptions &PPOpts(compiler.getPreprocessorOpts()); for (size_t i = 0; i < defines.size(); ++i) { PPOpts.addMacroDef(defines[i]); } PPOpts.IgnoreLineDirectives = Opts.IgnoreLineDirectives; // fxc compatibility: pre-expand operands before performing token-pasting PPOpts.ExpandTokPastingArg = Opts.LegacyMacroExpansion; // Pick additional arguments. clang::HeaderSearchOptions &HSOpts = compiler.getHeaderSearchOpts(); HSOpts.UseBuiltinIncludes = 0; // Consider: should we force-include '.' if the source file is relative? for (const llvm::opt::Arg *A : Opts.Args.filtered(options::OPT_I)) { const bool IsFrameworkFalse = false; const bool IgnoreSysRoot = true; if (dxcutil::IsAbsoluteOrCurDirRelative(A->getValue())) { HSOpts.AddPath(A->getValue(), frontend::Angled, IsFrameworkFalse, IgnoreSysRoot); } else { std::string s("./"); s += A->getValue(); HSOpts.AddPath(s, frontend::Angled, IsFrameworkFalse, IgnoreSysRoot); } } // Apply root signature option. unsigned rootSigMinor; if (Opts.ForceRootSigVer.empty() || Opts.ForceRootSigVer == "rootsig_1_1") { rootSigMinor = 1; } else { DXASSERT(Opts.ForceRootSigVer == "rootsig_1_0", "else opts should have been rejected"); rootSigMinor = 0; } compiler.getLangOpts().RootSigMajor = 1; compiler.getLangOpts().RootSigMinor = rootSigMinor; compiler.getLangOpts().HLSLVersion = Opts.HLSLVersion; compiler.getLangOpts().EnableDX9CompatMode = Opts.EnableDX9CompatMode; compiler.getLangOpts().EnableFXCCompatMode = Opts.EnableFXCCompatMode; compiler.getLangOpts().UseMinPrecision = !Opts.Enable16BitTypes; compiler.getLangOpts().EnablePayloadAccessQualifiers = Opts.EnablePayloadQualifiers; compiler.getLangOpts().HLSLProfile = compiler.getCodeGenOpts().HLSLProfile = Opts.TargetProfile; // Enable dumping implicit top level decls either if it was specifically // requested or if we are not dumping the ast from the command line. That // allows us to dump implicit AST nodes in the debugger. compiler.getLangOpts().DumpImplicitTopLevelDecls = Opts.AstDumpImplicit || !Opts.AstDump; compiler.getLangOpts().HLSLDefaultRowMajor = Opts.DefaultRowMajor; // SPIRV change starts #ifdef ENABLE_SPIRV_CODEGEN compiler.getLangOpts().SPIRV = Opts.GenSPIRV; llvm::Optional<spv_target_env> spirvTargetEnv = spirv::FeatureManager::stringToSpvEnvironment( Opts.SpirvOptions.targetEnv); // If we do not have a valid target environment, the error will be handled // later. if (spirvTargetEnv.hasValue()) { VersionTuple spirvVersion = spirv::FeatureManager::getSpirvVersion(spirvTargetEnv.getValue()); compiler.getLangOpts().SpirvMajorVersion = spirvVersion.getMajor(); assert(spirvVersion.getMinor().hasValue() && "There must always be a major and minor version number when " "targeting SPIR-V."); compiler.getLangOpts().SpirvMinorVersion = spirvVersion.getMinor().getValue(); } #endif // SPIRV change ends if (Opts.WarningAsError) compiler.getDiagnostics().setWarningsAsErrors(true); if (Opts.IEEEStrict) compiler.getCodeGenOpts().UnsafeFPMath = true; if (Opts.FloatDenormalMode.empty()) { compiler.getCodeGenOpts().HLSLFloat32DenormMode = DXIL::Float32DenormMode::Reserve7; // undefined } else if (Opts.FloatDenormalMode.equals_lower(StringRef("any"))) { compiler.getCodeGenOpts().HLSLFloat32DenormMode = DXIL::Float32DenormMode::Any; } else if (Opts.FloatDenormalMode.equals_lower(StringRef("ftz"))) { compiler.getCodeGenOpts().HLSLFloat32DenormMode = DXIL::Float32DenormMode::FTZ; } else { DXASSERT(Opts.FloatDenormalMode.equals_lower(StringRef("preserve")), "else opts should have been rejected"); compiler.getCodeGenOpts().HLSLFloat32DenormMode = DXIL::Float32DenormMode::Preserve; } if (Opts.DisableOptimizations) compiler.getCodeGenOpts().DisableLLVMOpts = true; compiler.getCodeGenOpts().OptimizationLevel = Opts.OptLevel; if (Opts.OptLevel >= 3) compiler.getCodeGenOpts().UnrollLoops = true; compiler.getCodeGenOpts().HLSLHighLevel = Opts.CodeGenHighLevel; compiler.getCodeGenOpts().HLSLAllowPreserveValues = Opts.AllowPreserveValues; compiler.getCodeGenOpts().HLSLOnlyWarnOnUnrollFail = Opts.EnableFXCCompatMode; compiler.getCodeGenOpts().HLSLResMayAlias = Opts.ResMayAlias; compiler.getCodeGenOpts().ScanLimit = Opts.ScanLimit; compiler.getCodeGenOpts().HLSLOptimizationToggles = Opts.OptToggles; compiler.getCodeGenOpts().HLSLAllResourcesBound = Opts.AllResourcesBound; compiler.getCodeGenOpts().HLSLIgnoreOptSemDefs = Opts.IgnoreOptSemDefs; compiler.getCodeGenOpts().HLSLIgnoreSemDefs = Opts.IgnoreSemDefs; compiler.getCodeGenOpts().HLSLOverrideSemDefs = Opts.OverrideSemDefs; compiler.getCodeGenOpts().HLSLPreferControlFlow = Opts.PreferFlowControl; compiler.getCodeGenOpts().HLSLAvoidControlFlow = Opts.AvoidFlowControl; compiler.getCodeGenOpts().HLSLLegacyResourceReservation = Opts.LegacyResourceReservation; compiler.getCodeGenOpts().HLSLDefines = defines; compiler.getCodeGenOpts().HLSLPreciseOutputs = Opts.PreciseOutputs; compiler.getCodeGenOpts().MainFileName = pMainFile; compiler.getCodeGenOpts().HLSLPrintBeforeAll = Opts.PrintBeforeAll; compiler.getCodeGenOpts().HLSLPrintBefore = Opts.PrintBefore; compiler.getCodeGenOpts().HLSLPrintAfterAll = Opts.PrintAfterAll; compiler.getCodeGenOpts().HLSLPrintAfter = Opts.PrintAfter; compiler.getCodeGenOpts().HLSLForceZeroStoreLifetimes = Opts.ForceZeroStoreLifetimes; compiler.getCodeGenOpts().HLSLEnableLifetimeMarkers = Opts.EnableLifetimeMarkers; compiler.getCodeGenOpts().HLSLEnablePayloadAccessQualifiers = Opts.EnablePayloadQualifiers; // Translate signature packing options if (Opts.PackPrefixStable) compiler.getCodeGenOpts().HLSLSignaturePackingStrategy = (unsigned)DXIL::PackingStrategy::PrefixStable; else if (Opts.PackOptimized) compiler.getCodeGenOpts().HLSLSignaturePackingStrategy = (unsigned)DXIL::PackingStrategy::Optimized; else compiler.getCodeGenOpts().HLSLSignaturePackingStrategy = (unsigned)DXIL::PackingStrategy::Default; // Constructing vector of strings to pass in to codegen. Just passing // in pArguments will expose ownership of memory to both CodeGenOptions and // this caller, which can lead to unexpected behavior. { // Find all args that are of Option::InputClass and record their indices // in a set. If there are multiple Option::InputClass arguments, exclude // all of them. We only use the last one and there's no point recording // the rest of them. // // This list is used to populate the argument list in debug module and // PDB, which are for recompiling. The input filenames are not needed for // it and should be excluded. llvm::DenseSet<unsigned> InputArgIndices; for (llvm::opt::Arg *arg : Opts.Args.getArgs()) { if (arg->getOption().getKind() == llvm::opt::Option::InputClass) InputArgIndices.insert(arg->getIndex()); } for (unsigned i = 0; i < Opts.Args.getNumInputArgStrings(); ++i) { if (InputArgIndices.count(i) == 0) { // Only include this arg if it's not in the set of // Option::InputClass args. StringRef argStr = Opts.Args.getArgString(i); compiler.getCodeGenOpts().HLSLArguments.emplace_back(argStr); } } } // Overrding default set of loop unroll. if (Opts.PreferFlowControl) compiler.getCodeGenOpts().UnrollLoops = false; if (Opts.AvoidFlowControl) compiler.getCodeGenOpts().UnrollLoops = true; clang::CodeGenOptions::InliningMethod Inlining = clang::CodeGenOptions::OnlyAlwaysInlining; if (Opts.NewInlining) Inlining = clang::CodeGenOptions::NormalInlining; compiler.getCodeGenOpts().setInlining(Inlining); compiler.getCodeGenOpts().HLSLExtensionsCodegen = std::make_shared<HLSLExtensionsCodegenHelperImpl>( compiler, m_langExtensionsHelper, Opts.RootSignatureDefine); // AutoBindingSpace also enables automatic binding for libraries if set. // UINT_MAX == unset compiler.getCodeGenOpts().HLSLDefaultSpace = Opts.AutoBindingSpace; // processed export names from -exports option: compiler.getCodeGenOpts().HLSLLibraryExports = Opts.Exports; // only export shader functions for library compiler.getCodeGenOpts().ExportShadersOnly = Opts.ExportShadersOnly; compiler.getLangOpts().ExportShadersOnly = Opts.ExportShadersOnly; if (Opts.DefaultLinkage.empty()) { compiler.getCodeGenOpts().DefaultLinkage = DXIL::DefaultLinkage::Default; } else if (Opts.DefaultLinkage.equals_lower("internal")) { compiler.getCodeGenOpts().DefaultLinkage = DXIL::DefaultLinkage::Internal; } else if (Opts.DefaultLinkage.equals_lower("external")) { compiler.getCodeGenOpts().DefaultLinkage = DXIL::DefaultLinkage::External; } compiler.getLangOpts().DefaultLinkage = compiler.getCodeGenOpts().DefaultLinkage; } // IDxcVersionInfo HRESULT STDMETHODCALLTYPE GetVersion(UINT32 *pMajor, UINT32 *pMinor) override { if (pMajor == nullptr || pMinor == nullptr) return E_INVALIDARG; *pMajor = DXIL::kDxilMajor; *pMinor = DXIL::kDxilMinor; return S_OK; } HRESULT STDMETHODCALLTYPE GetCustomVersionString( char **pVersionString // Custom version string for compiler. (Must be // CoTaskMemFree()'d!) ) override { size_t size = strlen(RC_FILE_VERSION); char *const result = (char *)CoTaskMemAlloc(size + 1); if (result == nullptr) return E_OUTOFMEMORY; std::strcpy(result, RC_FILE_VERSION); *pVersionString = result; return S_OK; } #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO HRESULT STDMETHODCALLTYPE GetCommitInfo(UINT32 *pCommitCount, char **pCommitHash) override { if (pCommitCount == nullptr || pCommitHash == nullptr) return E_INVALIDARG; char *const hash = (char *)CoTaskMemAlloc( 8 + 1); // 8 is guaranteed by utils/GetCommitInfo.py if (hash == nullptr) return E_OUTOFMEMORY; std::strcpy(hash, getGitCommitHash()); *pCommitHash = hash; *pCommitCount = getGitCommitCount(); return S_OK; } #endif // SUPPORT_QUERY_GIT_COMMIT_INFO HRESULT STDMETHODCALLTYPE GetFlags(UINT32 *pFlags) override { if (pFlags == nullptr) return E_INVALIDARG; *pFlags = DxcVersionInfoFlags_None; #ifndef NDEBUG *pFlags |= DxcVersionInfoFlags_Debug; #endif return S_OK; } }; ////////////////////////////////////////////////////////////// // legacy IDxcCompiler2 implementation that maps to DxcCompiler ULONG STDMETHODCALLTYPE DxcCompilerAdapter::AddRef() { return m_pCompilerImpl->AddRef(); } ULONG STDMETHODCALLTYPE DxcCompilerAdapter::Release() { return m_pCompilerImpl->Release(); } HRESULT STDMETHODCALLTYPE DxcCompilerAdapter::QueryInterface(REFIID iid, void **ppvObject) { return m_pCompilerImpl->QueryInterface(iid, ppvObject); } // Preprocess source text HRESULT STDMETHODCALLTYPE DxcCompilerAdapter::Preprocess( IDxcBlob *pSource, // Source text to preprocess LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult // Preprocessor output status, buffer, and errors ) { if (pSource == nullptr || ppResult == nullptr || (defineCount > 0 && pDefines == nullptr) || (argCount > 0 && pArguments == nullptr)) return E_INVALIDARG; *ppResult = nullptr; return WrapCompile(TRUE, pSource, pSourceName, nullptr, nullptr, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult, nullptr, nullptr); } // Disassemble a program. HRESULT STDMETHODCALLTYPE DxcCompilerAdapter::Disassemble( IDxcBlob *pProgram, // Program to disassemble. IDxcBlobEncoding **ppDisassembly // Disassembly text. ) { if (pProgram == nullptr || ppDisassembly == nullptr) return E_INVALIDARG; *ppDisassembly = nullptr; HRESULT hr = S_OK; DxcThreadMalloc TM(m_pMalloc); DxcBuffer buffer = {pProgram->GetBufferPointer(), pProgram->GetBufferSize(), 0}; CComPtr<IDxcResult> pResult; IFR(m_pCompilerImpl->Disassemble(&buffer, IID_PPV_ARGS(&pResult))); IFRBOOL(pResult, E_OUTOFMEMORY); IFR(pResult->GetStatus(&hr)); if (SUCCEEDED(hr)) { // Extract disassembly IFR(pResult->GetOutput(DXC_OUT_DISASSEMBLY, IID_PPV_ARGS(ppDisassembly), nullptr)); } return hr; } HRESULT CreateDxcUtils(REFIID riid, LPVOID *ppv); HRESULT STDMETHODCALLTYPE DxcCompilerAdapter::CompileWithDebug( IDxcBlob *pSource, // Source text to compile LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // Entry point name LPCWSTR pTargetProfile, // Shader profile to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult, // Compiler output status, buffer, and errors LPWSTR *ppDebugBlobName, // Suggested file name for debug blob. IDxcBlob **ppDebugBlob // Debug blob ) { if (pSource == nullptr || ppResult == nullptr || (defineCount > 0 && pDefines == nullptr) || (argCount > 0 && pArguments == nullptr) || pTargetProfile == nullptr) return E_INVALIDARG; *ppResult = nullptr; AssignToOutOpt(nullptr, ppDebugBlobName); AssignToOutOpt(nullptr, ppDebugBlob); return WrapCompile(FALSE, pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult, ppDebugBlobName, ppDebugBlob); } HRESULT DxcCompilerAdapter::WrapCompile( BOOL bPreprocess, // Preprocess mode IDxcBlob *pSource, // Source text to compile LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // Entry point name LPCWSTR pTargetProfile, // Shader profile to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult, // Compiler output status, buffer, and errors LPWSTR *ppDebugBlobName, // Suggested file name for debug blob. IDxcBlob **ppDebugBlob // Debug blob ) { HRESULT hr = S_OK; DxcThreadMalloc TM(m_pMalloc); try { CComPtr<IDxcUtils> pUtils; IFT(CreateDxcUtils(IID_PPV_ARGS(&pUtils))); CComPtr<IDxcCompilerArgs> pArgs; IFR(pUtils->BuildArguments(pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, &pArgs)); LPCWSTR PreprocessArgs[] = {L"-P", L"-Fi", L"preprocessed.hlsl"}; if (bPreprocess) { IFT(pArgs->AddArguments(PreprocessArgs, _countof(PreprocessArgs))); } DxcBuffer buffer = {pSource->GetBufferPointer(), pSource->GetBufferSize(), CP_ACP}; CComPtr<IDxcBlobEncoding> pSourceEncoding; if (SUCCEEDED(pSource->QueryInterface(&pSourceEncoding))) { BOOL sourceEncodingKnown = false; IFT(pSourceEncoding->GetEncoding(&sourceEncodingKnown, &buffer.Encoding)); } CComPtr<AbstractMemoryStream> pOutputStream; IFT(CreateMemoryStream(m_pMalloc, &pOutputStream)); // Parse command-line options into DxcOpts int argCountInt; IFT(UIntToInt(pArgs->GetCount(), &argCountInt)); hlsl::options::MainArgs mainArgs(argCountInt, pArgs->GetArguments(), 0); hlsl::options::DxcOpts opts; bool finished = false; CComPtr<IDxcOperationResult> pOperationResult; dxcutil::ReadOptsAndValidate(mainArgs, opts, pOutputStream, &pOperationResult, finished); if (!opts.TimeTrace.empty()) llvm::timeTraceProfilerInitialize(opts.TimeTraceGranularity); if (finished) { IFT(pOperationResult->QueryInterface(ppResult)); return S_OK; } if (pOutputStream->GetPosition() > 0) { // Clear existing stream in case it has option spew pOutputStream.Release(); IFT(CreateMemoryStream(m_pMalloc, &pOutputStream)); } // To concat out output with compiler errors raw_stream_ostream outStream(pOutputStream); LPCWSTR EmbedDebugOpt[] = {L"-Qembed_debug"}; if (opts.DebugInfo && !ppDebugBlob && !opts.EmbedDebug && !opts.StripDebug) { // SPIRV change starts #if defined(ENABLE_SPIRV_CODEGEN) if (!opts.GenSPIRV) outStream << "warning: no output provided for debug - embedding PDB in " "shader container. Use -Qembed_debug to silence this " "warning.\n"; #else outStream << "warning: no output provided for debug - embedding PDB in " "shader container. Use -Qembed_debug to silence this " "warning.\n"; #endif // SPIRV change ends IFT(pArgs->AddArguments(EmbedDebugOpt, _countof(EmbedDebugOpt))); } CComPtr<DxcResult> pResult = DxcResult::Alloc(m_pMalloc); pResult->SetEncoding(opts.DefaultTextCodePage); CComPtr<IDxcResult> pImplResult; IFR(m_pCompilerImpl->Compile(&buffer, pArgs->GetArguments(), pArgs->GetCount(), pIncludeHandler, IID_PPV_ARGS(&pImplResult))); IFRBOOL(pImplResult, E_OUTOFMEMORY); IFR(pImplResult->GetStatus(&hr)); pResult->CopyOutputsFromResult(pImplResult); pResult->SetStatusAndPrimaryResult(hr, pImplResult->PrimaryOutput()); if (opts.TimeReport) { std::string TimeReport; raw_string_ostream OS(TimeReport); llvm::TimerGroup::printAll(OS); IFT(pResult->SetOutputString(DXC_OUT_TIME_REPORT, TimeReport.c_str(), TimeReport.size())); } if (llvm::timeTraceProfilerEnabled()) { std::string TimeTrace; raw_string_ostream OS(TimeTrace); llvm::timeTraceProfilerWrite(OS); llvm::timeTraceProfilerCleanup(); IFT(pResult->SetOutputString(DXC_OUT_TIME_TRACE, TimeTrace.c_str(), TimeTrace.size())); } outStream.flush(); // Insert any warnings generated here if (pOutputStream->GetPosition() > 0) { CComPtr<IDxcBlobEncoding> pErrorsEncoding; if (SUCCEEDED(pResult->GetOutput( DXC_OUT_ERRORS, IID_PPV_ARGS(&pErrorsEncoding), nullptr)) && pErrorsEncoding && pErrorsEncoding->GetBufferSize()) { CComPtr<IDxcBlobUtf8> pErrorsUtf8; IFT(pUtils->GetBlobAsUtf8(pErrorsEncoding, &pErrorsUtf8)); outStream << pErrorsUtf8->GetStringPointer(); outStream.flush(); } // Reconstruct result with new error buffer CComPtr<IDxcBlobEncoding> pErrorBlob; IFT(hlsl::DxcCreateBlob(pOutputStream->GetPtr(), pOutputStream->GetPtrSize(), false, true, true, DXC_CP_UTF8, nullptr, &pErrorBlob)); if (pErrorBlob && pErrorBlob->GetBufferSize()) { pResult->Output(DXC_OUT_ERRORS)->object.Release(); pResult->SetOutputObject(DXC_OUT_ERRORS, pErrorBlob); } } // Extract debug blob if present CComHeapPtr<wchar_t> pDebugNameOnComHeap; CComPtr<IDxcBlob> pDebugBlob; if (SUCCEEDED(hr)) { CComPtr<IDxcBlobWide> pDebugName; hr = pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pDebugBlob), &pDebugName); if (SUCCEEDED(hr) && ppDebugBlobName && pDebugName) { if (!pDebugNameOnComHeap.AllocateBytes(pDebugName->GetBufferSize())) return E_OUTOFMEMORY; memcpy(pDebugNameOnComHeap.m_pData, pDebugName->GetBufferPointer(), pDebugName->GetBufferSize()); } } if (ppDebugBlob && pDebugBlob) *ppDebugBlob = pDebugBlob.Detach(); if (ppDebugBlobName && pDebugNameOnComHeap) *ppDebugBlobName = pDebugNameOnComHeap.Detach(); IFR(pResult.QueryInterface(ppResult)); hr = S_OK; } catch (std::bad_alloc &) { hr = E_OUTOFMEMORY; } catch (hlsl::Exception &e) { assert(DXC_FAILED(e.hr)); hr = DxcResult::Create( e.hr, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput(CP_UTF8, e.msg.c_str(), e.msg.size())}, ppResult); } catch (...) { hr = E_FAIL; } return hr; } ////////////////////////////////////////////////////////////// HRESULT CreateDxcCompiler(REFIID riid, LPVOID *ppv) { *ppv = nullptr; try { CComPtr<DxcCompiler> result(DxcCompiler::Alloc(DxcGetThreadMallocNoRef())); IFROOM(result.p); return result.p->QueryInterface(riid, ppv); } CATCH_CPP_RETURN_HRESULT(); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcapi.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcapi.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DxcCreateInstance function for the DirectX Compiler. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/WinIncludes.h" #ifdef _WIN32 #define DXC_API_IMPORT __declspec(dllexport) #else #define DXC_API_IMPORT __attribute__((visibility("default"))) #endif #include "dxc/Support/Global.h" #include "dxc/config.h" #include "dxc/dxcisense.h" #include "dxc/dxctools.h" #ifdef _WIN32 #include "dxcetw.h" #endif #include "dxc/DxilContainer/DxcContainerBuilder.h" #include "dxillib.h" #include <memory> HRESULT CreateDxcCompiler(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcDiaDataSource(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcIntelliSense(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcCompilerArgs(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcUtils(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcRewriter(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcValidator(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcAssembler(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcOptimizer(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcContainerBuilder(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcLinker(REFIID riid, _Out_ LPVOID *ppv); HRESULT CreateDxcPdbUtils(REFIID riid, _Out_ LPVOID *ppv); namespace hlsl { void CreateDxcContainerReflection(IDxcContainerReflection **ppResult); void CreateDxcLinker(IDxcContainerReflection **ppResult); } // namespace hlsl HRESULT CreateDxcContainerReflection(REFIID riid, _Out_ LPVOID *ppv) { try { CComPtr<IDxcContainerReflection> pReflection; hlsl::CreateDxcContainerReflection(&pReflection); return pReflection->QueryInterface(riid, ppv); } catch (const std::bad_alloc &) { return E_OUTOFMEMORY; } } HRESULT CreateDxcContainerBuilder(REFIID riid, _Out_ LPVOID *ppv) { // Call dxil.dll's containerbuilder *ppv = nullptr; const char *warning; HRESULT hr = DxilLibCreateInstance(CLSID_DxcContainerBuilder, (IDxcContainerBuilder **)ppv); if (FAILED(hr)) { warning = "Unable to create container builder from dxil.dll. Resulting " "container will not be signed.\n"; } else { return hr; } CComPtr<DxcContainerBuilder> Result = DxcContainerBuilder::Alloc(DxcGetThreadMallocNoRef()); IFROOM(Result.p); Result->Init(warning); return Result->QueryInterface(riid, ppv); } static HRESULT ThreadMallocDxcCreateInstance(REFCLSID rclsid, REFIID riid, _Out_ LPVOID *ppv) { HRESULT hr = S_OK; *ppv = nullptr; if (IsEqualCLSID(rclsid, CLSID_DxcCompiler)) { hr = CreateDxcCompiler(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcCompilerArgs)) { hr = CreateDxcCompilerArgs(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcUtils)) { hr = CreateDxcUtils(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcValidator)) { if (DxilLibIsEnabled()) { hr = DxilLibCreateInstance(rclsid, riid, (IUnknown **)ppv); } else { hr = CreateDxcValidator(riid, ppv); } } else if (IsEqualCLSID(rclsid, CLSID_DxcAssembler)) { hr = CreateDxcAssembler(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcOptimizer)) { hr = CreateDxcOptimizer(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcIntelliSense)) { hr = CreateDxcIntelliSense(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcContainerBuilder)) { hr = CreateDxcContainerBuilder(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcContainerReflection)) { hr = CreateDxcContainerReflection(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcPdbUtils)) { hr = CreateDxcPdbUtils(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcRewriter)) { hr = CreateDxcRewriter(riid, ppv); } else if (IsEqualCLSID(rclsid, CLSID_DxcLinker)) { hr = CreateDxcLinker(riid, ppv); } // Note: The following targets are not yet enabled for non-Windows platforms. #ifdef _WIN32 else if (IsEqualCLSID(rclsid, CLSID_DxcDiaDataSource)) { hr = CreateDxcDiaDataSource(riid, ppv); } #endif else { hr = REGDB_E_CLASSNOTREG; } return hr; } DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance(REFCLSID rclsid, REFIID riid, _Out_ LPVOID *ppv) { if (ppv == nullptr) { return E_POINTER; } HRESULT hr = S_OK; DxcEtw_DXCompilerCreateInstance_Start(); DxcThreadMalloc TM(nullptr); hr = ThreadMallocDxcCreateInstance(rclsid, riid, ppv); DxcEtw_DXCompilerCreateInstance_Stop(hr); return hr; } DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance2(IMalloc *pMalloc, REFCLSID rclsid, REFIID riid, _Out_ LPVOID *ppv) { if (ppv == nullptr) { return E_POINTER; } #ifdef DXC_DISABLE_ALLOCATOR_OVERRIDES if (pMalloc != DxcGetThreadMallocNoRef()) { return E_INVALIDARG; } #endif // DXC_DISABLE_ALLOCATOR_OVERRIDES HRESULT hr = S_OK; DxcEtw_DXCompilerCreateInstance_Start(); DxcThreadMalloc TM(pMalloc); hr = ThreadMallocDxcCreateInstance(rclsid, riid, ppv); DxcEtw_DXCompilerCreateInstance_Stop(hr); return hr; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcshadersourceinfo.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcshadersourceinfo.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Utility helpers for dealing with DXIL part related to shader sources // // and options. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DxilContainer/DxilContainer.h" #include "llvm/ADT/StringRef.h" #include <stdint.h> #include <vector> namespace clang { class CodeGenOptions; class SourceManager; } // namespace clang namespace hlsl { // TODO: Move this type to its own library. struct SourceInfoReader { using Buffer = std::vector<uint8_t>; Buffer m_UncompressedSources; struct Source { llvm::StringRef Name; llvm::StringRef Content; }; struct ArgPair { std::string Name; std::string Value; }; std::vector<Source> m_Sources; std::vector<ArgPair> m_ArgPairs; Source GetSource(unsigned i) const { return m_Sources[i]; } unsigned GetSourcesCount() const { return m_Sources.size(); } const ArgPair &GetArgPair(unsigned i) const { return m_ArgPairs[i]; } unsigned GetArgPairCount() const { return m_ArgPairs.size(); } // Note: The memory for SourceInfo must outlive this structure. bool Init(const hlsl::DxilSourceInfo *SourceInfo, unsigned sourceInfoSize); }; // Herper for writing the shader source part. struct SourceInfoWriter { using Buffer = std::vector<uint8_t>; Buffer m_Buffer; const hlsl::DxilSourceInfo *GetPart() const; void Write(llvm::StringRef targetProfile, llvm::StringRef entryPoint, clang::CodeGenOptions &cgOpts, clang::SourceManager &srcMgr); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcassembler.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcassembler.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Assembler object. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DXIL/DxilModule.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcapi.impl.h" #include "dxc/Support/dxcfilesystem.h" #include "dxc/Support/microcom.h" #include "dxcutil.h" #include "dxillib.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" using namespace llvm; using namespace hlsl; // This declaration is used for the locally-linked validator. HRESULT CreateDxcValidator(REFIID riid, LPVOID *ppv); static bool HasDebugInfo(const Module &M) { for (Module::const_named_metadata_iterator NMI = M.named_metadata_begin(), NME = M.named_metadata_end(); NMI != NME; ++NMI) { if (NMI->getName().startswith("llvm.dbg.")) { return true; } } return false; } class DxcAssembler : public IDxcAssembler { private: DXC_MICROCOM_TM_REF_FIELDS() public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcAssembler) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcAssembler>(this, iid, ppvObject); } // Assemble dxil in ll or llvm bitcode to dxbc container. HRESULT STDMETHODCALLTYPE AssembleToContainer( IDxcBlob *pShader, // Shader to assemble. IDxcOperationResult * *ppResult // Assemble output status, buffer, and errors ) override; }; // Assemble dxil in ll or llvm bitcode to dxbc container. HRESULT STDMETHODCALLTYPE DxcAssembler::AssembleToContainer( IDxcBlob *pShader, // Shader to assemble. IDxcOperationResult **ppResult // Assemble output status, buffer, and errors ) { if (pShader == nullptr || ppResult == nullptr) return E_POINTER; *ppResult = nullptr; HRESULT hr = S_OK; DxcThreadMalloc TM(m_pMalloc); try { ::llvm::sys::fs::MSFileSystem *msfPtr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); // Setup input buffer. // The ir parsing requires the buffer to be null terminated. We deal with // both source and bitcode input, so the input buffer may not be null // terminated. Create a new membuf that copies the buffer and adds a null // terminator. const unsigned char *pBytes = (const unsigned char *)(pShader->GetBufferPointer()); unsigned bytesLen = pShader->GetBufferSize(); bool bytesAreText = !isBitcode(pBytes, pBytes + bytesLen); CComPtr<IDxcBlob> readingBlob; CComPtr<IDxcBlobUtf8> bytesEncoded; if (bytesAreText) { // IR parsing requires a null terminator in the buffer. IFT(hlsl::DxcGetBlobAsUtf8(pShader, m_pMalloc, &bytesEncoded)); pBytes = (const unsigned char *)bytesEncoded->GetStringPointer(); bytesLen = bytesEncoded->GetBufferSize() - 1; // nullterm not included DXASSERT(pBytes[bytesLen] == 0, "otherwise, text not null-terminated."); } StringRef InputData((const char *)pBytes, bytesLen); const bool RequiresNullTerminator = false; std::unique_ptr<MemoryBuffer> memBuf = MemoryBuffer::getMemBuffer(InputData, "", RequiresNullTerminator); // Parse IR LLVMContext Context; SMDiagnostic Err; std::unique_ptr<Module> M = parseIR(memBuf->getMemBufferRef(), Err, Context); CComPtr<AbstractMemoryStream> pOutputStream; IFT(CreateMemoryStream(TM.GetInstalledAllocator(), &pOutputStream)); raw_stream_ostream outStream(pOutputStream.p); // Check for success. if (M.get() == 0) { Err.print("shader", outStream, false, false); outStream.flush(); CComPtr<IDxcBlob> pStreamBlob; CComPtr<IDxcBlobEncoding> pErrorBlob; DXVERIFY_NOMSG(SUCCEEDED(pOutputStream.QueryInterface(&pStreamBlob))); IFT(DxcResult::Create(E_FAIL, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput( CP_UTF8, // TODO Support DefaultTextCodePage (LPCSTR)pStreamBlob->GetBufferPointer(), pStreamBlob->GetBufferSize())}, ppResult)); return S_OK; } // Upgrade Validator Version if necessary. try { DxilModule &program = M->GetOrCreateDxilModule(); // Only set validator version metadata if none present. if (nullptr == M->getNamedMetadata(DxilMDHelper::kDxilValidatorVersionMDName)) { UINT32 majorVer, minorVer; dxcutil::GetValidatorVersion(&majorVer, &minorVer); if (program.UpgradeValidatorVersion(majorVer, minorVer)) { program.UpdateValidatorVersionMetadata(); } } } catch (hlsl::Exception &e) { IFT(DxcResult::Create(e.hr, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput( CP_UTF8, // TODO Support DefaultTextCodePage e.msg.c_str(), e.msg.size())}, ppResult)); return S_OK; } // Create bitcode of M. WriteBitcodeToFile(M.get(), outStream); outStream.flush(); CComPtr<IDxcBlob> pResultBlob; hlsl::SerializeDxilFlags flags = hlsl::SerializeDxilFlags::IncludeReflectionPart; if (HasDebugInfo(*M)) { flags |= SerializeDxilFlags::IncludeDebugInfoPart; flags |= SerializeDxilFlags::IncludeDebugNamePart; flags |= SerializeDxilFlags::DebugNameDependOnSource; } dxcutil::AssembleInputs inputs(std::move(M), pResultBlob, TM.GetInstalledAllocator(), flags, pOutputStream); dxcutil::AssembleToContainer(inputs); IFT(DxcResult::Create(S_OK, DXC_OUT_OBJECT, {DxcOutputObject::DataOutput( DXC_OUT_OBJECT, pResultBlob, DxcOutNoName)}, ppResult)); } CATCH_CPP_ASSIGN_HRESULT(); return hr; } HRESULT CreateDxcAssembler(REFIID riid, LPVOID *ppv) { CComPtr<DxcAssembler> result = DxcAssembler::Alloc(DxcGetThreadMallocNoRef()); if (result == nullptr) { *ppv = nullptr; return E_OUTOFMEMORY; } return result.p->QueryInterface(riid, ppv); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxclinker.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxclinker.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the Dxil Linker. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/ErrorCodes.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcapi.impl.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "dxillib.h" #include "llvm/ADT/SmallVector.h" #include <algorithm> #include "dxc/DxilValidation/DxilValidation.h" #include "dxc/HLSL/DxilLinker.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.internal.h" #include "dxcutil.h" #include "clang/Basic/Diagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/raw_ostream.h" using namespace hlsl; using namespace llvm; // This declaration is used for the locally-linked validator. HRESULT CreateDxcValidator(REFIID riid, LPVOID *ppv); struct DeserializedDxilCompilerVersion { const hlsl::DxilCompilerVersion DCV; std::string commitHashStr; std::string versionStr; DeserializedDxilCompilerVersion(const DxilCompilerVersion *pDCV) : DCV(*pDCV) { // Assumes pDCV has been checked for safe parsing if (pDCV->VersionStringListSizeInBytes) { const char *pStr = (const char *)(pDCV + 1); commitHashStr.assign(pStr); if (commitHashStr.size() + 1 < pDCV->VersionStringListSizeInBytes) versionStr.assign(pStr + commitHashStr.size() + 1); } } DeserializedDxilCompilerVersion(DeserializedDxilCompilerVersion &&other) : DCV(other.DCV), commitHashStr(std::move(other.commitHashStr)), versionStr(std::move(other.versionStr)) {} bool operator<(const DeserializedDxilCompilerVersion &rhs) const { return std::tie(DCV.Major, DCV.Minor, DCV.CommitCount, DCV.VersionStringListSizeInBytes, commitHashStr, versionStr) < std::tie(rhs.DCV.Major, rhs.DCV.Minor, rhs.DCV.CommitCount, rhs.DCV.VersionStringListSizeInBytes, rhs.commitHashStr, rhs.versionStr); } std::string display() const { std::string ret; ret += "Version(" + std::to_string(DCV.Major) + "." + std::to_string(DCV.Minor) + ") "; ret += "commits(" + std::to_string(DCV.CommitCount) + ") "; ret += "sha(" + commitHashStr + ") "; ret += "version string: \"" + versionStr + "\""; ret += "\n"; return ret; } }; class DxcLinker : public IDxcLinker, public IDxcContainerEvent { public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcLinker) // Register a library with name to ref it later. HRESULT RegisterLibrary(LPCWSTR pLibName, // Name of the library. IDxcBlob *pLib // Library to add. ) override; // Links the shader and produces a shader blob that the Direct3D runtime can // use. HRESULT STDMETHODCALLTYPE Link( LPCWSTR pEntryName, // Entry point name LPCWSTR pTargetProfile, // shader profile to link const LPCWSTR *pLibNames, // Array of library names to link UINT32 libCount, // Number of libraries to link const LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments IDxcOperationResult **ppResult // Linker output status, buffer, and errors ) override; HRESULT STDMETHODCALLTYPE RegisterDxilContainerEventHandler( IDxcContainerEventsHandler *pHandler, UINT64 *pCookie) override { DxcThreadMalloc TM(m_pMalloc); DXASSERT(m_pDxcContainerEventsHandler == nullptr, "else events handler is already registered"); *pCookie = 1; // Only one EventsHandler supported m_pDxcContainerEventsHandler = pHandler; return S_OK; }; HRESULT STDMETHODCALLTYPE UnRegisterDxilContainerEventHandler(UINT64 cookie) override { DxcThreadMalloc TM(m_pMalloc); DXASSERT(m_pDxcContainerEventsHandler != nullptr, "else unregister should not have been called"); m_pDxcContainerEventsHandler.Release(); return S_OK; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override { return DoBasicQueryInterface<IDxcLinker>(this, riid, ppvObject); } void Initialize() { UINT32 valMajor, valMinor; dxcutil::GetValidatorVersion(&valMajor, &valMinor); m_pLinker.reset(DxilLinker::CreateLinker(m_Ctx, valMajor, valMinor)); } bool AddCompilerVersionMapEntry(LPCWSTR libName, const hlsl::DxilCompilerVersion *pDCV, uint32_t partSize) { // Make sure it's safe to parse pDCV bool valid = pDCV && partSize >= sizeof(hlsl::DxilCompilerVersion) && partSize - sizeof(hlsl::DxilCompilerVersion) >= pDCV->VersionStringListSizeInBytes; if (valid && pDCV->VersionStringListSizeInBytes) { const char *vStr = (const char *)(pDCV + 1); valid = vStr[pDCV->VersionStringListSizeInBytes - 1] == 0; } DXASSERT(valid, "DxilCompilerVersion part malformed"); if (!valid) return false; CW2A pUtf8LibName(libName); std::string libNameStr = std::string(pUtf8LibName); auto result = m_uniqueCompilerVersions.insert(DeserializedDxilCompilerVersion(pDCV)); m_libNameToCompilerVersionPart[libNameStr] = &(*result.first); return true; } ~DxcLinker() { // Make sure DxilLinker is released before LLVMContext. m_pLinker.reset(); } private: DXC_MICROCOM_TM_REF_FIELDS() LLVMContext m_Ctx; std::unique_ptr<DxilLinker> m_pLinker; CComPtr<IDxcContainerEventsHandler> m_pDxcContainerEventsHandler; std::vector<CComPtr<IDxcBlob>> m_blobs; // Keep blobs live for lazy load. std::map<std::string, const DeserializedDxilCompilerVersion *> m_libNameToCompilerVersionPart; std::set<DeserializedDxilCompilerVersion> m_uniqueCompilerVersions; }; HRESULT DxcLinker::RegisterLibrary(LPCWSTR pLibName, // Name of the library. IDxcBlob *pBlob // Library to add. ) { if (!pLibName || !pBlob) return E_INVALIDARG; DXASSERT(m_pLinker.get(), "else Initialize() not called or failed silently"); DxcThreadMalloc TM(m_pMalloc); // Prepare UTF8-encoded versions of API values. CW2A pUtf8LibName(pLibName); // Already exist lib with same name. if (m_pLinker->HasLibNameRegistered(pUtf8LibName.m_psz)) return E_INVALIDARG; try { std::unique_ptr<llvm::Module> pModule, pDebugModule; CComPtr<AbstractMemoryStream> pDiagStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pDiagStream)); raw_stream_ostream DiagStream(pDiagStream); IFR(ValidateLoadModuleFromContainerLazy( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), pModule, pDebugModule, m_Ctx, m_Ctx, DiagStream)); // add an entry into the library to compiler version part map const hlsl::DxilContainerHeader *pHeader = hlsl::IsDxilContainerLike( pBlob->GetBufferPointer(), pBlob->GetBufferSize()); const DxilPartHeader *pDPH = hlsl::GetDxilPartByType( pHeader, hlsl::DxilFourCC::DFCC_CompilerVersion); if (pDPH) { const hlsl::DxilCompilerVersion *pDCV = (const hlsl::DxilCompilerVersion *)(pDPH + 1); // If the compiler version string is non-empty, add the struct to the // map if (!AddCompilerVersionMapEntry(pLibName, pDCV, pDPH->PartSize)) { return E_INVALIDARG; } } if (m_pLinker->RegisterLib(pUtf8LibName.m_psz, std::move(pModule), std::move(pDebugModule))) { m_blobs.emplace_back(pBlob); return S_OK; } else { return E_INVALIDARG; } } catch (hlsl::Exception &) { return E_INVALIDARG; } } // Links the shader and produces a shader blob that the Direct3D runtime can // use. HRESULT STDMETHODCALLTYPE DxcLinker::Link( LPCWSTR pEntryName, // Entry point name LPCWSTR pTargetProfile, // shader profile to link const LPCWSTR *pLibNames, // Array of library names to link UINT32 libCount, // Number of libraries to link const LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments IDxcOperationResult **ppResult // Linker output status, buffer, and errors ) { if (!pTargetProfile || !pLibNames || libCount == 0 || !ppResult) return E_INVALIDARG; DxcThreadMalloc TM(m_pMalloc); // Prepare UTF8-encoded versions of API values. CW2A pUtf8TargetProfile(pTargetProfile); CW2A pUtf8EntryPoint(pEntryName); CComPtr<AbstractMemoryStream> pOutputStream; // Detach previous libraries. m_pLinker->DetachAll(); HRESULT hr = S_OK; try { CComPtr<IDxcBlob> pOutputBlob; CComPtr<AbstractMemoryStream> pDiagStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream)); // Read and validate options. int argCountInt; IFT(UIntToInt(argCount, &argCountInt)); hlsl::options::MainArgs mainArgs(argCountInt, const_cast<LPCWSTR *>(pArguments), 0); hlsl::options::DxcOpts opts; CW2A pUtf8TargetProfile(pTargetProfile); // Set target profile before reading options and validate opts.TargetProfile = pUtf8TargetProfile.m_psz; bool finished; dxcutil::ReadOptsAndValidate(mainArgs, opts, pOutputStream, ppResult, finished); if (pEntryName) opts.EntryPoint = pUtf8EntryPoint.m_psz; if (finished) { return S_OK; } // IDxcResult output CComPtr<DxcResult> pResult = DxcResult::Alloc(m_pMalloc); IFT(pResult->SetEncoding(opts.DefaultTextCodePage)); IFT(pResult->SetOutputName(DXC_OUT_REFLECTION, opts.OutputReflectionFile)); IFT(pResult->SetOutputName(DXC_OUT_SHADER_HASH, opts.OutputShaderHashFile)); IFT(pResult->SetOutputName(DXC_OUT_ERRORS, opts.OutputWarningsFile)); IFT(pResult->SetOutputName(DXC_OUT_ROOT_SIGNATURE, opts.OutputRootSigFile)); IFT(pResult->SetOutputName(DXC_OUT_OBJECT, opts.OutputObject)); std::string warnings; // llvm::raw_string_ostream w(warnings); IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pDiagStream)); raw_stream_ostream DiagStream(pDiagStream); llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream); PrintDiagnosticContext DiagContext(DiagPrinter); m_Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler, &DiagContext, true); unsigned valMajor = 0, valMinor = 0; if (opts.ValVerMajor != UINT_MAX) { // user-specified validator version override valMajor = opts.ValVerMajor; valMinor = opts.ValVerMinor; } else { // Version from dxil.dll, or internal validator if unavailable dxcutil::GetValidatorVersion(&valMajor, &valMinor); } m_pLinker->SetValidatorVersion(valMajor, valMinor); // Root signature-only container validation is only supported on 1.5 and // above. bool validateRootSigContainer = DXIL::CompareVersions(valMajor, valMinor, 1, 5) >= 0; bool needsValidation = !opts.DisableValidation; // Disable validation if ValVerMajor is 0 (offline target, never validate), // or pre-release library targets lib_6_1/lib_6_2. if (opts.ValVerMajor == 0 || opts.TargetProfile == "lib_6_1" || opts.TargetProfile == "lib_6_2") { needsValidation = false; } // Attach libraries. bool bSuccess = true; const DeserializedDxilCompilerVersion *cur_version = nullptr; const DeserializedDxilCompilerVersion *first_version = nullptr; std::string cur_lib_name; std::string first_lib_name; for (UINT32 i = 0; i < libCount; i++) { CW2A pUtf8LibName(pLibNames[i]); bSuccess &= m_pLinker->AttachLib(pUtf8LibName.m_psz); cur_lib_name = std::string(pUtf8LibName); // only libraries with compiler version parts are in the map auto result = m_libNameToCompilerVersionPart.find(cur_lib_name); if (result != m_libNameToCompilerVersionPart.end()) { cur_version = result->second; } if (i == 0) { first_lib_name = cur_lib_name; first_version = cur_version; } if (cur_version != first_version) { std::string errorMsg = "error: Cannot link libraries with " "conflicting compiler versions.\n"; std::string firstErrorStr = "note: library \"" + first_lib_name + "\" version: "; firstErrorStr += first_version ? first_version->display() : "No version info available"; std::string secondErrorStr = "note: library \"" + cur_lib_name + "\" version: "; secondErrorStr += cur_version ? cur_version->display() : "No version info available"; errorMsg += firstErrorStr + secondErrorStr; DiagStream << errorMsg; bSuccess = false; } } dxilutil::ExportMap exportMap; bSuccess &= exportMap.ParseExports(opts.Exports, DiagStream); if (opts.ExportShadersOnly) exportMap.setExportShadersOnly(true); bool hasErrorOccurred = !bSuccess; if (bSuccess) { std::unique_ptr<Module> pM = m_pLinker->Link(opts.EntryPoint, pUtf8TargetProfile.m_psz, exportMap); if (pM) { const IntrusiveRefCntPtr<clang::DiagnosticIDs> Diags( new clang::DiagnosticIDs); IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts = new clang::DiagnosticOptions(); // Construct our diagnostic client. clang::TextDiagnosticPrinter *DiagClient = new clang::TextDiagnosticPrinter(DiagStream, &*DiagOpts); clang::DiagnosticsEngine Diag(Diags, &*DiagOpts, DiagClient); raw_stream_ostream outStream(pOutputStream.p); // Create bitcode of M. WriteBitcodeToFile(pM.get(), outStream); outStream.flush(); DxilShaderHash ShaderHashContent; CComPtr<AbstractMemoryStream> pReflectionStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pReflectionStream)); CComPtr<AbstractMemoryStream> pRootSigStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pRootSigStream)); SerializeDxilFlags SerializeFlags = hlsl::options::ComputeSerializeDxilFlags(opts); // Always save debug info. If lib has debug info, the link result will // have debug info. SerializeFlags |= SerializeDxilFlags::IncludeDebugNamePart; // Unless we want to strip it right away, include it in the container. if (!opts.StripDebug) { SerializeFlags |= SerializeDxilFlags::IncludeDebugInfoPart; } // Validation. HRESULT valHR = S_OK; dxcutil::AssembleInputs inputs( std::move(pM), pOutputBlob, DxcGetThreadMallocNoRef(), SerializeFlags, pOutputStream, 0, opts.DebugFile, &Diag, &ShaderHashContent, pReflectionStream, pRootSigStream, nullptr, nullptr); if (needsValidation) { valHR = dxcutil::ValidateAndAssembleToContainer(inputs); } else { dxcutil::AssembleToContainer(inputs); } // Callback after valid DXIL is produced if (SUCCEEDED(valHR)) { CComPtr<IDxcBlob> pTargetBlob; if (m_pDxcContainerEventsHandler != nullptr) { HRESULT hr = m_pDxcContainerEventsHandler->OnDxilContainerBuilt( pOutputBlob, &pTargetBlob); if (SUCCEEDED(hr) && pTargetBlob != nullptr) { std::swap(pOutputBlob, pTargetBlob); } } // TODO: DFCC_ShaderDebugName // DXC_OUT_REFLECTION if (pReflectionStream && pReflectionStream->GetPtrSize()) { CComPtr<IDxcBlob> pReflection; IFT(pReflectionStream->QueryInterface(&pReflection)); IFT(pResult->SetOutputObject(DXC_OUT_REFLECTION, pReflection)); } // DXC_OUT_ROOT_SIGNATURE if (pRootSigStream && pRootSigStream->GetPtrSize()) { CComPtr<IDxcBlob> pRootSignature; IFT(pRootSigStream->QueryInterface(&pRootSignature)); if (validateRootSigContainer && needsValidation) { CComPtr<IDxcBlobEncoding> pValErrors; // Validation failure communicated through diagnostic error dxcutil::ValidateRootSignatureInContainer(pRootSignature, &Diag); } IFT(pResult->SetOutputObject(DXC_OUT_ROOT_SIGNATURE, pRootSignature)); } // DXC_OUT_SHADER_HASH CComPtr<IDxcBlob> pHashBlob; IFT(hlsl::DxcCreateBlobOnHeapCopy(&ShaderHashContent, (UINT32)sizeof(ShaderHashContent), &pHashBlob)); IFT(pResult->SetOutputObject(DXC_OUT_SHADER_HASH, pHashBlob)); // DXC_OUT_OBJECT IFT(pResult->SetOutputObject(DXC_OUT_OBJECT, pOutputBlob)); } hasErrorOccurred = Diag.hasErrorOccurred(); } else { hasErrorOccurred = true; } } DiagStream.flush(); CComPtr<IStream> pStream = static_cast<CComPtr<IStream>>(pDiagStream); CComPtr<IDxcBlob> pErrorBlob; IFT(pStream.QueryInterface(&pErrorBlob)); if (IsBlobNullOrEmpty(pErrorBlob)) { // Add std err to warnings. IFT(pResult->SetOutputString(DXC_OUT_ERRORS, warnings.c_str(), warnings.size())); } else { IFT(pResult->SetOutputObject(DXC_OUT_ERRORS, pErrorBlob)); } IFT(pResult->SetStatusAndPrimaryResult(hasErrorOccurred ? E_FAIL : S_OK, DXC_OUT_OBJECT)); IFT(pResult->QueryInterface(IID_PPV_ARGS(ppResult))); } CATCH_CPP_ASSIGN_HRESULT(); return hr; } HRESULT CreateDxcLinker(REFIID riid, LPVOID *ppv) { *ppv = nullptr; try { CComPtr<DxcLinker> result(DxcLinker::Alloc(DxcGetThreadMallocNoRef())); IFROOM(result.p); result->Initialize(); return result.p->QueryInterface(riid, ppv); } CATCH_CPP_RETURN_HRESULT(); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/DXCompiler.cpp
/////////////////////////////////////////////////////////////////////////////// // // // DXCompiler.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the entry point for the dxcompiler DLL. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/WinIncludes.h" #include "dxc/Support/Global.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/config.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #ifdef LLVM_ON_WIN32 #include "dxcetw.h" #endif #include "dxillib.h" namespace hlsl { HRESULT SetupRegistryPassForHLSL(); HRESULT SetupRegistryPassForPIX(); } // namespace hlsl // C++ exception specification ignored except to indicate a function is not // __declspec(nothrow) #pragma warning(disable : 4290) #if defined(LLVM_ON_WIN32) && !defined(DXC_DISABLE_ALLOCATOR_OVERRIDES) // operator new and friends. void *__CRTDECL operator new(std::size_t size) noexcept(false) { void *ptr = DxcNew(size); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } void *__CRTDECL operator new(std::size_t size, const std::nothrow_t &nothrow_value) throw() { return DxcNew(size); } void __CRTDECL operator delete(void *ptr) throw() { DxcDelete(ptr); } void __CRTDECL operator delete(void *ptr, const std::nothrow_t &nothrow_constant) throw() { DxcDelete(ptr); } #endif static HRESULT InitMaybeFail() throw() { HRESULT hr; bool fsSetup = false, memSetup = false; IFC(DxcInitThreadMalloc()); DxcSetThreadMallocToDefault(); memSetup = true; if (::llvm::sys::fs::SetupPerThreadFileSystem()) { hr = E_FAIL; goto Cleanup; } fsSetup = true; IFC(hlsl::SetupRegistryPassForHLSL()); IFC(hlsl::SetupRegistryPassForPIX()); IFC(DxilLibInitialize()); if (hlsl::options::initHlslOptTable()) { hr = E_FAIL; goto Cleanup; } Cleanup: if (FAILED(hr)) { if (fsSetup) { ::llvm::sys::fs::CleanupPerThreadFileSystem(); } if (memSetup) { DxcClearThreadMalloc(); DxcCleanupThreadMalloc(); } } else { DxcClearThreadMalloc(); } return hr; } #if defined(LLVM_ON_UNIX) HRESULT __attribute__((constructor)) DllMain() { return InitMaybeFail(); } void __attribute__((destructor)) DllShutdown() { DxcSetThreadMallocToDefault(); ::hlsl::options::cleanupHlslOptTable(); ::llvm::sys::fs::CleanupPerThreadFileSystem(); ::llvm::llvm_shutdown(); DxcClearThreadMalloc(); DxcCleanupThreadMalloc(); } #else // LLVM_ON_UNIX BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD Reason, LPVOID reserved) { BOOL result = TRUE; if (Reason == DLL_PROCESS_ATTACH) { EventRegisterMicrosoft_Windows_DXCompiler_API(); DxcEtw_DXCompilerInitialization_Start(); HRESULT hr = InitMaybeFail(); DxcEtw_DXCompilerInitialization_Stop(hr); result = SUCCEEDED(hr) ? TRUE : FALSE; } else if (Reason == DLL_PROCESS_DETACH) { DxcEtw_DXCompilerShutdown_Start(); DxcSetThreadMallocToDefault(); ::hlsl::options::cleanupHlslOptTable(); ::llvm::sys::fs::CleanupPerThreadFileSystem(); ::llvm::llvm_shutdown(); if (reserved == NULL) { // FreeLibrary has been called or the DLL load failed DxilLibCleanup(DxilLibCleanUpType::UnloadLibrary); } else { // Process termination. We should not call FreeLibrary() DxilLibCleanup(DxilLibCleanUpType::ProcessTermination); } DxcClearThreadMalloc(); DxcCleanupThreadMalloc(); DxcEtw_DXCompilerShutdown_Stop(S_OK); EventUnregisterMicrosoft_Windows_DXCompiler_API(); } return result; } #endif // LLVM_ON_UNIX
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcutil.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcutil.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides helper code for dxcompiler. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxcutil.h" #include "dxc/DXIL/DxilModule.h" #include "dxc/DxilContainer/DxilContainerAssembler.h" #include "dxc/DxilRootSignature/DxilRootSignature.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcapi.impl.h" #include "dxc/dxcapi.h" #include "dxillib.h" #include "clang/Basic/Diagnostic.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Support/Path.h" using namespace llvm; using namespace hlsl; // This declaration is used for the locally-linked validator. HRESULT CreateDxcValidator(REFIID riid, LPVOID *ppv); // This internal call allows the validator to avoid having to re-deserialize // the module. It trusts that the caller didn't make any changes and is // kept internal because the layout of the module class may change based // on changes across modules, or picking a different compiler version or CRT. HRESULT RunInternalValidator(IDxcValidator *pValidator, llvm::Module *pDebugModule, IDxcBlob *pShader, UINT32 Flags, IDxcOperationResult **ppResult); namespace { // AssembleToContainer helper functions. bool CreateValidator(CComPtr<IDxcValidator> &pValidator, hlsl::options::ValidatorSelection SelectValidator = hlsl::options::ValidatorSelection::Auto) { bool bInternal = SelectValidator == hlsl::options::ValidatorSelection::Internal; bool bExternal = SelectValidator == hlsl::options::ValidatorSelection::External; if (!bInternal && DxilLibIsEnabled()) DxilLibCreateInstance(CLSID_DxcValidator, &pValidator); bool bInternalValidator = false; if (pValidator == nullptr) { IFTBOOL(!bExternal, DXC_E_VALIDATOR_MISSING); IFT(CreateDxcValidator(IID_PPV_ARGS(&pValidator))); bInternalValidator = true; } return bInternalValidator; } } // namespace namespace dxcutil { AssembleInputs::AssembleInputs( std::unique_ptr<llvm::Module> &&pM, CComPtr<IDxcBlob> &pOutputContainerBlob, IMalloc *pMalloc, hlsl::SerializeDxilFlags SerializeFlags, CComPtr<hlsl::AbstractMemoryStream> &pModuleBitcode, uint32_t ValidationFlags, llvm::StringRef DebugName, clang::DiagnosticsEngine *pDiag, hlsl::DxilShaderHash *pShaderHashOut, AbstractMemoryStream *pReflectionOut, AbstractMemoryStream *pRootSigOut, CComPtr<IDxcBlob> pRootSigBlob, CComPtr<IDxcBlob> pPrivateBlob, hlsl::options::ValidatorSelection SelectValidator) : pM(std::move(pM)), pOutputContainerBlob(pOutputContainerBlob), pMalloc(pMalloc), SerializeFlags(SerializeFlags), ValidationFlags(ValidationFlags), pModuleBitcode(pModuleBitcode), DebugName(DebugName), pDiag(pDiag), pShaderHashOut(pShaderHashOut), pReflectionOut(pReflectionOut), pRootSigOut(pRootSigOut), pRootSigBlob(pRootSigBlob), pPrivateBlob(pPrivateBlob), SelectValidator(SelectValidator) {} void GetValidatorVersion(unsigned *pMajor, unsigned *pMinor, hlsl::options::ValidatorSelection SelectValidator) { if (pMajor == nullptr || pMinor == nullptr) return; CComPtr<IDxcValidator> pValidator; CreateValidator(pValidator, SelectValidator); CComPtr<IDxcVersionInfo> pVersionInfo; if (SUCCEEDED(pValidator.QueryInterface(&pVersionInfo))) { IFT(pVersionInfo->GetVersion(pMajor, pMinor)); } else { // Default to 1.0 *pMajor = 1; *pMinor = 0; } } void AssembleToContainer(AssembleInputs &inputs) { CComPtr<AbstractMemoryStream> pContainerStream; IFT(CreateMemoryStream(inputs.pMalloc, &pContainerStream)); if (!(inputs.SerializeFlags & SerializeDxilFlags::StripRootSignature) && inputs.pRootSigBlob) { IFT(SetRootSignature(&inputs.pM->GetOrCreateDxilModule(), inputs.pRootSigBlob)); } // Update the module root signature from file if (inputs.pPrivateBlob) { SerializeDxilContainerForModule( &inputs.pM->GetOrCreateDxilModule(), inputs.pModuleBitcode, inputs.pVersionInfo, pContainerStream, inputs.DebugName, inputs.SerializeFlags, inputs.pShaderHashOut, inputs.pReflectionOut, inputs.pRootSigOut, inputs.pPrivateBlob->GetBufferPointer(), inputs.pPrivateBlob->GetBufferSize()); } else { SerializeDxilContainerForModule( &inputs.pM->GetOrCreateDxilModule(), inputs.pModuleBitcode, inputs.pVersionInfo, pContainerStream, inputs.DebugName, inputs.SerializeFlags, inputs.pShaderHashOut, inputs.pReflectionOut, inputs.pRootSigOut); } inputs.pOutputContainerBlob.Release(); IFT(pContainerStream.QueryInterface(&inputs.pOutputContainerBlob)); } void ReadOptsAndValidate(hlsl::options::MainArgs &mainArgs, hlsl::options::DxcOpts &opts, AbstractMemoryStream *pOutputStream, IDxcOperationResult **ppResult, bool &finished) { const llvm::opt::OptTable *table = ::options::getHlslOptTable(); raw_stream_ostream outStream(pOutputStream); if (0 != hlsl::options::ReadDxcOpts(table, hlsl::options::CompilerFlags, mainArgs, opts, outStream)) { CComPtr<IDxcBlob> pErrorBlob; IFT(pOutputStream->QueryInterface(&pErrorBlob)); outStream.flush(); IFT(DxcResult::Create( E_INVALIDARG, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput(opts.DefaultTextCodePage, (LPCSTR)pErrorBlob->GetBufferPointer(), pErrorBlob->GetBufferSize())}, ppResult)); finished = true; return; } DXASSERT(opts.HLSLVersion > hlsl::LangStd::v2015, "else ReadDxcOpts didn't fail for non-isense"); finished = false; } HRESULT ValidateAndAssembleToContainer(AssembleInputs &inputs) { HRESULT valHR = S_OK; // If we have debug info, this will be a clone of the module before debug info // is stripped. This is used with internal validator to provide more useful // error messages. std::unique_ptr<llvm::Module> llvmModuleWithDebugInfo; CComPtr<IDxcValidator> pValidator; bool bInternalValidator = CreateValidator(pValidator, inputs.SelectValidator); // Warning on internal Validator CComPtr<IDxcValidator2> pValidator2; if (!bInternalValidator) { pValidator.QueryInterface(&pValidator2); } if (bInternalValidator || pValidator2) { // If using the internal validator or external validator supports // IDxcValidator2, we'll use the modules directly. In this case, we'll want // to make a clone to avoid SerializeDxilContainerForModule stripping all // the debug info. The debug info will be stripped from the orginal module, // but preserved in the cloned module. if (llvm::getDebugMetadataVersionFromModule(*inputs.pM) != 0) { llvmModuleWithDebugInfo.reset(llvm::CloneModule(inputs.pM.get())); } } // Verify validator version can validate this module CComPtr<IDxcVersionInfo> pValidatorVersion; IFT(pValidator->QueryInterface(&pValidatorVersion)); UINT32 ValMajor, ValMinor; IFT(pValidatorVersion->GetVersion(&ValMajor, &ValMinor)); DxilModule &DM = inputs.pM.get()->GetOrCreateDxilModule(); unsigned ReqValMajor, ReqValMinor; DM.GetValidatorVersion(ReqValMajor, ReqValMinor); if (DXIL::CompareVersions(ValMajor, ValMinor, ReqValMajor, ReqValMinor) < 0) { // Module is expecting to be validated by a newer validator. if (inputs.pDiag) { unsigned diagID = inputs.pDiag->getCustomDiagID( clang::DiagnosticsEngine::Level::Error, "The module cannot be validated by the version of the validator " "currently attached."); inputs.pDiag->Report(diagID); } return E_FAIL; } AssembleToContainer(inputs); CComPtr<IDxcOperationResult> pValResult; // Important: in-place edit is required so the blob is reused and thus // dxil.dll can be released. inputs.ValidationFlags |= DxcValidatorFlags_InPlaceEdit; if (bInternalValidator) { IFT(RunInternalValidator(pValidator, llvmModuleWithDebugInfo.get(), inputs.pOutputContainerBlob, inputs.ValidationFlags, &pValResult)); } else { if (pValidator2 && llvmModuleWithDebugInfo) { // If metadata was stripped, re-serialize the input module. CComPtr<AbstractMemoryStream> pDebugModuleStream; IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pDebugModuleStream)); raw_stream_ostream outStream(pDebugModuleStream.p); WriteBitcodeToFile(llvmModuleWithDebugInfo.get(), outStream, true); outStream.flush(); DxcBuffer debugModule = {}; debugModule.Ptr = pDebugModuleStream->GetPtr(); debugModule.Size = pDebugModuleStream->GetPtrSize(); IFT(pValidator2->ValidateWithDebug(inputs.pOutputContainerBlob, inputs.ValidationFlags, &debugModule, &pValResult)); } else { IFT(pValidator->Validate(inputs.pOutputContainerBlob, inputs.ValidationFlags, &pValResult)); } } IFT(pValResult->GetStatus(&valHR)); if (inputs.pDiag) { if (FAILED(valHR)) { CComPtr<IDxcBlobEncoding> pErrors; CComPtr<IDxcBlobUtf8> pErrorsUtf8; IFT(pValResult->GetErrorBuffer(&pErrors)); IFT(hlsl::DxcGetBlobAsUtf8(pErrors, inputs.pMalloc, &pErrorsUtf8)); StringRef errRef(pErrorsUtf8->GetStringPointer(), pErrorsUtf8->GetStringLength()); unsigned DiagID = inputs.pDiag->getCustomDiagID( clang::DiagnosticsEngine::Error, "validation errors\r\n%0"); inputs.pDiag->Report(DiagID) << errRef; } } CComPtr<IDxcBlob> pValidatedBlob; IFT(pValResult->GetResult(&pValidatedBlob)); if (pValidatedBlob != nullptr) { std::swap(inputs.pOutputContainerBlob, pValidatedBlob); } pValidator.Release(); return valHR; } HRESULT ValidateRootSignatureInContainer( IDxcBlob *pRootSigContainer, clang::DiagnosticsEngine *pDiag, hlsl::options::ValidatorSelection SelectValidator) { HRESULT valHR = S_OK; CComPtr<IDxcValidator> pValidator; CComPtr<IDxcOperationResult> pValResult; CreateValidator(pValidator); IFT(pValidator->Validate(pRootSigContainer, DxcValidatorFlags_RootSignatureOnly | DxcValidatorFlags_InPlaceEdit, &pValResult)); IFT(pValResult->GetStatus(&valHR)); if (pDiag) { if (FAILED(valHR)) { CComPtr<IDxcBlobEncoding> pErrors; CComPtr<IDxcBlobUtf8> pErrorsUtf8; IFT(pValResult->GetErrorBuffer(&pErrors)); IFT(hlsl::DxcGetBlobAsUtf8(pErrors, nullptr, &pErrorsUtf8)); StringRef errRef(pErrorsUtf8->GetStringPointer(), pErrorsUtf8->GetStringLength()); unsigned DiagID = pDiag->getCustomDiagID(clang::DiagnosticsEngine::Error, "root signature validation errors\r\n%0"); pDiag->Report(DiagID) << errRef; } } return valHR; } HRESULT SetRootSignature(hlsl::DxilModule *pModule, CComPtr<IDxcBlob> pSource) { const char *pName = "RTS0"; const UINT32 partKind = ((UINT32)pName[0] | ((UINT32)pName[1] << 8) | ((UINT32)pName[2] << 16) | ((UINT32)pName[3] << 24)); CComPtr<IDxcContainerReflection> pReflection; UINT32 partCount; IFT(DxcCreateInstance(CLSID_DxcContainerReflection, __uuidof(IDxcContainerReflection), (void **)&pReflection)); IFT(pReflection->Load(pSource)); IFT(pReflection->GetPartCount(&partCount)); CComPtr<IDxcBlob> pContent; for (UINT32 i = 0; i < partCount; ++i) { UINT32 curPartKind; IFT(pReflection->GetPartKind(i, &curPartKind)); if (curPartKind == partKind) { CComPtr<IDxcBlob> pContent; IFT(pReflection->GetPartContent(i, &pContent)); try { const void *serializedData = pContent->GetBufferPointer(); uint32_t serializedSize = pContent->GetBufferSize(); hlsl::RootSignatureHandle rootSig; rootSig.LoadSerialized(static_cast<const uint8_t *>(serializedData), serializedSize); std::vector<uint8_t> serializedRootSignature; serializedRootSignature.assign(rootSig.GetSerializedBytes(), rootSig.GetSerializedBytes() + rootSig.GetSerializedSize()); pModule->ResetSerializedRootSignature(serializedRootSignature); } catch (...) { return DXC_E_INCORRECT_ROOT_SIGNATURE; } } } return S_OK; } void CreateOperationResultFromOutputs( DXC_OUT_KIND resultKind, UINT32 textEncoding, IDxcBlob *pResultBlob, CComPtr<IStream> &pErrorStream, const std::string &warnings, bool hasErrorOccurred, IDxcOperationResult **ppResult) { CComPtr<DxcResult> pResult = DxcResult::Alloc(DxcGetThreadMallocNoRef()); IFT(pResult->SetEncoding(textEncoding)); IFT(pResult->SetStatusAndPrimaryResult(hasErrorOccurred ? E_FAIL : S_OK, resultKind)); IFT(pResult->SetOutputObject(resultKind, pResultBlob)); CComPtr<IDxcBlob> pErrorBlob; IFT(pErrorStream.QueryInterface(&pErrorBlob)); if (IsBlobNullOrEmpty(pErrorBlob)) { IFT(pResult->SetOutputString(DXC_OUT_ERRORS, warnings.c_str(), warnings.size())); } else { IFT(pResult->SetOutputObject(DXC_OUT_ERRORS, pErrorBlob)); } IFT(pResult.QueryInterface(ppResult)); } void CreateOperationResultFromOutputs(IDxcBlob *pResultBlob, CComPtr<IStream> &pErrorStream, const std::string &warnings, bool hasErrorOccurred, IDxcOperationResult **ppResult) { CreateOperationResultFromOutputs(DXC_OUT_OBJECT, DXC_CP_UTF8, pResultBlob, pErrorStream, warnings, hasErrorOccurred, ppResult); } bool IsAbsoluteOrCurDirRelative(const llvm::Twine &T) { if (llvm::sys::path::is_absolute(T)) { return true; } if (T.isSingleStringRef()) { StringRef r = T.getSingleStringRef(); if (r.size() < 2) return false; const char *pData = r.data(); return pData[0] == '.' && (pData[1] == '\\' || pData[1] == '/'); } DXASSERT(false, "twine kind not supported"); return false; } } // namespace dxcutil
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcshadersourceinfo.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcshadersourceinfo.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Utility helpers for dealing with DXIL part related to shader sources // // and options. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxcshadersourceinfo.h" #include "dxc/DxilCompression/DxilCompressionHelpers.h" #include "dxc/DxilContainer/DxilContainer.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/CodeGenOptions.h" #include "llvm/Support/Path.h" #include "dxc/Support/Global.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/Path.h" #include "dxc/Support/WinIncludes.h" using namespace hlsl; using Buffer = SourceInfoWriter::Buffer; /////////////////////////////////////////////////////////////////////////////// // Reader /////////////////////////////////////////////////////////////////////////////// static size_t PointerByteOffset(const void *a, const void *b) { return (const uint8_t *)a - (const uint8_t *)b; } bool SourceInfoReader::Init(const hlsl::DxilSourceInfo *SourceInfo, unsigned sourceInfoSize) { if (sizeof(*SourceInfo) > sourceInfoSize) return false; if (SourceInfo->AlignedSizeInBytes > sourceInfoSize) return false; const hlsl::DxilSourceInfo *mainHeader = SourceInfo; const size_t totalSizeInBytes = mainHeader->AlignedSizeInBytes; const hlsl::DxilSourceInfoSection *section = (const hlsl::DxilSourceInfoSection *)(SourceInfo + 1); for (unsigned i = 0; i < SourceInfo->SectionCount; i++) { if (PointerByteOffset(section + 1, mainHeader) > totalSizeInBytes) return false; if (PointerByteOffset(section, mainHeader) + section->AlignedSizeInBytes > totalSizeInBytes) return false; const size_t sectionSizeInBytes = section->AlignedSizeInBytes; switch (section->Type) { case hlsl::DxilSourceInfoSectionType::Args: { const hlsl::DxilSourceInfo_Args *header = (const hlsl::DxilSourceInfo_Args *)(section + 1); if (PointerByteOffset(header + 1, section) > sectionSizeInBytes) return false; if (PointerByteOffset(header + 1, section) + header->SizeInBytes > sectionSizeInBytes) return false; const char *ptr = (const char *)(header + 1); unsigned i = 0; while (i < header->SizeInBytes) { // To learn more about the format of this data, check struct // DxilSourceInfo_Args in DxilContainer.h Read the argument name const char *argName = ptr + i; unsigned argNameLength = 0; for (; i < header->SizeInBytes; i++) { if (ptr[i] == '\0') { i++; break; } argNameLength++; } // Read the argument value const char *argValue = ptr + i; unsigned argValueLength = 0; for (; i < header->SizeInBytes; i++) { if (ptr[i] == '\0') { i++; break; } argValueLength++; } ArgPair pair = {}; assert(argNameLength || argValueLength); if (argNameLength || argValueLength) { if (argNameLength) pair.Name.assign(argName, argNameLength); if (argValueLength) pair.Value.assign(argValue, argValueLength); m_ArgPairs.push_back(std::move(pair)); } } } break; case hlsl::DxilSourceInfoSectionType::SourceNames: { const hlsl::DxilSourceInfo_SourceNames *header = (const hlsl::DxilSourceInfo_SourceNames *)(section + 1); if (PointerByteOffset(header + 1, section) > sectionSizeInBytes) return false; if (PointerByteOffset(header + 1, section) + header->EntriesSizeInBytes > sectionSizeInBytes) return false; assert(m_Sources.size() == 0 || m_Sources.size() == header->Count); m_Sources.resize(header->Count); const hlsl::DxilSourceInfo_SourceNamesEntry *firstEntry = (const hlsl::DxilSourceInfo_SourceNamesEntry *)(header + 1); const hlsl::DxilSourceInfo_SourceNamesEntry *entry = firstEntry; for (unsigned i = 0; i < header->Count; i++) { if (PointerByteOffset(entry + 1, firstEntry) > header->EntriesSizeInBytes) return false; if (PointerByteOffset(entry + 1, firstEntry) + entry->NameSizeInBytes > header->EntriesSizeInBytes) return false; if (PointerByteOffset(entry, firstEntry) + entry->AlignedSizeInBytes > header->EntriesSizeInBytes) return false; const void *ptr = entry + 1; if (entry->NameSizeInBytes > 0) { // Fail if not null terminated if (((const char *)ptr)[entry->NameSizeInBytes - 1] != '\0') return false; llvm::StringRef name = { (const char *)ptr, entry->NameSizeInBytes - 1, }; m_Sources[i].Name = name; } entry = (const hlsl::DxilSourceInfo_SourceNamesEntry *)((const uint8_t *)entry + entry->AlignedSizeInBytes); } } break; case hlsl::DxilSourceInfoSectionType::SourceContents: { const hlsl::DxilSourceInfo_SourceContents *header = (const hlsl::DxilSourceInfo_SourceContents *)(section + 1); if (PointerByteOffset(header + 1, section) > sectionSizeInBytes) return false; if (PointerByteOffset(header + 1, section) + header->EntriesSizeInBytes > sectionSizeInBytes) return false; const hlsl::DxilSourceInfo_SourceContentsEntry *firstEntry = nullptr; if (header->CompressType == hlsl::DxilSourceInfo_SourceContentsCompressType::Zlib) { m_UncompressedSources.resize(header->UncompressedEntriesSizeInBytes); { bool bDecompressSucc = hlsl::ZlibResult::Success == ZlibDecompress(DxcGetThreadMallocNoRef(), header + 1, header->EntriesSizeInBytes, m_UncompressedSources.data(), m_UncompressedSources.size()); assert(bDecompressSucc); if (!bDecompressSucc) return false; } if (m_UncompressedSources.size() != header->UncompressedEntriesSizeInBytes) return false; firstEntry = (const hlsl::DxilSourceInfo_SourceContentsEntry *) m_UncompressedSources.data(); } else { if (header->EntriesSizeInBytes != header->UncompressedEntriesSizeInBytes) return false; if (PointerByteOffset(header + 1, section) + header->UncompressedEntriesSizeInBytes > sectionSizeInBytes) return false; firstEntry = (const hlsl::DxilSourceInfo_SourceContentsEntry *)(header + 1); } assert(m_Sources.size() == 0 || m_Sources.size() == header->Count); m_Sources.resize(header->Count); const hlsl::DxilSourceInfo_SourceContentsEntry *entry = firstEntry; for (unsigned i = 0; i < header->Count; i++) { if (PointerByteOffset(entry + 1, firstEntry) > header->UncompressedEntriesSizeInBytes) return false; if (PointerByteOffset(entry + 1, firstEntry) + entry->ContentSizeInBytes > header->UncompressedEntriesSizeInBytes) return false; if (PointerByteOffset(entry, firstEntry) + entry->AlignedSizeInBytes > header->UncompressedEntriesSizeInBytes) return false; const void *ptr = entry + 1; if (entry->ContentSizeInBytes > 0) { // Fail if not null terminated if (((const char *)ptr)[entry->ContentSizeInBytes - 1] != '\0') return false; llvm::StringRef content = { (const char *)ptr, entry->ContentSizeInBytes - 1, }; m_Sources[i].Content = content; } entry = (const hlsl::DxilSourceInfo_SourceContentsEntry *)((const uint8_t *)entry + entry->AlignedSizeInBytes); } } break; } section = (const hlsl::DxilSourceInfoSection *)((const uint8_t *)section + section->AlignedSizeInBytes); } return true; } /////////////////////////////////////////////////////////////////////////////// // Writer /////////////////////////////////////////////////////////////////////////////// static void Append(Buffer *buf, uint8_t c) { buf->push_back(c); } static void Append(Buffer *buf, const void *ptr, size_t size) { size_t OldSize = buf->size(); buf->resize(OldSize + size); memcpy(buf->data() + OldSize, ptr, size); } static uint32_t PadToFourBytes(uint32_t size) { uint32_t rem = size % 4; if (rem) return size + (4 - rem); return size; } static uint32_t PadBufferToFourBytes(Buffer *buf, uint32_t unpaddedSize) { const uint32_t paddedSize = PadToFourBytes(unpaddedSize); // Padding. for (uint32_t i = unpaddedSize; i < paddedSize; i++) { Append(buf, 0); } return paddedSize; } static void AppendFileContentEntry(Buffer *buf, llvm::StringRef content) { hlsl::DxilSourceInfo_SourceContentsEntry header = {}; header.AlignedSizeInBytes = PadToFourBytes(sizeof(header) + content.size() + 1); header.ContentSizeInBytes = content.size() + 1; const size_t offset = buf->size(); Append(buf, &header, sizeof(header)); Append(buf, content.data(), content.size()); Append(buf, 0); // Null term const size_t paddedOffset = PadBufferToFourBytes(buf, buf->size() - offset); (void)paddedOffset; assert(paddedOffset == header.AlignedSizeInBytes); } static size_t BeginSection(Buffer *buf) { const size_t sectionOffset = buf->size(); hlsl::DxilSourceInfoSection sectionHeader = {}; Append(buf, &sectionHeader, sizeof(sectionHeader)); // Write an empty header return sectionOffset; } static void FinishSection(Buffer *buf, const size_t sectionOffset, hlsl::DxilSourceInfoSectionType type) { hlsl::DxilSourceInfoSection sectionHeader = {}; // Calculate and pad the size of the section. const size_t sectionSize = buf->size() - sectionOffset; const size_t paddedSectionSize = PadBufferToFourBytes(buf, sectionSize); // Go back and rewrite the section header assert(paddedSectionSize % sizeof(uint32_t) == 0); sectionHeader.AlignedSizeInBytes = paddedSectionSize; sectionHeader.Type = type; memcpy(buf->data() + sectionOffset, &sectionHeader, sizeof(sectionHeader)); } struct SourceFile { std::string Name; llvm::StringRef Content; }; static std::vector<SourceFile> ComputeFileList(clang::CodeGenOptions &cgOpts, clang::SourceManager &srcMgr) { std::vector<SourceFile> ret; std::map<std::string, llvm::StringRef> filesMap; { bool bFoundMainFile = false; for (auto it = srcMgr.fileinfo_begin(), end = srcMgr.fileinfo_end(); it != end; ++it) { if (it->first->isValid() && !it->second->IsSystemFile) { llvm::SmallString<256> Path = llvm::StringRef(it->first->getName()); llvm::sys::path::native(Path); // If main file, write that to metadata first. // Add the rest to filesMap to sort by name. if (cgOpts.MainFileName.compare(it->first->getName()) == 0) { SourceFile file; file.Name = Path.str(); file.Content = it->second->getRawBuffer()->getBuffer(); ret.push_back(file); assert(!bFoundMainFile && "otherwise, more than one file matches main filename"); bFoundMainFile = true; } else { filesMap[Path.str()] = it->second->getRawBuffer()->getBuffer(); } } } assert(bFoundMainFile && "otherwise, no file found matches main filename"); // Emit the rest of the files in sorted order. for (auto it : filesMap) { SourceFile file; file.Name = it.first; file.Content = it.second; ret.push_back(file); } } return ret; } void SourceInfoWriter::Write(llvm::StringRef targetProfile, llvm::StringRef entryPoint, clang::CodeGenOptions &cgOpts, clang::SourceManager &srcMgr) { m_Buffer.clear(); // Write an empty header first. hlsl::DxilSourceInfo mainHeader = {}; Append(&m_Buffer, &mainHeader, sizeof(mainHeader)); std::vector<SourceFile> sourceFileList = ComputeFileList(cgOpts, srcMgr); //////////////////////////////////////////////////////////////////// // Add all file names in a list. //////////////////////////////////////////////////////////////////// { const size_t sectionOffset = BeginSection(&m_Buffer); // Write an empty header const size_t headerOffset = m_Buffer.size(); hlsl::DxilSourceInfo_SourceNames header = {}; Append(&m_Buffer, &header, sizeof(header)); // Write the entries data const size_t dataOffset = m_Buffer.size(); for (unsigned i = 0; i < sourceFileList.size(); i++) { SourceFile &file = sourceFileList[i]; const size_t entryOffset = m_Buffer.size(); // Write the header hlsl::DxilSourceInfo_SourceNamesEntry entryHeader = {}; entryHeader.NameSizeInBytes = file.Name.size() + 1; entryHeader.ContentSizeInBytes = file.Content.size() + 1; entryHeader.AlignedSizeInBytes = PadToFourBytes(sizeof(entryHeader) + file.Name.size() + 1); Append(&m_Buffer, &entryHeader, sizeof(entryHeader)); Append(&m_Buffer, file.Name.data(), file.Name.size()); Append(&m_Buffer, 0); // Null terminator const size_t paddedOffset = PadBufferToFourBytes(&m_Buffer, m_Buffer.size() - entryOffset); (void)paddedOffset; assert(paddedOffset == entryHeader.AlignedSizeInBytes); } // Go back and write the header. header.Count = sourceFileList.size(); header.EntriesSizeInBytes = m_Buffer.size() - dataOffset; memcpy(m_Buffer.data() + headerOffset, &header, sizeof(header)); FinishSection(&m_Buffer, sectionOffset, hlsl::DxilSourceInfoSectionType::SourceNames); mainHeader.SectionCount++; } //////////////////////////////////////////////////////////////////// // Add all file contents in a list. //////////////////////////////////////////////////////////////////// { const size_t sectionOffset = BeginSection(&m_Buffer); // Put all the contents in a buffer Buffer uncompressedBuffer; for (unsigned i = 0; i < sourceFileList.size(); i++) { SourceFile &file = sourceFileList[i]; AppendFileContentEntry(&uncompressedBuffer, file.Content); } const size_t headerOffset = m_Buffer.size(); // Write the header hlsl::DxilSourceInfo_SourceContents header = {}; header.EntriesSizeInBytes = uncompressedBuffer.size(); header.UncompressedEntriesSizeInBytes = uncompressedBuffer.size(); header.Count = sourceFileList.size(); Append(&m_Buffer, &header, sizeof(header)); const size_t sizeBeforeCompress = m_Buffer.size(); bool bCompressed = hlsl::ZlibResult::Success == ZlibCompressAppend(DxcGetThreadMallocNoRef(), uncompressedBuffer.data(), uncompressedBuffer.size(), m_Buffer); // If we compressed the content, go back to rewrite the header to write the // correct size in bytes. if (bCompressed) { header.EntriesSizeInBytes = m_Buffer.size() - sizeBeforeCompress; header.CompressType = hlsl::DxilSourceInfo_SourceContentsCompressType::Zlib; memcpy(m_Buffer.data() + headerOffset, &header, sizeof(header)); } // Otherwise, just write the whole uncompressed else { Append(&m_Buffer, uncompressedBuffer.data(), uncompressedBuffer.size()); } FinishSection(&m_Buffer, sectionOffset, hlsl::DxilSourceInfoSectionType::SourceContents); mainHeader.SectionCount++; } //////////////////////////////////////////////////////////////////// // Args //////////////////////////////////////////////////////////////////// { // Use the opt table to render the arguments and separate them into // argName and argValue. const size_t sectionOffset = BeginSection(&m_Buffer); hlsl::DxilSourceInfo_Args header = {}; const size_t headerOffset = m_Buffer.size(); Append(&m_Buffer, &header, sizeof(header)); // Write an empty header first llvm::SmallVector<const char *, 32> optPointers; for (const std::string &arg : cgOpts.HLSLArguments) { optPointers.push_back(arg.c_str()); } unsigned missingIndex = 0; unsigned missingCount = 0; const llvm::opt::OptTable *optTable = hlsl::options::getHlslOptTable(); llvm::opt::InputArgList argList = optTable->ParseArgs(optPointers, missingIndex, missingCount); llvm::SmallString<64> argumentStorage; const size_t argumentsOffset = m_Buffer.size(); for (llvm::opt::Arg *arg : argList) { llvm::StringRef name = arg->getOption().getName(); const char *value = nullptr; if (arg->getNumValues() > 0) { assert(arg->getNumValues() == 1); value = arg->getValue(); } // If this is a positional argument, set the name to "" // explicitly. if (arg->getOption().getKind() == llvm::opt::Option::InputClass) { name = ""; } // If the argument must be merged (eg. -Wx, where W is the option and x is // the value), merge them right now. else if (arg->getOption().getKind() == llvm::opt::Option::JoinedClass) { argumentStorage.clear(); argumentStorage.append(name); argumentStorage.append(value); name = argumentStorage; value = nullptr; } // Name Append(&m_Buffer, name.data(), name.size()); Append(&m_Buffer, 0); // Null term // Value if (value) Append(&m_Buffer, value, strlen(value)); Append(&m_Buffer, 0); // Null term header.Count++; } // For each arg // Go back and rewrite the header now that we know the size header.SizeInBytes = m_Buffer.size() - argumentsOffset; memcpy(m_Buffer.data() + headerOffset, &header, sizeof(header)); FinishSection(&m_Buffer, sectionOffset, hlsl::DxilSourceInfoSectionType::Args); mainHeader.SectionCount++; } // Go back and rewrite the main header. assert(m_Buffer.size() >= sizeof(mainHeader)); size_t mainPartSize = m_Buffer.size(); mainPartSize = PadBufferToFourBytes(&m_Buffer, mainPartSize); assert(mainPartSize % sizeof(uint32_t) == 0); mainHeader.AlignedSizeInBytes = mainPartSize; memcpy(m_Buffer.data(), &mainHeader, sizeof(mainHeader)); } const hlsl::DxilSourceInfo *hlsl::SourceInfoWriter::GetPart() const { if (!m_Buffer.size()) return nullptr; assert(m_Buffer.size() >= sizeof(hlsl::DxilSourceInfo)); const hlsl::DxilSourceInfo *ret = (const hlsl::DxilSourceInfo *)m_Buffer.data(); assert(ret->AlignedSizeInBytes == m_Buffer.size()); return ret; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcfilesystem.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcfilesystem.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides helper file system for dxcompiler. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" #include "dxc/dxcapi.h" #include "dxcutil.h" #include "llvm/Support/raw_ostream.h" #include "dxc/Support/Path.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/dxcfilesystem.h" #include "clang/Frontend/CompilerInstance.h" #ifndef _WIN32 #include <sys/stat.h> #include <unistd.h> #endif using namespace llvm; using namespace hlsl; // DxcArgsFileSystem namespace { #if defined(_MSC_VER) #include <io.h> #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO #define STDERR_FILENO 2 #endif #endif #ifdef _WIN32 #ifndef NDEBUG // This should be improved with global enabled mask rather than a compile-time // mask. #define DXTRACE_MASK_ENABLED 0 #define DXTRACE_MASK_APIFS 1 #define DXTRACE_ENABLED(subsystem) (DXTRACE_MASK_ENABLED & subsystem) // DXTRACE_FMT formats a debugger trace message if DXTRACE_MASK allows it. #define DXTRACE_FMT(subsystem, fmt, ...) \ do { \ if (DXTRACE_ENABLED(subsystem)) \ OutputDebugFormatA(fmt, __VA_ARGS__); \ } while (0) /// DXTRACE_FMT_APIFS is used by the API-based virtual filesystem. #define DXTRACE_FMT_APIFS(fmt, ...) \ DXTRACE_FMT(DXTRACE_MASK_APIFS, fmt, __VA_ARGS__) #else #define DXTRACE_FMT_APIFS(...) #endif // NDEBUG #else // _WIN32 #define DXTRACE_FMT_APIFS(...) #endif // _WIN32 enum class HandleKind { Special = 0, File = 1, FileDir = 2, SearchDir = 3 }; enum class SpecialValue { Unknown = 0, StdOut = 1, StdErr = 2, Source = 3, Output = 4 }; // We use 10 bits for Offset to support MaxIncludedFiles include files, // and we use 16 bits for Length to support nearly arbitrary path length. struct HandleBits { unsigned Offset : 10; unsigned Length : 16; unsigned Kind : 4; }; struct DxcArgsHandle { DxcArgsHandle(HANDLE h) : Handle(h) {} DxcArgsHandle(unsigned fileIndex) { Handle = 0; Bits.Offset = fileIndex; Bits.Length = 0; Bits.Kind = (unsigned)HandleKind::File; } DxcArgsHandle(HandleKind HK, unsigned fileIndex, unsigned dirLength) { Handle = 0; Bits.Offset = fileIndex; Bits.Length = dirLength; Bits.Kind = (unsigned)HK; } DxcArgsHandle(SpecialValue V) { Handle = 0; Bits.Offset = (unsigned)V; Bits.Length = 0; Bits.Kind = (unsigned)HandleKind::Special; ; } union { HANDLE Handle; HandleBits Bits; }; bool operator==(const DxcArgsHandle &Other) { return Handle == Other.Handle; } HandleKind GetKind() const { return (HandleKind)Bits.Kind; } bool IsFileKind() const { return GetKind() == HandleKind::File; } bool IsSpecialUnknown() const { return Handle == 0; } bool IsDirHandle() const { return GetKind() == HandleKind::FileDir || GetKind() == HandleKind::SearchDir; } bool IsStdHandle() const { return GetKind() == HandleKind::Special && (GetSpecialValue() == SpecialValue::StdErr || GetSpecialValue() == SpecialValue::StdOut); } unsigned GetFileIndex() const { DXASSERT_NOMSG(IsFileKind()); return Bits.Offset; } SpecialValue GetSpecialValue() const { DXASSERT_NOMSG(GetKind() == HandleKind::Special); return (SpecialValue)Bits.Offset; } unsigned Length() const { return Bits.Length; } }; static_assert(sizeof(DxcArgsHandle) == sizeof(HANDLE), "else can't transparently typecast"); const DxcArgsHandle UnknownHandle(SpecialValue::Unknown); const DxcArgsHandle StdOutHandle(SpecialValue::StdOut); const DxcArgsHandle StdErrHandle(SpecialValue::StdErr); const DxcArgsHandle OutputHandle(SpecialValue::Output); /// Max number of included files (1:1 to their directories) or search /// directories. If programs include more than a handful, DxcArgsFileSystem will /// need to do better than linear scans. If this is fired, /// ERROR_OUT_OF_STRUCTURES will be returned by an attempt to open a file. static const size_t MaxIncludedFiles = 1000; } // namespace namespace dxcutil { void MakeAbsoluteOrCurDirRelativeW(LPCWSTR &Path, std::wstring &PathStorage) { if (hlsl::IsAbsoluteOrCurDirRelativeW(Path)) { return; } else { PathStorage = L"./"; PathStorage += Path; Path = PathStorage.c_str(); } } /// File system based on API arguments. Support being added incrementally. /// /// DxcArgsFileSystem emulates a file system to clang/llvm based on API /// arguments. It can block certain functionality (like picking up the current /// directory), while adding other (like supporting an app's in-memory /// files through an IDxcIncludeHandler). /// /// stdin/stdout/stderr are registered especially (given that they have a /// special role in llvm::ins/outs/errs and are defaults to various operations, /// it's not unexpected). The direct user of DxcArgsFileSystem can also register /// streams to capture output for specific files. /// /// Support for IDxcIncludeHandler is somewhat tricky because the API is very /// minimal, to allow simple implementations, but that puts this class in the /// position of brokering between llvm/clang existing files (which probe for /// files and directories in various patterns), and this simpler handler. /// The current approach is to minimize changes in llvm/clang and work around /// the absence of directory support in IDxcIncludeHandler by assuming all /// included paths already exist (the handler may reject those paths later on), /// and always querying for a file before its parent directory (so we can /// disambiguate between one or the other). class DxcArgsFileSystemImpl : public DxcArgsFileSystem { private: CComPtr<IDxcBlobUtf8> m_pSource; LPCWSTR m_pSourceName; std::wstring m_pAbsSourceName; // absolute (or '.'-relative) source name CComPtr<IStream> m_pSourceStream; CComPtr<IStream> m_pOutputStream; CComPtr<AbstractMemoryStream> m_pStdOutStream; CComPtr<AbstractMemoryStream> m_pStdErrStream; LPCWSTR m_pOutputStreamName; std::wstring m_pAbsOutputStreamName; CComPtr<IDxcIncludeHandler> m_includeLoader; std::vector<std::wstring> m_searchEntries; bool m_bDisplayIncludeProcess; UINT32 m_DefaultCodePage; // Some constraints of the current design: opening the same file twice // will return the same handle/structure, and thus the same file pointer. struct IncludedFile { CComPtr<IDxcBlobUtf8> Blob; CComPtr<IStream> BlobStream; std::wstring Name; IncludedFile(std::wstring &&name, IDxcBlobUtf8 *pBlob, IStream *pStream) : Blob(pBlob), BlobStream(pStream), Name(name) {} }; llvm::SmallVector<IncludedFile, 4> m_includedFiles; static bool IsDirOf(LPCWSTR lpDir, size_t dirLen, const std::wstring &fileName) { if (fileName.size() <= dirLen) return false; if (0 != wcsncmp(lpDir, fileName.data(), dirLen)) return false; // Prefix matches, c:\\ to c:\\foo.hlsl or ./bar to ./bar/file.hlsl // Ensure there are no additional characters, don't match ./ba if ./bar.hlsl // exists if (lpDir[dirLen - 1] == '\\' || lpDir[dirLen - 1] == '/') { // The file name was already terminated in a separator. return true; } return fileName.data()[dirLen] == '\\' || fileName.data()[dirLen] == '/'; } static bool IsDirPrefixOrSame(LPCWSTR lpDir, size_t dirLen, const std::wstring &path) { if (0 == wcscmp(lpDir, path.c_str())) return true; return IsDirOf(lpDir, dirLen, path); } HANDLE TryFindDirHandle(LPCWSTR lpDir) const { size_t dirLen = wcslen(lpDir); for (size_t i = 0; i < m_includedFiles.size(); ++i) { const std::wstring &fileName = m_includedFiles[i].Name; if (IsDirOf(lpDir, dirLen, fileName)) { return DxcArgsHandle(HandleKind::FileDir, i, dirLen).Handle; } } for (size_t i = 0; i < m_searchEntries.size(); ++i) { if (IsDirPrefixOrSame(lpDir, dirLen, m_searchEntries[i])) { return DxcArgsHandle(HandleKind::SearchDir, i, dirLen).Handle; } } return INVALID_HANDLE_VALUE; } DWORD TryFindOrOpen(LPCWSTR lpFileName, size_t &index) { for (size_t i = 0; i < m_includedFiles.size(); ++i) { if (0 == wcscmp(lpFileName, m_includedFiles[i].Name.data())) { index = i; return ERROR_SUCCESS; } } if (m_includeLoader.p != nullptr) { if (m_includedFiles.size() == MaxIncludedFiles) { return ERROR_OUT_OF_STRUCTURES; } CComPtr<::IDxcBlob> fileBlob; std::wstring NormalizedFileName = hlsl::NormalizePathW(lpFileName); HRESULT hr = m_includeLoader->LoadSource(NormalizedFileName.c_str(), &fileBlob); if (FAILED(hr)) { return ERROR_UNHANDLED_EXCEPTION; } if (fileBlob.p != nullptr) { CComPtr<IDxcBlobUtf8> fileBlobUtf8; if (FAILED(hlsl::DxcGetBlobAsUtf8(fileBlob, DxcGetThreadMallocNoRef(), &fileBlobUtf8, m_DefaultCodePage))) { return ERROR_UNHANDLED_EXCEPTION; } CComPtr<IStream> fileStream; if (FAILED(hlsl::CreateReadOnlyBlobStream(fileBlobUtf8, &fileStream))) { return ERROR_UNHANDLED_EXCEPTION; } m_includedFiles.emplace_back(std::wstring(lpFileName), fileBlobUtf8, fileStream); index = m_includedFiles.size() - 1; if (m_bDisplayIncludeProcess) { std::string openFileStr; raw_string_ostream s(openFileStr); std::string fileName = Unicode::WideToUTF8StringOrThrow(lpFileName); s << "Opening file [" << fileName << "], stack top [" << (index - 1) << "]\n"; s.flush(); ULONG cbWritten; IFT(m_pStdOutStream->Write(openFileStr.c_str(), openFileStr.size(), &cbWritten)); } return ERROR_SUCCESS; } } return ERROR_NOT_FOUND; } static HANDLE IncludedFileIndexToHandle(size_t index) { return DxcArgsHandle(index).Handle; } bool IsKnownHandle(HANDLE h) const { return !DxcArgsHandle(h).IsSpecialUnknown(); } IncludedFile &HandleToIncludedFile(HANDLE handle) { DxcArgsHandle argsHandle(handle); DXASSERT_NOMSG(argsHandle.GetFileIndex() < m_includedFiles.size()); return m_includedFiles[argsHandle.GetFileIndex()]; } public: DxcArgsFileSystemImpl(IDxcBlobUtf8 *pSource, LPCWSTR pSourceName, IDxcIncludeHandler *pHandler, UINT32 defaultCodePage) : m_pSource(pSource), m_pSourceName(pSourceName), m_pOutputStreamName(nullptr), m_includeLoader(pHandler), m_bDisplayIncludeProcess(false), m_DefaultCodePage(defaultCodePage) { MakeAbsoluteOrCurDirRelativeW(m_pSourceName, m_pAbsSourceName); IFT(CreateReadOnlyBlobStream(m_pSource, &m_pSourceStream)); m_includedFiles.push_back( IncludedFile(std::wstring(m_pSourceName), m_pSource, m_pSourceStream)); } void EnableDisplayIncludeProcess() override { m_bDisplayIncludeProcess = true; } void WriteStdErrToStream(raw_string_ostream &s) override { s.write((char *)m_pStdErrStream->GetPtr(), m_pStdErrStream->GetPtrSize()); s.flush(); } void WriteStdOutToStream(raw_string_ostream &s) override { s.write((char *)m_pStdOutStream->GetPtr(), m_pStdOutStream->GetPtrSize()); s.flush(); } HRESULT CreateStdStreams(IMalloc *pMalloc) override { DXASSERT(m_pStdOutStream == nullptr, "else already created"); CreateMemoryStream(pMalloc, &m_pStdOutStream); CreateMemoryStream(pMalloc, &m_pStdErrStream); if (m_pStdOutStream == nullptr || m_pStdErrStream == nullptr) { return E_OUTOFMEMORY; } return S_OK; } void GetStreamForFD(int fd, IStream **ppResult) { return GetStreamForHandle(HandleFromFD(fd), ppResult); } void GetStreamForHandle(HANDLE handle, IStream **ppResult) { CComPtr<IStream> stream; DxcArgsHandle argsHandle(handle); if (argsHandle == OutputHandle) { stream = m_pOutputStream; } else if (argsHandle == StdOutHandle) { stream = m_pStdOutStream; } else if (argsHandle == StdErrHandle) { stream = m_pStdErrStream; } else if (argsHandle.GetKind() == HandleKind::File) { stream = HandleToIncludedFile(handle).BlobStream; } *ppResult = stream.Detach(); } void GetStdOutputHandleStream(IStream **ppResultStream) override { return GetStreamForHandle(StdOutHandle.Handle, ppResultStream); } void GetStdErrorHandleStream(IStream **ppResultStream) override { return GetStreamForHandle(StdErrHandle.Handle, ppResultStream); } void SetupForCompilerInstance(clang::CompilerInstance &compiler) override { DXASSERT(m_searchEntries.size() == 0, "else compiler instance being set twice"); // Turn these into UTF-16 to avoid converting later, and ensure they // are fully-qualified or relative to the current directory. const std::vector<clang::HeaderSearchOptions::Entry> &entries = compiler.getHeaderSearchOpts().UserEntries; if (entries.size() > MaxIncludedFiles) { throw hlsl::Exception(HRESULT_FROM_WIN32(ERROR_OUT_OF_STRUCTURES)); } for (unsigned i = 0, e = entries.size(); i != e; ++i) { const clang::HeaderSearchOptions::Entry &E = entries[i]; if (dxcutil::IsAbsoluteOrCurDirRelative(E.Path.c_str())) { m_searchEntries.emplace_back( Unicode::UTF8ToWideStringOrThrow(E.Path.c_str())); } else { std::wstring ws(L"./"); ws += Unicode::UTF8ToWideStringOrThrow(E.Path.c_str()); m_searchEntries.emplace_back(std::move(ws)); } } } HRESULT RegisterOutputStream(LPCWSTR pName, IStream *pStream) override { DXASSERT(m_pOutputStream.p == nullptr, "else multiple outputs registered"); m_pOutputStream = pStream; m_pOutputStreamName = pName; MakeAbsoluteOrCurDirRelativeW(m_pOutputStreamName, m_pAbsOutputStreamName); return S_OK; } HRESULT UnRegisterOutputStream() override { m_pOutputStream.Detach(); m_pOutputStream = nullptr; return S_OK; } ~DxcArgsFileSystemImpl() override{}; BOOL FindNextFileW(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } void FindClose(HANDLE findHandle) throw() override { __debugbreak(); } HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes) throw() override { DXTRACE_FMT_APIFS("DxcArgsFileSystem::CreateFileW %S\n", lpFileName); DWORD findError; { std::wstring FileNameStore; // The destructor might release and set // LastError to success. MakeAbsoluteOrCurDirRelativeW(lpFileName, FileNameStore); // Check for a match to the output file. if (m_pOutputStreamName != nullptr && 0 == wcscmp(lpFileName, m_pOutputStreamName)) { return OutputHandle.Handle; } HANDLE dirHandle = TryFindDirHandle(lpFileName); if (dirHandle != INVALID_HANDLE_VALUE) { return dirHandle; } size_t includedIndex; findError = TryFindOrOpen(lpFileName, includedIndex); if (findError == ERROR_SUCCESS) { return IncludedFileIndexToHandle(includedIndex); } } SetLastError(findError); return INVALID_HANDLE_VALUE; } BOOL SetFileTime(HANDLE hFile, const FILETIME *lpCreationTime, const FILETIME *lpLastAccessTime, const FILETIME *lpLastWriteTime) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } BOOL GetFileInformationByHandle( HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation) throw() override { DxcArgsHandle argsHandle(hFile); ZeroMemory(lpFileInformation, sizeof(*lpFileInformation)); lpFileInformation->nFileIndexLow = (DWORD)(uintptr_t)hFile; if (argsHandle.IsFileKind()) { IncludedFile &file = HandleToIncludedFile(hFile); lpFileInformation->dwFileAttributes = FILE_ATTRIBUTE_NORMAL; lpFileInformation->nFileSizeLow = file.Blob->GetStringLength(); return TRUE; } if (argsHandle == OutputHandle) { lpFileInformation->dwFileAttributes = FILE_ATTRIBUTE_NORMAL; STATSTG stat; HRESULT hr = m_pOutputStream->Stat(&stat, STATFLAG_NONAME); if (FAILED(hr)) { SetLastError(ERROR_IO_DEVICE); return FALSE; } lpFileInformation->nFileSizeLow = stat.cbSize.u.LowPart; return TRUE; } else if (argsHandle.IsDirHandle()) { lpFileInformation->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY; lpFileInformation->nFileIndexHigh = 1; return TRUE; } SetLastError(ERROR_INVALID_HANDLE); return FALSE; } DWORD GetFileType(HANDLE hFile) throw() override { DxcArgsHandle argsHandle(hFile); if (argsHandle.IsStdHandle()) { return FILE_TYPE_CHAR; } // Every other known handle is of type disk. if (!argsHandle.IsSpecialUnknown()) { return FILE_TYPE_DISK; } SetLastError(ERROR_NOT_FOUND); return FILE_TYPE_UNKNOWN; } BOOL CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } DWORD GetFileAttributesW(LPCWSTR lpFileName) throw() override { DXTRACE_FMT_APIFS("DxcArgsFileSystem::GetFileAttributesW %S\n", lpFileName); DWORD findError; { std::wstring FileNameStore; // The destructor might release and set // LastError to success. MakeAbsoluteOrCurDirRelativeW(lpFileName, FileNameStore); size_t sourceNameLen = wcslen(m_pSourceName); size_t fileNameLen = wcslen(lpFileName); // Check for a match to the source. if (fileNameLen == sourceNameLen) { if (0 == wcsncmp(m_pSourceName, lpFileName, fileNameLen)) { return FILE_ATTRIBUTE_NORMAL; } } // Check for a perfect match to the output. if (m_pOutputStreamName != nullptr && 0 == wcscmp(m_pOutputStreamName, lpFileName)) { return FILE_ATTRIBUTE_NORMAL; } if (TryFindDirHandle(lpFileName) != INVALID_HANDLE_VALUE) { return FILE_ATTRIBUTE_DIRECTORY; } size_t includedIndex; findError = TryFindOrOpen(lpFileName, includedIndex); if (findError == ERROR_SUCCESS) { return FILE_ATTRIBUTE_NORMAL; } } SetLastError(findError); return INVALID_FILE_ATTRIBUTES; } BOOL CloseHandle(HANDLE hObject) throw() override { // Not actually closing handle. Would allow improper usage, but simplifies // query/open/usage patterns. if (IsKnownHandle(hObject)) { return TRUE; } SetLastError(ERROR_INVALID_HANDLE); return FALSE; } BOOL DeleteFileW(LPCWSTR lpFileName) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } BOOL RemoveDirectoryW(LPCWSTR lpFileName) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } BOOL CreateDirectoryW(LPCWSTR lpPathName) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } DWORD GetMainModuleFileNameW(LPWSTR lpFilename, DWORD nSize) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } DWORD GetTempPathW(DWORD nBufferLength, LPWSTR lpBuffer) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } BOOLEAN CreateSymbolicLinkW(LPCWSTR lpSymlinkFileName, LPCWSTR lpTargetFileName, DWORD dwFlags) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } bool SupportsCreateSymbolicLink() throw() override { return false; } BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } HANDLE CreateFileMappingW(HANDLE hFile, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow) throw() override { SetLastError(ERROR_NOT_CAPABLE); return INVALID_HANDLE_VALUE; } LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap) throw() override { SetLastError(ERROR_NOT_CAPABLE); return nullptr; } BOOL UnmapViewOfFile(LPCVOID lpBaseAddress) throw() override { SetLastError(ERROR_NOT_CAPABLE); return FALSE; } // Console APIs. bool FileDescriptorIsDisplayed(int fd) throw() override { return false; } unsigned GetColumnCount(DWORD nStdHandle) throw() override { return 80; } unsigned GetConsoleOutputTextAttributes() throw() override { return 0; } void SetConsoleOutputTextAttributes(unsigned) throw() override { __debugbreak(); } void ResetConsoleOutputTextAttributes() throw() override { __debugbreak(); } // CRT APIs - handles and file numbers can be mapped directly. HANDLE HandleFromFD(int fd) const { if (fd == STDOUT_FILENO) return StdOutHandle.Handle; if (fd == STDERR_FILENO) return StdErrHandle.Handle; return (HANDLE)(uintptr_t)(fd); } int open_osfhandle(intptr_t osfhandle, int flags) throw() override { DxcArgsHandle H((HANDLE)osfhandle); if (H == StdOutHandle.Handle) return STDOUT_FILENO; if (H == StdErrHandle.Handle) return STDERR_FILENO; return (int)(intptr_t)H.Handle; } intptr_t get_osfhandle(int fd) throw() override { return (intptr_t)HandleFromFD(fd); } int close(int fd) throw() override { return 0; } long lseek(int fd, long offset, int origin) throw() override { CComPtr<IStream> stream; GetStreamForFD(fd, &stream); if (stream == nullptr) { errno = EBADF; return -1; } LARGE_INTEGER li; li.u.LowPart = offset; li.u.HighPart = 0; ULARGE_INTEGER newOffset; HRESULT hr = stream->Seek(li, origin, &newOffset); if (FAILED(hr)) { errno = EINVAL; return -1; } return newOffset.u.LowPart; } int setmode(int fd, int mode) throw() override { return 0; } errno_t resize_file(LPCWSTR path, uint64_t size) throw() override { return 0; } int Read(int fd, void *buffer, unsigned int count) throw() override { CComPtr<IStream> stream; GetStreamForFD(fd, &stream); if (stream == nullptr) { errno = EBADF; return -1; } ULONG cbRead; HRESULT hr = stream->Read(buffer, count, &cbRead); if (FAILED(hr)) { errno = EIO; return -1; } return (int)cbRead; } int Write(int fd, const void *buffer, unsigned int count) throw() override { CComPtr<IStream> stream; GetStreamForFD(fd, &stream); if (stream == nullptr) { errno = EBADF; return -1; } #ifndef NDEBUG if (fd == STDERR_FILENO) { char *copyWithNull = new char[count + 1]; strncpy(copyWithNull, (const char *)buffer, count); copyWithNull[count] = '\0'; OutputDebugStringA(copyWithNull); delete[] copyWithNull; } #endif ULONG written; HRESULT hr = stream->Write(buffer, count, &written); if (FAILED(hr)) { errno = EIO; return -1; } return (int)written; } #ifndef _WIN32 // Replicate Unix interfaces using DxcArgsFileSystemImpl int getStatus(HANDLE FileHandle, struct stat *Status) { if (FileHandle == INVALID_HANDLE_VALUE) return -1; memset(Status, 0, sizeof(*Status)); switch (GetFileType(FileHandle)) { default: llvm_unreachable("Don't know anything about this file type"); case FILE_TYPE_DISK: break; case FILE_TYPE_CHAR: Status->st_mode = S_IFCHR; return 0; case FILE_TYPE_PIPE: Status->st_mode = S_IFIFO; return 0; } BY_HANDLE_FILE_INFORMATION Info; if (!GetFileInformationByHandle(FileHandle, &Info)) return -1; if (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) Status->st_mode = S_IFDIR; else Status->st_mode = S_IFREG; Status->st_dev = Info.nFileIndexHigh; Status->st_ino = Info.nFileIndexLow; Status->st_mtime = Info.ftLastWriteTime.dwLowDateTime; Status->st_size = Info.nFileSizeLow; return 0; } virtual int Open(const char *lpFileName, int flags, mode_t mode) throw() override { HANDLE H = CreateFileW(CA2W(lpFileName), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); if (H == INVALID_HANDLE_VALUE) return -1; int FD = open_osfhandle(intptr_t(H), 0); if (FD == -1) CloseHandle(H); return FD; } // fake my way toward as linux-y a file_status as I can get virtual int Stat(const char *lpFileName, struct stat *Status) throw() override { CA2W fileName_wide(lpFileName); DWORD attr = GetFileAttributesW(fileName_wide); if (attr == INVALID_FILE_ATTRIBUTES) return -1; HANDLE H = CreateFileW(fileName_wide, 0, // Attributes only. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); if (H == INVALID_HANDLE_VALUE) return -1; return getStatus(H, Status); } virtual int Fstat(int FD, struct stat *Status) throw() override { HANDLE FileHandle = reinterpret_cast<HANDLE>(get_osfhandle(FD)); return getStatus(FileHandle, Status); } #endif // _WIN32 }; } // namespace dxcutil namespace dxcutil { DxcArgsFileSystem *CreateDxcArgsFileSystem(IDxcBlobUtf8 *pSource, LPCWSTR pSourceName, IDxcIncludeHandler *pIncludeHandler, UINT32 defaultCodePage) { return new DxcArgsFileSystemImpl(pSource, pSourceName, pIncludeHandler, defaultCodePage); } } // namespace dxcutil
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcutil.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcutil.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides helper code for dxcompiler. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DxilModule.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "llvm/ADT/StringRef.h" #include <memory> namespace clang { class DiagnosticsEngine; } namespace llvm { class LLVMContext; class MemoryBuffer; class Module; class raw_string_ostream; class Twine; } // namespace llvm namespace hlsl { struct DxilShaderHash; class AbstractMemoryStream; namespace options { class MainArgs; class DxcOpts; } // namespace options } // namespace hlsl namespace dxcutil { struct AssembleInputs { AssembleInputs(std::unique_ptr<llvm::Module> &&pM, CComPtr<IDxcBlob> &pOutputContainerBlob, IMalloc *pMalloc, hlsl::SerializeDxilFlags SerializeFlags, CComPtr<hlsl::AbstractMemoryStream> &pModuleBitcode, uint32_t ValidationFlags = 0, llvm::StringRef DebugName = llvm::StringRef(), clang::DiagnosticsEngine *pDiag = nullptr, hlsl::DxilShaderHash *pShaderHashOut = nullptr, hlsl::AbstractMemoryStream *pReflectionOut = nullptr, hlsl::AbstractMemoryStream *pRootSigOut = nullptr, CComPtr<IDxcBlob> pRootSigBlob = nullptr, CComPtr<IDxcBlob> pPrivateBlob = nullptr, hlsl::options::ValidatorSelection SelectValidator = hlsl::options::ValidatorSelection::Auto); std::unique_ptr<llvm::Module> pM; CComPtr<IDxcBlob> &pOutputContainerBlob; IDxcVersionInfo *pVersionInfo = nullptr; IMalloc *pMalloc; hlsl::SerializeDxilFlags SerializeFlags; uint32_t ValidationFlags = 0; CComPtr<hlsl::AbstractMemoryStream> &pModuleBitcode; llvm::StringRef DebugName = llvm::StringRef(); clang::DiagnosticsEngine *pDiag; hlsl::DxilShaderHash *pShaderHashOut = nullptr; hlsl::AbstractMemoryStream *pReflectionOut = nullptr; hlsl::AbstractMemoryStream *pRootSigOut = nullptr; CComPtr<IDxcBlob> pRootSigBlob = nullptr; CComPtr<IDxcBlob> pPrivateBlob = nullptr; hlsl::options::ValidatorSelection SelectValidator = hlsl::options::ValidatorSelection::Auto; }; HRESULT ValidateAndAssembleToContainer(AssembleInputs &inputs); HRESULT ValidateRootSignatureInContainer( IDxcBlob *pRootSigContainer, clang::DiagnosticsEngine *pDiag = nullptr, hlsl::options::ValidatorSelection SelectValidator = hlsl::options::ValidatorSelection::Auto); HRESULT SetRootSignature(hlsl::DxilModule *pModule, CComPtr<IDxcBlob> pSource); void GetValidatorVersion(unsigned *pMajor, unsigned *pMinor, hlsl::options::ValidatorSelection SelectValidator = hlsl::options::ValidatorSelection::Auto); void AssembleToContainer(AssembleInputs &inputs); HRESULT Disassemble(IDxcBlob *pProgram, llvm::raw_string_ostream &Stream); void ReadOptsAndValidate(hlsl::options::MainArgs &mainArgs, hlsl::options::DxcOpts &opts, hlsl::AbstractMemoryStream *pOutputStream, IDxcOperationResult **ppResult, bool &finished); void CreateOperationResultFromOutputs( DXC_OUT_KIND resultKind, UINT32 textEncoding, IDxcBlob *pResultBlob, CComPtr<IStream> &pErrorStream, const std::string &warnings, bool hasErrorOccurred, IDxcOperationResult **ppResult); void CreateOperationResultFromOutputs(IDxcBlob *pResultBlob, CComPtr<IStream> &pErrorStream, const std::string &warnings, bool hasErrorOccurred, IDxcOperationResult **ppResult); bool IsAbsoluteOrCurDirRelative(const llvm::Twine &T); } // namespace dxcutil
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxclibrary.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxclibrary.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Compiler Library helper. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/microcom.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MSFileSystem.h" #include "dxc/DXIL/DxilPDB.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/dxcapi.internal.h" #include "dxc/dxctools.h" #include <unordered_set> #include <vector> using namespace llvm; using namespace hlsl; // Temporary: Define these here until a better header location is found. namespace hlsl { HRESULT CreateDxilShaderOrLibraryReflectionFromProgramHeader( const DxilProgramHeader *pProgramHeader, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject); HRESULT CreateDxilShaderOrLibraryReflectionFromModulePart( const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject); } // namespace hlsl class DxcIncludeHandlerForFS : public IDxcIncludeHandler { private: DXC_MICROCOM_TM_REF_FIELDS() public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcIncludeHandlerForFS) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject); } HRESULT STDMETHODCALLTYPE LoadSource( LPCWSTR pFilename, // Candidate filename. IDxcBlob **ppIncludeSource // Resultant source object for included file, // nullptr if not found. ) override { try { CComPtr<IDxcBlobEncoding> pEncoding; HRESULT hr = ::hlsl::DxcCreateBlobFromFile(m_pMalloc, pFilename, nullptr, &pEncoding); if (SUCCEEDED(hr)) { *ppIncludeSource = pEncoding.Detach(); } return hr; } CATCH_CPP_RETURN_HRESULT(); } }; class DxcCompilerArgs : public IDxcCompilerArgs { private: DXC_MICROCOM_TM_REF_FIELDS() std::unordered_set<std::wstring> m_Strings; std::vector<LPCWSTR> m_Arguments; LPCWSTR AddArgument(LPCWSTR pArg) { auto it = m_Strings.insert(pArg); LPCWSTR pInternalVersion = (it.first)->c_str(); m_Arguments.push_back(pInternalVersion); return pInternalVersion; } public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcCompilerArgs) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcCompilerArgs>(this, iid, ppvObject); } // Pass GetArguments() and GetCount() to Compile LPCWSTR *STDMETHODCALLTYPE GetArguments() override { return m_Arguments.data(); } UINT32 STDMETHODCALLTYPE GetCount() override { return static_cast<UINT32>(m_Arguments.size()); } // Add additional arguments or defines here, if desired. HRESULT STDMETHODCALLTYPE AddArguments( LPCWSTR *pArguments, // Array of pointers to arguments to add UINT32 argCount // Number of arguments to add ) override { DxcThreadMalloc TM(m_pMalloc); try { for (UINT32 i = 0; i < argCount; ++i) { AddArgument(pArguments[i]); } return S_OK; } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE AddArgumentsUTF8( LPCSTR *pArguments, // Array of pointers to UTF-8 arguments to add UINT32 argCount // Number of arguments to add ) override { DxcThreadMalloc TM(m_pMalloc); try { for (UINT32 i = 0; i < argCount; ++i) { AddArgument(CA2W(pArguments[i])); } return S_OK; } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE AddDefines( const DxcDefine *pDefines, // Array of defines UINT32 defineCount // Number of defines ) override { DxcThreadMalloc TM(m_pMalloc); try { for (UINT32 i = 0; i < defineCount; ++i) { LPCWSTR Name = pDefines[i].Name; LPCWSTR Value = pDefines[i].Value; AddArgument(L"-D"); if (!Value) { // L"-D", L"<name>" AddArgument(Name); continue; } // L"-D", L"<name>=<value>" std::wstring defineArg; size_t size = 2 + wcslen(Name) + wcslen(Value); defineArg.reserve(size); defineArg = Name; defineArg += L"="; defineArg += pDefines[i].Value; AddArgument(defineArg.c_str()); } return S_OK; } CATCH_CPP_RETURN_HRESULT(); } // This is used by BuildArguments to skip extra entry/profile arguments in the // arg list when already specified separatly. This would lead to duplicate or // even contradictory arguments in the arg list, visible in debug information. HRESULT AddArgumentsOptionallySkippingEntryAndTarget( LPCWSTR *pArguments, // Array of pointers to arguments to add UINT32 argCount, // Number of arguments to add bool skipEntry, bool skipTarget) { DxcThreadMalloc TM(m_pMalloc); bool skipNext = false; for (UINT32 i = 0; i < argCount; ++i) { if (skipNext) { skipNext = false; continue; } if (skipEntry || skipTarget) { LPCWSTR arg = pArguments[i]; UINT size = wcslen(arg); if (size >= 2) { if (arg[0] == L'-' || arg[0] == L'/') { if ((skipEntry && arg[1] == L'E') || (skipTarget && arg[1] == L'T')) { skipNext = size == 2; // skip next if value not joined continue; } } } } AddArgument(pArguments[i]); } return S_OK; } }; class DxcUtils; // DxcLibrary just wraps DxcUtils now. class DxcLibrary : public IDxcLibrary { private: DxcUtils &self; public: DxcLibrary(DxcUtils &impl) : self(impl) {} ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override; HRESULT STDMETHODCALLTYPE SetMalloc(IMalloc *pMalloc) override; HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(IDxcBlob *pBlob, UINT32 offset, UINT32 length, IDxcBlob **ppResult) override; HRESULT STDMETHODCALLTYPE CreateBlobFromFile(LPCWSTR pFileName, UINT32 *pCodePage, IDxcBlobEncoding **pBlobEncoding) override; HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned(LPCVOID pText, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override; HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy(LPCVOID pText, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override; HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc( LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override; HRESULT STDMETHODCALLTYPE CreateIncludeHandler(IDxcIncludeHandler **ppResult) override; HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly(IDxcBlob *pBlob, IStream **ppStream) override; HRESULT STDMETHODCALLTYPE GetBlobAsUtf8(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) override; HRESULT STDMETHODCALLTYPE GetBlobAsWide(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) override; }; class DxcUtils : public IDxcUtils { friend class DxcLibrary; private: DXC_MICROCOM_TM_REF_FIELDS() DxcLibrary m_Library; public: DxcUtils(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_Library(*this) {} DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcUtils) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { HRESULT hr = DoBasicQueryInterface<IDxcUtils>(this, iid, ppvObject); if (FAILED(hr)) { return DoBasicQueryInterface<IDxcLibrary>(&m_Library, iid, ppvObject); } return hr; } HRESULT STDMETHODCALLTYPE CreateBlobFromBlob(IDxcBlob *pBlob, UINT32 offset, UINT32 length, IDxcBlob **ppResult) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::DxcCreateBlobFromBlob(pBlob, offset, length, ppResult); } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE CreateBlobFromPinned(LPCVOID pData, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::DxcCreateBlobWithEncodingFromPinned(pData, size, codePage, pBlobEncoding); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE MoveToBlob(LPCVOID pData, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::DxcCreateBlobWithEncodingOnMalloc(pData, pIMalloc, size, codePage, pBlobEncoding); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE CreateBlob(LPCVOID pData, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::DxcCreateBlobWithEncodingOnHeapCopy(pData, size, codePage, pBlobEncoding); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE LoadFile(LPCWSTR pFileName, UINT32 *pCodePage, IDxcBlobEncoding **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); return ::hlsl::DxcCreateBlobFromFile(pFileName, pCodePage, pBlobEncoding); } HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob(IDxcBlob *pBlob, IStream **ppStream) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::CreateReadOnlyBlobStream(pBlob, ppStream); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE CreateDefaultIncludeHandler(IDxcIncludeHandler **ppResult) override { DxcThreadMalloc TM(m_pMalloc); CComPtr<DxcIncludeHandlerForFS> result; result = DxcIncludeHandlerForFS::Alloc(m_pMalloc); if (result.p == nullptr) { return E_OUTOFMEMORY; } *ppResult = result.Detach(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8(IDxcBlob *pBlob, IDxcBlobUtf8 **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); return ::hlsl::DxcGetBlobAsUtf8(pBlob, m_pMalloc, pBlobEncoding); } virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide(IDxcBlob *pBlob, IDxcBlobWide **pBlobEncoding) override { DxcThreadMalloc TM(m_pMalloc); try { return ::hlsl::DxcGetBlobAsWide(pBlob, m_pMalloc, pBlobEncoding); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE GetDxilContainerPart(const DxcBuffer *pShader, UINT32 DxcPart, void **ppPartData, UINT32 *pPartSizeInBytes) override { if (!ppPartData || !pPartSizeInBytes) return E_INVALIDARG; const DxilContainerHeader *pHeader = IsDxilContainerLike(pShader->Ptr, pShader->Size); if (!pHeader) return DXC_E_CONTAINER_INVALID; if (!IsValidDxilContainer(pHeader, pShader->Size)) return DXC_E_CONTAINER_INVALID; DxilPartIterator it = std::find_if(begin(pHeader), end(pHeader), DxilPartIsType(DxcPart)); if (it == end(pHeader)) return DXC_E_MISSING_PART; *ppPartData = (void *)GetDxilPartData(*it); *pPartSizeInBytes = (*it)->PartSize; return S_OK; } virtual HRESULT STDMETHODCALLTYPE CreateReflection( const DxcBuffer *pData, REFIID iid, void **ppvReflection) override { if (!pData || !pData->Ptr || pData->Size < 8 || pData->Encoding != DXC_CP_ACP || !ppvReflection) return E_INVALIDARG; DxcThreadMalloc TM(m_pMalloc); try { CComPtr<IDxcBlob> pPdbContainerBlob; const DxilPartHeader *pModulePart = nullptr; const DxilPartHeader *pRDATPart = nullptr; const DxilContainerHeader *pHeader = IsDxilContainerLike(pData->Ptr, pData->Size); if (!pHeader) { CComPtr<IDxcBlobEncoding> pBlob; IFR(hlsl::DxcCreateBlobWithEncodingFromPinned(pData->Ptr, pData->Size, pData->Size, &pBlob)); CComPtr<IStream> pStream; IFR(hlsl::CreateReadOnlyBlobStream(pBlob, &pStream)); if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(m_pMalloc, pStream, &pPdbContainerBlob))) { pHeader = IsDxilContainerLike(pPdbContainerBlob->GetBufferPointer(), pPdbContainerBlob->GetBufferSize()); } } // Is this a valid DxilContainer? if (pHeader) { if (!IsValidDxilContainer(pHeader, pData->Size)) return E_INVALIDARG; const DxilPartHeader *pDXILPart = nullptr; const DxilPartHeader *pDebugDXILPart = nullptr; const DxilPartHeader *pStatsPart = nullptr; for (DxilPartIterator it = begin(pHeader), E = end(pHeader); it != E; ++it) { const DxilPartHeader *pPart = *it; switch (pPart->PartFourCC) { case DFCC_DXIL: IFRBOOL(!pDXILPart, DXC_E_DUPLICATE_PART); // Should only be one pDXILPart = pPart; break; case DFCC_ShaderDebugInfoDXIL: IFRBOOL(!pDebugDXILPart, DXC_E_DUPLICATE_PART); // Should only be one pDebugDXILPart = pPart; break; case DFCC_ShaderStatistics: IFRBOOL(!pStatsPart, DXC_E_DUPLICATE_PART); // Should only be one pStatsPart = pPart; break; case DFCC_RuntimeData: IFRBOOL(!pRDATPart, DXC_E_DUPLICATE_PART); // Should only be one pRDATPart = pPart; break; } } // For now, pStatsPart contains module without function bodies for // reflection. If not found, fall back to DXIL part. pModulePart = pStatsPart ? pStatsPart : pDebugDXILPart ? pDebugDXILPart : pDXILPart; if (nullptr == pModulePart) return DXC_E_MISSING_PART; } else if (hlsl::IsValidDxilProgramHeader( (const hlsl::DxilProgramHeader *)pData->Ptr, pData->Size)) { return hlsl::CreateDxilShaderOrLibraryReflectionFromProgramHeader( (const hlsl::DxilProgramHeader *)pData->Ptr, pRDATPart, iid, ppvReflection); } else { // Not a container, try a statistics part that holds a valid program // part. In the future, this will just be the RDAT part. const DxilPartHeader *pPart = reinterpret_cast<const DxilPartHeader *>(pData->Ptr); if (pPart->PartSize < sizeof(DxilProgramHeader) || pPart->PartSize + sizeof(DxilPartHeader) > pData->Size) return E_INVALIDARG; if (pPart->PartFourCC != DFCC_ShaderStatistics) return E_INVALIDARG; pModulePart = pPart; UINT32 SizeRemaining = pData->Size - (sizeof(DxilPartHeader) + pPart->PartSize); if (SizeRemaining > sizeof(DxilPartHeader)) { // Looks like we also have an RDAT part pPart = (const DxilPartHeader *)(GetDxilPartData(pPart) + pPart->PartSize); if (pPart->PartSize < /*sizeof(RuntimeDataHeader)*/ 8 || pPart->PartSize + sizeof(DxilPartHeader) > SizeRemaining) return E_INVALIDARG; if (pPart->PartFourCC != DFCC_RuntimeData) return E_INVALIDARG; pRDATPart = pPart; } } return hlsl::CreateDxilShaderOrLibraryReflectionFromModulePart( pModulePart, pRDATPart, iid, ppvReflection); } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE BuildArguments( LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // Entry point name. (-E) LPCWSTR pTargetProfile, // Shader profile to compile. (-T) LPCWSTR *pArguments, // Array of pointers to arguments UINT32 NumArguments, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 NumDefines, // Number of defines IDxcCompilerArgs **ppArgs // Arguments you can use with Compile() method ) override { DxcThreadMalloc TM(m_pMalloc); try { CComPtr<DxcCompilerArgs> pArgs = DxcCompilerArgs::Alloc(m_pMalloc); if (!pArgs) return E_OUTOFMEMORY; if (pSourceName) { IFR(pArgs->AddArguments(&pSourceName, 1)); } if (pEntryPoint) { if (wcslen(pEntryPoint)) { LPCWSTR args[] = {L"-E", pEntryPoint}; IFR(pArgs->AddArguments(args, _countof(args))); } else { pEntryPoint = nullptr; } } if (pTargetProfile) { if (wcslen(pTargetProfile)) { LPCWSTR args[] = {L"-T", pTargetProfile}; IFR(pArgs->AddArguments(args, _countof(args))); } else { pTargetProfile = nullptr; } } if (pArguments && NumArguments) { IFR(pArgs->AddArgumentsOptionallySkippingEntryAndTarget( pArguments, NumArguments, !!pEntryPoint, !!pTargetProfile)); } if (pDefines && NumDefines) { IFR(pArgs->AddDefines(pDefines, NumDefines)); } *ppArgs = pArgs.Detach(); return S_OK; } CATCH_CPP_RETURN_HRESULT(); } virtual HRESULT STDMETHODCALLTYPE GetPDBContents( IDxcBlob *pPDBBlob, IDxcBlob **ppHash, IDxcBlob **ppContainer) override { DxcThreadMalloc TM(m_pMalloc); try { CComPtr<IStream> pStream; IFR(hlsl::CreateReadOnlyBlobStream(pPDBBlob, &pStream)); IFR(hlsl::pdb::LoadDataFromStream(m_pMalloc, pStream, ppHash, ppContainer)); return S_OK; } CATCH_CPP_RETURN_HRESULT(); } }; ////////////////////////////////////////////////////////////// // legacy DxcLibrary implementation that maps to DxcCompiler ULONG STDMETHODCALLTYPE DxcLibrary::AddRef() { return self.AddRef(); } ULONG STDMETHODCALLTYPE DxcLibrary::Release() { return self.Release(); } HRESULT STDMETHODCALLTYPE DxcLibrary::QueryInterface(REFIID iid, void **ppvObject) { return self.QueryInterface(iid, ppvObject); } HRESULT STDMETHODCALLTYPE DxcLibrary::SetMalloc(IMalloc *pMalloc) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateBlobFromBlob(IDxcBlob *pBlob, UINT32 offset, UINT32 length, IDxcBlob **ppResult) { return self.CreateBlobFromBlob(pBlob, offset, length, ppResult); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateBlobFromFile( LPCWSTR pFileName, UINT32 *pCodePage, IDxcBlobEncoding **pBlobEncoding) { return self.LoadFile(pFileName, pCodePage, pBlobEncoding); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateBlobWithEncodingFromPinned( LPCVOID pText, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) { return self.CreateBlobFromPinned(pText, size, codePage, pBlobEncoding); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateBlobWithEncodingOnHeapCopy( LPCVOID pText, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) { return self.CreateBlob(pText, size, codePage, pBlobEncoding); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateBlobWithEncodingOnMalloc( LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, IDxcBlobEncoding **pBlobEncoding) { return self.MoveToBlob(pText, pIMalloc, size, codePage, pBlobEncoding); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateIncludeHandler(IDxcIncludeHandler **ppResult) { return self.CreateDefaultIncludeHandler(ppResult); } HRESULT STDMETHODCALLTYPE DxcLibrary::CreateStreamFromBlobReadOnly(IDxcBlob *pBlob, IStream **ppStream) { return self.CreateReadOnlyStreamFromBlob(pBlob, ppStream); } HRESULT STDMETHODCALLTYPE DxcLibrary::GetBlobAsUtf8(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) { CComPtr<IDxcBlobUtf8> pBlobUtf8; IFR(self.GetBlobAsUtf8(pBlob, &pBlobUtf8)); IFR(pBlobUtf8->QueryInterface(pBlobEncoding)); return S_OK; } HRESULT STDMETHODCALLTYPE DxcLibrary::GetBlobAsWide(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) { CComPtr<IDxcBlobWide> pBlobUtf16; IFR(self.GetBlobAsWide(pBlob, &pBlobUtf16)); IFR(pBlobUtf16->QueryInterface(pBlobEncoding)); return S_OK; } HRESULT CreateDxcCompilerArgs(REFIID riid, LPVOID *ppv) { CComPtr<DxcCompilerArgs> result = DxcCompilerArgs::Alloc(DxcGetThreadMallocNoRef()); if (result == nullptr) { *ppv = nullptr; return E_OUTOFMEMORY; } return result.p->QueryInterface(riid, ppv); } HRESULT CreateDxcUtils(REFIID riid, LPVOID *ppv) { CComPtr<DxcUtils> result = DxcUtils::Alloc(DxcGetThreadMallocNoRef()); if (result == nullptr) { *ppv = nullptr; return E_OUTOFMEMORY; } return result.p->QueryInterface(riid, ppv); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcompileradapter.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcompileradapater.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides helper code for dxcompiler. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" namespace hlsl { // This class provides an adapter for the legacy compiler interfaces // (i.e. IDxcCompiler and IDxcCompiler2) that is backed by an IDxcCompiler3 // implemenation. It allows a single core IDxcCompiler3 implementation to be // used to implement all IDxcCompiler interfaces. // // This must be owned/managed by IDxcCompiler3 instance. class DxcCompilerAdapter : public IDxcCompiler2 { private: IDxcCompiler3 *m_pCompilerImpl; IMalloc *m_pMalloc; // Internal wrapper for compile HRESULT WrapCompile( BOOL bPreprocess, // Preprocess mode IDxcBlob *pSource, // Source text to compile LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // Entry point name LPCWSTR pTargetProfile, // Shader profile to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult, // Compiler output status, buffer, and errors LPWSTR *ppDebugBlobName, // Suggested file name for debug blob. IDxcBlob **ppDebugBlob // Debug blob ); public: DxcCompilerAdapter(IDxcCompiler3 *impl, IMalloc *pMalloc) : m_pCompilerImpl(impl), m_pMalloc(pMalloc) {} ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override; // ================ IDxcCompiler ================ // Compile a single entry point to the target shader model HRESULT STDMETHODCALLTYPE Compile( IDxcBlob *pSource, // Source text to compile LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // entry point name LPCWSTR pTargetProfile, // shader profile to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult // Compiler output status, buffer, and errors ) override { return CompileWithDebug(pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult, nullptr, nullptr); } // Preprocess source text HRESULT STDMETHODCALLTYPE Preprocess( IDxcBlob *pSource, // Source text to preprocess LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult // Preprocessor output status, buffer, and errors ) override; // Disassemble a program. HRESULT STDMETHODCALLTYPE Disassemble( IDxcBlob *pSource, // Program to disassemble. IDxcBlobEncoding **ppDisassembly // Disassembly text. ) override; // ================ IDxcCompiler2 ================ // Compile a single entry point to the target shader model with debug // information. HRESULT STDMETHODCALLTYPE CompileWithDebug( IDxcBlob *pSource, // Source text to compile LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and // include handlers. LPCWSTR pEntryPoint, // Entry point name LPCWSTR pTargetProfile, // Shader profile to compile LPCWSTR *pArguments, // Array of pointers to arguments UINT32 argCount, // Number of arguments const DxcDefine *pDefines, // Array of defines UINT32 defineCount, // Number of defines IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle // #include directives (optional) IDxcOperationResult * *ppResult, // Compiler output status, buffer, and errors LPWSTR *ppDebugBlobName, // Suggested file name for debug blob. IDxcBlob **ppDebugBlob // Debug blob ) override; }; } // namespace hlsl
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. # See LICENSE.TXT for details. add_hlsl_hctgen(DxcDisassembler OUTPUT DxcDisassembler.inc BUILD_DIR) set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} analysis asmparser # asmprinter # no support for LLVM codegen bitreader bitwriter # codegen # no support for LLVM codegen core # debuginfodwarf # no support for DWARF files (IR debug info is OK) # debuginfopdb # no support for PDB files dxcsupport dxil dxilcontainer dxilpixpasses # for DxcOptimizerPass dxilrootsignature dxcbindingtable hlsl instcombine ipa ipo irreader # libdriver # lineeditor linker # lto # mirparser # no support for LLVM codegen mssupport # object # no support for object files (coff, elf) option # passes profiledata scalaropts # selectiondag # no support for LLVM codegen support target transformutils vectorize dxilcompression passprinters ) if (WIN32) set(SOURCES dxcapi.cpp dxcassembler.cpp dxclibrary.cpp dxcompilerobj.cpp dxcvalidator.cpp DXCompiler.cpp DXCompiler.rc DXCompiler.def dxcfilesystem.cpp dxillib.cpp dxcutil.cpp dxcdisassembler.cpp dxcpdbutils.cpp dxclinker.cpp dxcshadersourceinfo.cpp ) else () set(SOURCES dxcapi.cpp dxcassembler.cpp dxclibrary.cpp dxcompilerobj.cpp DXCompiler.cpp dxcfilesystem.cpp dxcutil.cpp dxcdisassembler.cpp dxcpdbutils.cpp dxillib.cpp dxcvalidator.cpp dxclinker.cpp dxcshadersourceinfo.cpp ) set (HLSL_IGNORE_SOURCES dxcdia.cpp ) endif(WIN32) set(LIBRARIES clangIndex # clangARCMigrate clangRewrite clangCodeGen clangRewriteFrontend clangFrontend clangDriver # clangSerialization clangSema clangEdit clangAST clangCodeGen clangLex clangTooling clangBasic libclang dxcvalidator ) if(WIN32) set(LIBRARIES ${LIBRARIES} LLVMDxilDia) endif(WIN32) set(GENERATED_HEADERS ClangAttrClasses ClangAttrList ClangAttrParsedAttrList ClangCommentNodes ClangDiagnosticCommon ClangDiagnosticFrontend ClangDeclNodes ClangStmtNodes ) if (MSVC) find_package(DiaSDK REQUIRED) # Used for constants and declarations. endif (MSVC) add_clang_library(dxcompiler SHARED ${SOURCES}) add_dependencies(dxcompiler TablegenHLSLOptions) if (MSVC) # No DxcEtw on non-Windows platforms. add_dependencies(dxcompiler DxcEtw) endif() target_link_libraries(dxcompiler PRIVATE ${LIBRARIES}) if (ENABLE_SPIRV_CODEGEN) target_link_libraries(dxcompiler PRIVATE clangSPIRV) endif (ENABLE_SPIRV_CODEGEN) include_directories(AFTER ${LLVM_INCLUDE_DIR}/dxc/Tracing ${DIASDK_INCLUDE_DIRS} ${HLSL_VERSION_LOCATION}) include_directories(${LLVM_SOURCE_DIR}/tools/clang/tools/dxcvalidator) set_target_properties(dxcompiler PROPERTIES OUTPUT_NAME "dxcompiler" VERSION ${LIBCLANG_LIBRARY_VERSION} DEFINE_SYMBOL _CINDEX_LIB_) if (WIN32) set(install_dest RUNTIME DESTINATION bin) else() set(install_dest LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX}) endif() install(TARGETS dxcompiler ${install_dest} COMPONENT dxcompiler) add_custom_target(install-dxcompiler DEPENDS dxcompiler COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=dxcompiler -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcvalidator.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcvalidator.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Validator object. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxcvalidator.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/Global.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO #include "clang/Basic/Version.h" #endif // SUPPORT_QUERY_GIT_COMMIT_INFO using namespace llvm; using namespace hlsl; class DxcValidator : public IDxcValidator2, #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO public IDxcVersionInfo2 #else public IDxcVersionInfo #endif // SUPPORT_QUERY_GIT_COMMIT_INFO { private: DXC_MICROCOM_TM_REF_FIELDS() public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcValidator) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcValidator, IDxcValidator2, IDxcVersionInfo>(this, iid, ppvObject); } // For internal use only. HRESULT ValidateWithOptDebugModule( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. llvm::Module *pDebugModule, // Debug module to validate, if available IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ); // IDxcValidator HRESULT STDMETHODCALLTYPE Validate( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ) override; // IDxcValidator2 HRESULT STDMETHODCALLTYPE ValidateWithDebug( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. DxcBuffer *pOptDebugBitcode, // Optional debug module bitcode to provide // line numbers IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ) override; // IDxcVersionInfo HRESULT STDMETHODCALLTYPE GetVersion(UINT32 *pMajor, UINT32 *pMinor) override; HRESULT STDMETHODCALLTYPE GetFlags(UINT32 *pFlags) override; #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO // IDxcVersionInfo2 HRESULT STDMETHODCALLTYPE GetCommitInfo(UINT32 *pCommitCount, char **pCommitHash) override; #endif }; // Compile a single entry point to the target shader model HRESULT STDMETHODCALLTYPE DxcValidator::Validate( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ) { return hlsl::validateWithDebug(pShader, Flags, nullptr, ppResult); } HRESULT STDMETHODCALLTYPE DxcValidator::ValidateWithDebug( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. DxcBuffer *pOptDebugBitcode, // Optional debug module bitcode to provide // line numbers IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ) { return hlsl::validateWithDebug(pShader, Flags, pOptDebugBitcode, ppResult); } HRESULT DxcValidator::ValidateWithOptDebugModule( IDxcBlob *pShader, // Shader to validate. UINT32 Flags, // Validation flags. llvm::Module *pDebugModule, // Debug module to validate, if available IDxcOperationResult * *ppResult // Validation output status, buffer, and errors ) { return hlsl::validateWithOptDebugModule(pShader, Flags, pDebugModule, ppResult); } HRESULT STDMETHODCALLTYPE DxcValidator::GetVersion(UINT32 *pMajor, UINT32 *pMinor) { return hlsl::getValidationVersion(pMajor, pMinor); } #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO HRESULT STDMETHODCALLTYPE DxcValidator::GetCommitInfo(UINT32 *pCommitCount, char **pCommitHash) { if (pCommitCount == nullptr || pCommitHash == nullptr) return E_INVALIDARG; char *const hash = (char *)CoTaskMemAlloc( 8 + 1); // 8 is guaranteed by utils/GetCommitInfo.py if (hash == nullptr) return E_OUTOFMEMORY; std::strcpy(hash, clang::getGitCommitHash()); *pCommitHash = hash; *pCommitCount = clang::getGitCommitCount(); return S_OK; } #endif // SUPPORT_QUERY_GIT_COMMIT_INFO HRESULT STDMETHODCALLTYPE DxcValidator::GetFlags(UINT32 *pFlags) { if (pFlags == nullptr) return E_INVALIDARG; *pFlags = DxcVersionInfoFlags_None; #ifndef NDEBUG *pFlags |= DxcVersionInfoFlags_Debug; #endif *pFlags |= DxcVersionInfoFlags_Internal; return S_OK; } /////////////////////////////////////////////////////////////////////////////// HRESULT RunInternalValidator(IDxcValidator *pValidator, llvm::Module *pDebugModule, IDxcBlob *pShader, UINT32 Flags, IDxcOperationResult **ppResult) { DXASSERT_NOMSG(pValidator != nullptr); DXASSERT_NOMSG(pShader != nullptr); DXASSERT_NOMSG(ppResult != nullptr); DxcValidator *pInternalValidator = (DxcValidator *)pValidator; return pInternalValidator->ValidateWithOptDebugModule(pShader, Flags, pDebugModule, ppResult); } HRESULT CreateDxcValidator(REFIID riid, LPVOID *ppv) { try { CComPtr<DxcValidator> result( DxcValidator::Alloc(DxcGetThreadMallocNoRef())); IFROOM(result.p); return result.p->QueryInterface(riid, ppv); } CATCH_CPP_RETURN_HRESULT(); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/DXCompiler.rc
// Copyright (c) Microsoft Corporation. All rights reserved. // #include <windows.h> #include <ntverp.h> #define VER_FILETYPE VFT_DLL #define VER_FILESUBTYPE VFT_UNKNOWN #define VER_FILEDESCRIPTION_STR "DX Compiler DLL" #define VER_INTERNALNAME_STR "DX Compiler DLL" #define VER_ORIGINALFILENAME_STR "DXCompiler.dll" // #include <common.ver> #include "dxcetw.rc"
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcdisassembler.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcdisassembler.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements Disassembler. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/Global.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "dxc/dxcapi.h" #include "dxc/DXIL/DxilConstants.h" #include "dxc/DXIL/DxilInstructions.h" #include "dxc/DXIL/DxilModule.h" #include "dxc/DXIL/DxilOperations.h" #include "dxc/DXIL/DxilPDB.h" #include "dxc/DXIL/DxilResource.h" #include "dxc/DXIL/DxilResourceProperties.h" #include "dxc/DXIL/DxilShaderModel.h" #include "dxc/DXIL/DxilUtil.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/DxilContainer/DxilPipelineStateValidation.h" #include "dxc/DxilContainer/DxilRuntimeReflection.h" #include "dxc/HLSL/ComputeViewIdState.h" #include "dxc/HLSL/HLMatrixType.h" #include "dxc/Support/FileIOHelper.h" #include "dxcutil.h" #include "llvm/IR/AssemblyAnnotationWriter.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormattedStream.h" #include <assert.h> // Needed for DxilPipelineStateValidation.h using namespace llvm; using namespace hlsl; using namespace hlsl::DXIL; namespace { // Disassemble helper functions. template <typename T> const T *ByteOffset(LPCVOID p, uint32_t byteOffset) { return reinterpret_cast<const T *>((const uint8_t *)p + byteOffset); } bool SigElementHasStream(const DxilProgramSignatureElement &pSignature) { return pSignature.Stream != 0; } void PrintSignature(LPCSTR pName, const DxilProgramSignature *pSignature, bool bIsInput, raw_string_ostream &OS, StringRef comment) { OS << comment << "\n" << comment << " " << pName << " signature:\n" << comment << "\n" << comment << " Name Index Mask Register SysValue Format Used\n" << comment << " -------------------- ----- ------ -------- -------- ------- ------\n"; if (pSignature->ParamCount == 0) { OS << comment << " no parameters\n"; return; } const DxilProgramSignatureElement *pSigBegin = ByteOffset<DxilProgramSignatureElement>(pSignature, pSignature->ParamOffset); const DxilProgramSignatureElement *pSigEnd = pSigBegin + pSignature->ParamCount; bool bHasStreams = std::any_of(pSigBegin, pSigEnd, SigElementHasStream); for (const DxilProgramSignatureElement *pSig = pSigBegin; pSig != pSigEnd; ++pSig) { OS << comment << " "; const char *pSemanticName = ByteOffset<char>(pSignature, pSig->SemanticName); if (bHasStreams) { OS << "m" << pSig->Stream << ":"; OS << left_justify(pSemanticName, 17); } else { OS << left_justify(pSemanticName, 20); } OS << ' ' << format("%5u", pSig->SemanticIndex); char Mask[4]; memset(Mask, ' ', sizeof(Mask)); if (pSig->Mask & DxilProgramSigMaskX) Mask[0] = 'x'; if (pSig->Mask & DxilProgramSigMaskY) Mask[1] = 'y'; if (pSig->Mask & DxilProgramSigMaskZ) Mask[2] = 'z'; if (pSig->Mask & DxilProgramSigMaskW) Mask[3] = 'w'; if (pSig->Register == (unsigned)-1) { OS << " N/A"; if (!_stricmp(pSemanticName, "SV_Depth")) OS << " oDepth"; else if (0 == _stricmp(pSemanticName, "SV_DepthGreaterEqual")) OS << " oDepthGE"; else if (0 == _stricmp(pSemanticName, "SV_DepthLessEqual")) OS << " oDepthLE"; else if (0 == _stricmp(pSemanticName, "SV_Coverage")) OS << " oMask"; else if (0 == _stricmp(pSemanticName, "SV_StencilRef")) OS << " oStencilRef"; else if (pSig->SystemValue == DxilProgramSigSemantic::PrimitiveID) OS << " primID"; else OS << " special"; } else { OS << " " << Mask[0] << Mask[1] << Mask[2] << Mask[3]; OS << ' ' << format("%8u", pSig->Register); } LPCSTR pSysValue = "NONE"; switch (pSig->SystemValue) { case DxilProgramSigSemantic::ClipDistance: pSysValue = "CLIPDST"; break; case DxilProgramSigSemantic::CullDistance: pSysValue = "CULLDST"; break; case DxilProgramSigSemantic::Position: pSysValue = "POS"; break; case DxilProgramSigSemantic::RenderTargetArrayIndex: pSysValue = "RTINDEX"; break; case DxilProgramSigSemantic::ViewPortArrayIndex: pSysValue = "VPINDEX"; break; case DxilProgramSigSemantic::VertexID: pSysValue = "VERTID"; break; case DxilProgramSigSemantic::PrimitiveID: pSysValue = "PRIMID"; break; case DxilProgramSigSemantic::InstanceID: pSysValue = "INSTID"; break; case DxilProgramSigSemantic::IsFrontFace: pSysValue = "FFACE"; break; case DxilProgramSigSemantic::SampleIndex: pSysValue = "SAMPLE"; break; case DxilProgramSigSemantic::Target: pSysValue = "TARGET"; break; case DxilProgramSigSemantic::Depth: pSysValue = "DEPTH"; break; case DxilProgramSigSemantic::DepthGE: pSysValue = "DEPTHGE"; break; case DxilProgramSigSemantic::DepthLE: pSysValue = "DEPTHLE"; break; case DxilProgramSigSemantic::Coverage: pSysValue = "COVERAGE"; break; case DxilProgramSigSemantic::InnerCoverage: pSysValue = "INNERCOV"; break; case DxilProgramSigSemantic::StencilRef: pSysValue = "STENCILREF"; break; case DxilProgramSigSemantic::FinalQuadEdgeTessfactor: pSysValue = "QUADEDGE"; break; case DxilProgramSigSemantic::FinalQuadInsideTessfactor: pSysValue = "QUADINT"; break; case DxilProgramSigSemantic::FinalTriEdgeTessfactor: pSysValue = "TRIEDGE"; break; case DxilProgramSigSemantic::FinalTriInsideTessfactor: pSysValue = "TRIINT"; break; case DxilProgramSigSemantic::FinalLineDetailTessfactor: pSysValue = "LINEDET"; break; case DxilProgramSigSemantic::FinalLineDensityTessfactor: pSysValue = "LINEDEN"; break; case DxilProgramSigSemantic::Barycentrics: pSysValue = "BARYCEN"; break; case DxilProgramSigSemantic::ShadingRate: pSysValue = "SHDINGRATE"; break; case DxilProgramSigSemantic::CullPrimitive: pSysValue = "CULLPRIM"; break; case DxilProgramSigSemantic::Undefined: break; } OS << right_justify(pSysValue, 9); LPCSTR pFormat = "unknown"; switch (pSig->CompType) { case DxilProgramSigCompType::Float32: pFormat = "float"; break; case DxilProgramSigCompType::SInt32: pFormat = "int"; break; case DxilProgramSigCompType::UInt32: pFormat = "uint"; break; case DxilProgramSigCompType::UInt16: pFormat = "uint16"; break; case DxilProgramSigCompType::SInt16: pFormat = "int16"; break; case DxilProgramSigCompType::Float16: pFormat = "fp16"; break; case DxilProgramSigCompType::UInt64: pFormat = "uint64"; break; case DxilProgramSigCompType::SInt64: pFormat = "int64"; break; case DxilProgramSigCompType::Float64: pFormat = "double"; break; case DxilProgramSigCompType::Unknown: break; } OS << right_justify(pFormat, 8); memset(Mask, ' ', sizeof(Mask)); BYTE rwMask = pSig->AlwaysReads_Mask; if (!bIsInput) rwMask = ~rwMask; if (rwMask & DxilProgramSigMaskX) Mask[0] = 'x'; if (rwMask & DxilProgramSigMaskY) Mask[1] = 'y'; if (rwMask & DxilProgramSigMaskZ) Mask[2] = 'z'; if (rwMask & DxilProgramSigMaskW) Mask[3] = 'w'; if (pSig->Register == (unsigned)-1) OS << (rwMask ? " YES" : " NO"); else OS << " " << Mask[0] << Mask[1] << Mask[2] << Mask[3]; OS << "\n"; } OS << comment << "\n"; } void PintCompMaskNameCompact(raw_string_ostream &OS, unsigned CompMask) { char Mask[5]; memset(Mask, '\0', sizeof(Mask)); unsigned idx = 0; if (CompMask & DxilProgramSigMaskX) Mask[idx++] = 'x'; if (CompMask & DxilProgramSigMaskY) Mask[idx++] = 'y'; if (CompMask & DxilProgramSigMaskZ) Mask[idx++] = 'z'; if (CompMask & DxilProgramSigMaskW) Mask[idx++] = 'w'; OS << right_justify(Mask, 4); } void PrintDxilSignature(LPCSTR pName, const DxilSignature &Signature, raw_string_ostream &OS, StringRef comment) { const std::vector<std::unique_ptr<DxilSignatureElement>> &sigElts = Signature.GetElements(); if (sigElts.size() == 0) return; // TODO: Print all the data in DxilSignature. OS << comment << "\n" << comment << " " << pName << " signature:\n" << comment << "\n" << comment << " Name Index InterpMode DynIdx\n" << comment << " -------------------- ----- ---------------------- ------\n"; for (auto &sigElt : sigElts) { OS << comment << " "; OS << left_justify(sigElt->GetName(), 20); auto &indexVec = sigElt->GetSemanticIndexVec(); unsigned index = 0; if (!indexVec.empty()) { index = sigElt->GetSemanticIndexVec()[0]; } OS << ' ' << format("%5u", index); sigElt->GetInterpolationMode()->GetName(); OS << ' ' << right_justify(sigElt->GetInterpolationMode()->GetName(), 22); OS << " "; PintCompMaskNameCompact(OS, sigElt->GetDynIdxCompMask()); OS << "\n"; } } PCSTR g_pFeatureInfoNames[] = { "Double-precision floating point", "Raw and Structured buffers", "UAVs at every shader stage", "64 UAV slots", "Minimum-precision data types", "Double-precision extensions for 11.1", "Shader extensions for 11.1", "Comparison filtering for feature level 9", "Tiled resources", "PS Output Stencil Ref", "PS Inner Coverage", "Typed UAV Load Additional Formats", "Raster Ordered UAVs", ("SV_RenderTargetArrayIndex or SV_ViewportArrayIndex from any shader " "feeding rasterizer"), "Wave level operations", "64-Bit integer", "View Instancing", "Barycentrics", "Use native low precision", "Shading Rate", "Raytracing tier 1.1 features", "Sampler feedback", "64-bit Atomics on Typed Resources", "64-bit Atomics on Group Shared", "Derivatives in mesh and amplification shaders", "Resource descriptor heap indexing", "Sampler descriptor heap indexing", "Wave Matrix", "64-bit Atomics on Heap Resources", "Advanced Texture Ops", "Writeable MSAA Textures", "SampleCmp with gradient or bias", "Extended command info", }; static_assert(_countof(g_pFeatureInfoNames) == ShaderFeatureInfoCount, "g_pFeatureInfoNames needs to be updated"); PCSTR g_pOptFeatureInfoNames[] = { "Function uses derivatives", "Function requires visible group", }; static_assert(_countof(g_pOptFeatureInfoNames) == OptFeatureInfoCount, "g_pOptFeatureInfoNames needs to be updated"); void PrintFeatureInfo(const DxilShaderFeatureInfo *pFeatureInfo, raw_string_ostream &OS, StringRef comment) { uint64_t featureFlags = pFeatureInfo->FeatureFlags; if (!featureFlags) return; OS << comment << "\n"; OS << comment << " Note: shader requires additional functionality:\n"; for (unsigned i = 0; i < ShaderFeatureInfoCount; i++) { if (featureFlags & (((uint64_t)1) << i)) OS << comment << " " << g_pFeatureInfoNames[i] << "\n"; } OS << comment << "\n"; uint64_t optFeatureFlags = featureFlags >> OptFeatureInfoShift; if (!optFeatureFlags) return; OS << comment << " Note: shader has optional feature flags set:\n"; for (unsigned i = 0; i < OptFeatureInfoCount; i++) { if (optFeatureFlags & (((uint64_t)1) << i)) OS << comment << " " << g_pOptFeatureInfoNames[i] << "\n"; } OS << comment << "\n"; } void PrintResourceFormat(DxilResourceBase &res, unsigned alignment, raw_string_ostream &OS) { switch (res.GetClass()) { case DxilResourceBase::Class::CBuffer: case DxilResourceBase::Class::Sampler: OS << right_justify("NA", alignment); break; case DxilResourceBase::Class::UAV: case DxilResourceBase::Class::SRV: switch (res.GetKind()) { case DxilResource::Kind::RawBuffer: OS << right_justify("byte", alignment); break; case DxilResource::Kind::StructuredBuffer: OS << right_justify("struct", alignment); break; default: DxilResource *pRes = static_cast<DxilResource *>(&res); CompType &&compType = pRes->GetCompType(); const char *compName = compType.GetName(); // TODO: add vector size. OS << right_justify(compName, alignment); break; } break; case DxilResource::Class::Invalid: break; } } void PrintResourceDim(DxilResourceBase &res, unsigned alignment, raw_string_ostream &OS) { switch (res.GetClass()) { case DxilResourceBase::Class::CBuffer: case DxilResourceBase::Class::Sampler: OS << right_justify("NA", alignment); break; case DxilResourceBase::Class::UAV: case DxilResourceBase::Class::SRV: switch (res.GetKind()) { case DxilResource::Kind::RawBuffer: case DxilResource::Kind::StructuredBuffer: if (res.GetClass() == DxilResourceBase::Class::SRV) OS << right_justify("r/o", alignment); else { DxilResource &dxilRes = static_cast<DxilResource &>(res); if (!dxilRes.HasCounter()) OS << right_justify("r/w", alignment); else OS << right_justify("r/w+cnt", alignment); } break; case DxilResource::Kind::TypedBuffer: OS << right_justify("buf", alignment); break; case DxilResource::Kind::Texture2DMS: case DxilResource::Kind::Texture2DMSArray: { DxilResource *pRes = static_cast<DxilResource *>(&res); std::string dimName = res.GetResDimName(); if (pRes->GetSampleCount()) dimName += std::to_string(pRes->GetSampleCount()); OS << right_justify(dimName, alignment); } break; default: OS << right_justify(res.GetResDimName(), alignment); break; } break; case DxilResourceBase::Class::Invalid: break; } } void PrintResourceBinding(DxilResourceBase &res, raw_string_ostream &OS, StringRef comment) { OS << comment << " " << left_justify(res.GetGlobalName(), 31); OS << right_justify(res.GetResClassName(), 10); PrintResourceFormat(res, 8, OS); PrintResourceDim(res, 12, OS); std::string ID = res.GetResIDPrefix(); ID += std::to_string(res.GetID()); OS << right_justify(ID, 8); std::string bind = res.GetResBindPrefix(); bind += std::to_string(res.GetLowerBound()); if (res.GetSpaceID()) bind += ",space" + std::to_string(res.GetSpaceID()); OS << right_justify(bind, 15); if (res.GetRangeSize() != UINT_MAX) OS << right_justify(std::to_string(res.GetRangeSize()), 6) << "\n"; else OS << right_justify("unbounded", 6) << "\n"; } void PrintResourceBindings(DxilModule &M, raw_string_ostream &OS, StringRef comment) { OS << comment << "\n" << comment << " Resource Bindings:\n" << comment << "\n" << comment << " Name Type Format Dim " "ID HLSL Bind Count\n" << comment << " ------------------------------ ---------- ------- ----------- " "------- -------------- ------\n"; for (auto &res : M.GetCBuffers()) { PrintResourceBinding(*res.get(), OS, comment); } for (auto &res : M.GetSamplers()) { PrintResourceBinding(*res.get(), OS, comment); } for (auto &res : M.GetSRVs()) { PrintResourceBinding(*res.get(), OS, comment); } for (auto &res : M.GetUAVs()) { PrintResourceBinding(*res.get(), OS, comment); } OS << comment << "\n"; } void PrintOutputsDependentOnViewId( llvm::raw_ostream &OS, llvm::StringRef comment, llvm::StringRef SetName, unsigned NumOutputs, const DxilViewIdState::OutputsDependentOnViewIdType &OutputsDependentOnViewId) { OS << comment << " " << SetName << " dependent on ViewId: { "; bool bFirst = true; for (unsigned i = 0; i < NumOutputs; i++) { if (OutputsDependentOnViewId[i]) { if (!bFirst) OS << ", "; OS << i; bFirst = false; } } OS << " }\n"; } void PrintInputsContributingToOutputs( llvm::raw_ostream &OS, llvm::StringRef comment, llvm::StringRef InputSetName, llvm::StringRef OutputSetName, const DxilViewIdState::InputsContributingToOutputType &InputsContributingToOutputs) { OS << comment << " " << InputSetName << " contributing to computation of " << OutputSetName << ":\n"; for (auto &it : InputsContributingToOutputs) { unsigned outIdx = it.first; auto &Inputs = it.second; OS << comment << " output " << outIdx << " depends on inputs: { "; bool bFirst = true; for (unsigned i : Inputs) { if (!bFirst) OS << ", "; OS << i; bFirst = false; } OS << " }\n"; } } void PrintViewIdState(DxilModule &M, raw_string_ostream &OS, StringRef comment) { if (!M.GetModule()->getNamedMetadata("dx.viewIdState")) return; const ShaderModel *pSM = M.GetShaderModel(); DxilViewIdState VID(&M); auto &SerializedVID = M.GetSerializedViewIdState(); VID.Deserialize(SerializedVID.data(), SerializedVID.size()); OS << comment << "\n"; OS << comment << " ViewId state:\n"; OS << comment << "\n"; OS << comment << " Number of inputs: " << VID.getNumInputSigScalars(); if (!pSM->IsGS()) { OS << ", outputs: " << VID.getNumOutputSigScalars(0); } else { OS << ", outputs per stream: { " << VID.getNumOutputSigScalars(0) << ", " << VID.getNumOutputSigScalars(1) << ", " << VID.getNumOutputSigScalars(2) << ", " << VID.getNumOutputSigScalars(3) << " }"; } if (pSM->IsHS() || pSM->IsDS()) { OS << ", patchconst: " << VID.getNumPCSigScalars(); } else if (pSM->IsMS()) { OS << ", primitive outputs: " << VID.getNumPCSigScalars(); } OS << "\n"; if (!pSM->IsGS()) { PrintOutputsDependentOnViewId(OS, comment, "Outputs", VID.getNumOutputSigScalars(0), VID.getOutputsDependentOnViewId(0)); } else { for (unsigned i = 0; i < 4; i++) { if (VID.getNumOutputSigScalars(i) > 0) { std::string OutputsName = std::string("Outputs for Stream ") + std::to_string(i); PrintOutputsDependentOnViewId(OS, comment, OutputsName, VID.getNumOutputSigScalars(i), VID.getOutputsDependentOnViewId(i)); } } } if (pSM->IsHS()) { PrintOutputsDependentOnViewId(OS, comment, "PCOutputs", VID.getNumPCSigScalars(), VID.getPCOutputsDependentOnViewId()); } else if (pSM->IsMS()) { PrintOutputsDependentOnViewId(OS, comment, "Primitive Outputs", VID.getNumPCSigScalars(), VID.getPCOutputsDependentOnViewId()); } if (!pSM->IsGS()) { PrintInputsContributingToOutputs(OS, comment, "Inputs", "Outputs", VID.getInputsContributingToOutputs(0)); } else { for (unsigned i = 0; i < 4; i++) { if (VID.getNumOutputSigScalars(i) > 0) { std::string OutputsName = std::string("Outputs for Stream ") + std::to_string(i); PrintInputsContributingToOutputs(OS, comment, "Inputs", OutputsName, VID.getInputsContributingToOutputs(i)); } } } if (pSM->IsHS()) { PrintInputsContributingToOutputs(OS, comment, "Inputs", "PCOutputs", VID.getInputsContributingToPCOutputs()); } else if (pSM->IsMS()) { PrintInputsContributingToOutputs(OS, comment, "Inputs", "Primitive Outputs", VID.getInputsContributingToPCOutputs()); } else if (pSM->IsDS()) { PrintInputsContributingToOutputs(OS, comment, "PCInputs", "Outputs", VID.getPCInputsContributingToOutputs()); } OS << comment << "\n"; } static const char *SubobjectKindToString(DXIL::SubobjectKind kind) { switch (kind) { case DXIL::SubobjectKind::StateObjectConfig: return "StateObjectConfig"; case DXIL::SubobjectKind::GlobalRootSignature: return "GlobalRootSignature"; case DXIL::SubobjectKind::LocalRootSignature: return "LocalRootSignature"; case DXIL::SubobjectKind::SubobjectToExportsAssociation: return "SubobjectToExportsAssociation"; case DXIL::SubobjectKind::RaytracingShaderConfig: return "RaytracingShaderConfig"; case DXIL::SubobjectKind::RaytracingPipelineConfig: return "RaytracingPipelineConfig"; case DXIL::SubobjectKind::HitGroup: return "HitGroup"; case DXIL::SubobjectKind::RaytracingPipelineConfig1: return "RaytracingPipelineConfig1"; } return "<invalid kind>"; } static const char *FlagToString(DXIL::StateObjectFlags Flag) { switch (Flag) { case DXIL::StateObjectFlags::AllowLocalDependenciesOnExternalDefinitions: return "STATE_OBJECT_FLAG_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITIONS"; case DXIL::StateObjectFlags::AllowExternalDependenciesOnLocalDefinitions: return "STATE_OBJECT_FLAG_ALLOW_EXTERNAL_DEPENDENCIES_ON_LOCAL_DEFINITIONS"; case DXIL::StateObjectFlags::AllowStateObjectAdditions: return "STATE_OBJECT_FLAG_ALLOW_STATE_OBJECT_ADDITIONS"; } return "<invalid StateObjectFlag>"; } static const char *FlagToString(DXIL::RaytracingPipelineFlags Flag) { switch (Flag) { case DXIL::RaytracingPipelineFlags::None: return "RAYTRACING_PIPELINE_FLAG_NONE"; case DXIL::RaytracingPipelineFlags::SkipTriangles: return "RAYTRACING_PIPELINE_FLAG_SKIP_TRIANGLES"; case DXIL::RaytracingPipelineFlags::SkipProceduralPrimitives: return "RAYTRACING_PIPELINE_FLAG_SKIP_PROCEDURAL_PRIMITIVES"; } return "<invalid RaytracingPipelineFlags>"; } static const char *HitGroupTypeToString(DXIL::HitGroupType type) { switch (type) { case DXIL::HitGroupType::Triangle: return "Triangle"; case DXIL::HitGroupType::ProceduralPrimitive: return "ProceduralPrimitive"; } return "<invalid HitGroupType>"; } template <typename _T> void PrintFlags(raw_string_ostream &OS, uint32_t Flags) { if (!Flags) { OS << "0"; return; } uint32_t flag = 0; while (Flags) { if (flag) OS << " | "; flag = (Flags & ~(Flags - 1)); Flags ^= flag; OS << FlagToString((_T)flag); } } void PrintSubobjects(const DxilSubobjects &subobjects, raw_string_ostream &OS, StringRef comment) { if (subobjects.GetSubobjects().empty()) return; OS << comment << "\n"; OS << comment << " Subobjects:\n"; OS << comment << "\n"; for (auto &it : subobjects.GetSubobjects()) { StringRef name = it.first; if (!it.second) { OS << comment << " " << name << " = <null>" << "\n"; continue; } const DxilSubobject &obj = *it.second.get(); OS << comment << " " << SubobjectKindToString(obj.GetKind()) << " " << name << " = " << "{ "; bool bLocalRS = false; switch (obj.GetKind()) { case DXIL::SubobjectKind::StateObjectConfig: { uint32_t Flags = 0; if (!obj.GetStateObjectConfig(Flags)) { OS << "<error getting subobject>"; break; } PrintFlags<DXIL::StateObjectFlags>(OS, Flags); break; } case DXIL::SubobjectKind::LocalRootSignature: bLocalRS = true; LLVM_FALLTHROUGH; case DXIL::SubobjectKind::GlobalRootSignature: { const char *Text = nullptr; const void *Data = nullptr; uint32_t Size = 0; if (!obj.GetRootSignature(bLocalRS, Data, Size, &Text)) { OS << "<error getting subobject>"; break; } OS << "<" << Size << " bytes>"; if (Text && Text[0]) { OS << ", \"" << Text << "\""; } break; } case DXIL::SubobjectKind::SubobjectToExportsAssociation: { llvm::StringRef Subobject; const char *const *Exports = nullptr; uint32_t NumExports; if (!obj.GetSubobjectToExportsAssociation(Subobject, Exports, NumExports)) { OS << "<error getting subobject>"; break; } OS << "\"" << Subobject << "\", { "; if (Exports) { for (unsigned i = 0; i < NumExports; ++i) { OS << (i ? ", " : "") << "\"" << Exports[i] << "\""; } } OS << " } "; break; } case DXIL::SubobjectKind::RaytracingShaderConfig: { uint32_t MaxPayloadSizeInBytes; uint32_t MaxAttributeSizeInBytes; if (!obj.GetRaytracingShaderConfig(MaxPayloadSizeInBytes, MaxAttributeSizeInBytes)) { OS << "<error getting subobject>"; break; } OS << "MaxPayloadSizeInBytes = " << MaxPayloadSizeInBytes << ", MaxAttributeSizeInBytes = " << MaxAttributeSizeInBytes; break; } case DXIL::SubobjectKind::RaytracingPipelineConfig: { uint32_t MaxTraceRecursionDepth; if (!obj.GetRaytracingPipelineConfig(MaxTraceRecursionDepth)) { OS << "<error getting subobject>"; break; } OS << "MaxTraceRecursionDepth = " << MaxTraceRecursionDepth; break; } case DXIL::SubobjectKind::HitGroup: { HitGroupType hgType; StringRef AnyHit; StringRef ClosestHit; StringRef Intersection; if (!obj.GetHitGroup(hgType, AnyHit, ClosestHit, Intersection)) { OS << "<error getting subobject>"; break; } OS << "HitGroupType = " << HitGroupTypeToString(hgType) << ", Anyhit = \"" << AnyHit << "\", Closesthit = \"" << ClosestHit << "\", Intersection = \"" << Intersection << "\""; break; } case DXIL::SubobjectKind::RaytracingPipelineConfig1: { uint32_t MaxTraceRecursionDepth; uint32_t Flags; if (!obj.GetRaytracingPipelineConfig1(MaxTraceRecursionDepth, Flags)) { OS << "<error getting subobject>"; break; } OS << "MaxTraceRecursionDepth = " << MaxTraceRecursionDepth; OS << ", Flags = "; PrintFlags<DXIL::RaytracingPipelineFlags>(OS, Flags); break; } } OS << " };\n"; } OS << comment << "\n"; } void PrintStructLayout(StructType *ST, DxilTypeSystem &typeSys, const DataLayout *DL, raw_string_ostream &OS, StringRef comment, StringRef varName, unsigned offset, unsigned indent, unsigned arraySize, unsigned sizeOfStruct = 0); void PrintTypeAndName(llvm::Type *Ty, DxilFieldAnnotation &annotation, std::string &StreamStr, unsigned arraySize, bool minPrecision) { raw_string_ostream Stream(StreamStr); while (Ty->isArrayTy()) Ty = Ty->getArrayElementType(); const char *compTyName = annotation.GetCompType().GetHLSLName(minPrecision); if (annotation.HasMatrixAnnotation()) { const DxilMatrixAnnotation &Matrix = annotation.GetMatrixAnnotation(); switch (Matrix.Orientation) { case MatrixOrientation::RowMajor: Stream << "row_major "; break; case MatrixOrientation::ColumnMajor: Stream << "column_major "; break; case MatrixOrientation::Undefined: case MatrixOrientation::LastEntry: break; } Stream << compTyName << Matrix.Rows << "x" << Matrix.Cols; } else if (Ty->isVectorTy()) Stream << compTyName << Ty->getVectorNumElements(); else Stream << compTyName; Stream << " " << annotation.GetFieldName(); if (arraySize) Stream << "[" << arraySize << "]"; Stream << ";"; Stream.flush(); } void PrintFieldLayout(llvm::Type *Ty, DxilFieldAnnotation &annotation, DxilTypeSystem &typeSys, const DataLayout *DL, raw_string_ostream &OS, StringRef comment, unsigned offset, unsigned indent, unsigned offsetIndent, unsigned sizeToPrint = 0) { if (Ty->isStructTy() && !annotation.HasMatrixAnnotation()) { PrintStructLayout(cast<StructType>(Ty), typeSys, DL, OS, comment, annotation.GetFieldName(), offset, indent, offsetIndent); } else { llvm::Type *EltTy = Ty; unsigned arraySize = 0; unsigned arrayLevel = 0; if (!HLMatrixType::isa(EltTy) && EltTy->isArrayTy()) { arraySize = 1; while (!HLMatrixType::isa(EltTy) && EltTy->isArrayTy()) { arraySize *= EltTy->getArrayNumElements(); EltTy = EltTy->getArrayElementType(); arrayLevel++; } } if (annotation.HasMatrixAnnotation()) { const DxilMatrixAnnotation &Matrix = annotation.GetMatrixAnnotation(); switch (Matrix.Orientation) { case MatrixOrientation::RowMajor: arraySize /= Matrix.Rows; break; case MatrixOrientation::ColumnMajor: arraySize /= Matrix.Cols; break; case MatrixOrientation::Undefined: case MatrixOrientation::LastEntry: break; } if (EltTy->isVectorTy()) { EltTy = EltTy->getVectorElementType(); } else if (EltTy->isStructTy()) EltTy = HLMatrixType::cast(EltTy).getElementTypeForReg(); if (arrayLevel == 1) arraySize = 0; } std::string StreamStr; if (!HLMatrixType::isa(EltTy) && EltTy->isStructTy()) { std::string NameTypeStr = annotation.GetFieldName(); raw_string_ostream Stream(NameTypeStr); if (arraySize) Stream << "[" << std::to_string(arraySize) << "]"; Stream << ";"; Stream.flush(); PrintStructLayout(cast<StructType>(EltTy), typeSys, DL, OS, comment, NameTypeStr, offset, indent, offsetIndent); } else { (OS << comment).indent(indent); std::string NameTypeStr; PrintTypeAndName(Ty, annotation, NameTypeStr, arraySize, typeSys.UseMinPrecision()); OS << left_justify(NameTypeStr, offsetIndent); // Offset OS << comment << " Offset:" << right_justify(std::to_string(offset), 5); if (sizeToPrint) OS << " Size: " << right_justify(std::to_string(sizeToPrint), 5); OS << "\n"; } } } // null DataLayout => assume constant buffer layout void PrintStructLayout(StructType *ST, DxilTypeSystem &typeSys, const DataLayout *DL, raw_string_ostream &OS, StringRef comment, StringRef varName, unsigned offset, unsigned indent, unsigned offsetIndent, unsigned sizeOfStruct) { DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST); (OS << comment).indent(indent) << "struct " << ST->getName() << "\n"; (OS << comment).indent(indent) << "{\n"; OS << comment << "\n"; unsigned fieldIndent = indent + 4; if (!annotation) { if (!sizeOfStruct) { (OS << comment).indent(fieldIndent) << "/* empty struct */\n"; } else { (OS << comment).indent(fieldIndent) << "[" << sizeOfStruct << " x i8] (type annotation not present)\n"; } } else { for (unsigned i = 0; i < ST->getNumElements(); i++) { DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i); unsigned int fieldOffset; if (DL == nullptr) { // Constant buffer data layout fieldOffset = offset + fieldAnnotation.GetCBufferOffset(); } else { // Normal data layout fieldOffset = offset + DL->getStructLayout(ST)->getElementOffset(i); } PrintFieldLayout(ST->getElementType(i), fieldAnnotation, typeSys, DL, OS, comment, fieldOffset, fieldIndent, offsetIndent - 4); } } (OS << comment).indent(indent) << "\n"; // The 2 in offsetIndent-indent-2 is for "} ". std::string varNameAndSemicolon = varName; varNameAndSemicolon += ';'; (OS << comment).indent(indent) << "} " << left_justify(varNameAndSemicolon, offsetIndent - 2); OS << comment << " Offset:" << right_justify(std::to_string(offset), 5); if (sizeOfStruct) OS << " Size: " << right_justify(std::to_string(sizeOfStruct), 5); OS << "\n"; OS << comment << "\n"; } void PrintStructBufferDefinition(DxilResource *buf, DxilTypeSystem &typeSys, const DataLayout &DL, raw_string_ostream &OS, StringRef comment) { const unsigned offsetIndent = 50; OS << comment << " Resource bind info for " << buf->GetGlobalName() << "\n"; OS << comment << " {\n"; OS << comment << "\n"; llvm::Type *RetTy = buf->GetRetType(); // Skip none struct type. if (!RetTy->isStructTy() || HLMatrixType::isa(RetTy)) { llvm::Type *Ty = buf->GetHLSLType()->getPointerElementType(); // For resource array, use element type. while (Ty->isArrayTy()) Ty = Ty->getArrayElementType(); // Get the struct buffer type like this %class.StructuredBuffer = type { // %struct.mat }. StructType *ST = cast<StructType>(Ty); DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST); if (nullptr == annotation) { OS << comment << " [" << DL.getTypeAllocSize(ST) << " x i8] (type annotation not present)\n"; } else { DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(0); fieldAnnotation.SetFieldName("$Element"); PrintFieldLayout( RetTy, fieldAnnotation, typeSys, /*DL*/ nullptr, OS, comment, /*offset*/ 0, /*indent*/ 3, offsetIndent, DL.getTypeAllocSize(ST)); } OS << comment << "\n"; } else { StructType *ST = cast<StructType>(RetTy); DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST); if (nullptr == annotation) { OS << comment << " [" << DL.getTypeAllocSize(ST) << " x i8] (type annotation not present)\n"; } else { PrintStructLayout(ST, typeSys, &DL, OS, comment, "$Element", /*offset*/ 0, /*indent*/ 3, offsetIndent, DL.getTypeAllocSize(ST)); } } OS << comment << " }\n"; OS << comment << "\n"; } void PrintTBufferDefinition(DxilResource *buf, DxilTypeSystem &typeSys, raw_string_ostream &OS, StringRef comment) { const unsigned offsetIndent = 50; llvm::Type *Ty = buf->GetHLSLType()->getPointerElementType(); // For TextureBuffer<> buf[2], the array size is in Resource binding count // part. if (Ty->isArrayTy()) Ty = Ty->getArrayElementType(); DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(cast<StructType>(Ty)); OS << comment << " tbuffer " << buf->GetGlobalName() << "\n"; OS << comment << " {\n"; OS << comment << "\n"; if (nullptr == annotation) { OS << comment << " (type annotation not present)\n"; OS << comment << "\n"; } else { PrintStructLayout(cast<StructType>(Ty), typeSys, /*DL*/ nullptr, OS, comment, buf->GetGlobalName(), /*offset*/ 0, /*indent*/ 3, offsetIndent, annotation->GetCBufferSize()); } OS << comment << " }\n"; OS << comment << "\n"; } void PrintCBufferDefinition(DxilCBuffer *buf, DxilTypeSystem &typeSys, raw_string_ostream &OS, StringRef comment) { const unsigned offsetIndent = 50; llvm::Type *Ty = buf->GetHLSLType()->getPointerElementType(); // For ConstantBuffer<> buf[2], the array size is in Resource binding count // part. if (Ty->isArrayTy()) Ty = Ty->getArrayElementType(); DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(cast<StructType>(Ty)); OS << comment << " cbuffer " << buf->GetGlobalName() << "\n"; OS << comment << " {\n"; OS << comment << "\n"; if (nullptr == annotation) { OS << comment << " [" << buf->GetSize() << " x i8] (type annotation not present)\n"; OS << comment << "\n"; } else { PrintStructLayout(cast<StructType>(Ty), typeSys, /*DL*/ nullptr, OS, comment, buf->GetGlobalName(), /*offset*/ 0, /*indent*/ 3, offsetIndent, buf->GetSize()); } OS << comment << " }\n"; OS << comment << "\n"; } void PrintBufferDefinitions(DxilModule &M, raw_string_ostream &OS, StringRef comment) { OS << comment << "\n" << comment << " Buffer Definitions:\n" << comment << "\n"; DxilTypeSystem &typeSys = M.GetTypeSystem(); for (auto &CBuf : M.GetCBuffers()) PrintCBufferDefinition(CBuf.get(), typeSys, OS, comment); const DataLayout &layout = M.GetModule()->getDataLayout(); for (auto &res : M.GetSRVs()) { if (res->IsStructuredBuffer()) PrintStructBufferDefinition(res.get(), typeSys, layout, OS, comment); else if (res->IsTBuffer()) PrintTBufferDefinition(res.get(), typeSys, OS, comment); } for (auto &res : M.GetUAVs()) { if (res->IsStructuredBuffer()) PrintStructBufferDefinition(res.get(), typeSys, layout, OS, comment); } } #include "DxcDisassembler.inc" LPCSTR ResourceKindToString(DXIL::ResourceKind RK) { switch (RK) { case DXIL::ResourceKind::Texture1D: return "Texture1D"; case DXIL::ResourceKind::Texture2D: return "Texture2D"; case DXIL::ResourceKind::Texture2DMS: return "Texture2DMS"; case DXIL::ResourceKind::Texture3D: return "Texture3D"; case DXIL::ResourceKind::TextureCube: return "TextureCube"; case DXIL::ResourceKind::Texture1DArray: return "Texture1DArray"; case DXIL::ResourceKind::Texture2DArray: return "Texture2DArray"; case DXIL::ResourceKind::Texture2DMSArray: return "Texture2DMSArray"; case DXIL::ResourceKind::TextureCubeArray: return "TextureCubeArray"; case DXIL::ResourceKind::TypedBuffer: return "TypedBuffer"; case DXIL::ResourceKind::RawBuffer: return "ByteAddressBuffer"; case DXIL::ResourceKind::StructuredBuffer: return "StructuredBuffer"; case DXIL::ResourceKind::CBuffer: return "CBuffer"; case DXIL::ResourceKind::Sampler: return "Sampler"; case DXIL::ResourceKind::TBuffer: return "TBuffer"; case DXIL::ResourceKind::RTAccelerationStructure: return "RTAccelerationStructure"; case DXIL::ResourceKind::FeedbackTexture2D: return "FeedbackTexture2D"; case DXIL::ResourceKind::FeedbackTexture2DArray: return "FeedbackTexture2DArray"; default: return "<invalid ResourceKind>"; } } LPCSTR CompTypeToString(DXIL::ComponentType CompType) { switch (CompType) { case DXIL::ComponentType::I1: return "I1"; case DXIL::ComponentType::I16: return "I16"; case DXIL::ComponentType::U16: return "U16"; case DXIL::ComponentType::I32: return "I32"; case DXIL::ComponentType::U32: return "U32"; case DXIL::ComponentType::I64: return "I64"; case DXIL::ComponentType::U64: return "U64"; case DXIL::ComponentType::F16: return "F16"; case DXIL::ComponentType::F32: return "F32"; case DXIL::ComponentType::F64: return "F64"; case DXIL::ComponentType::SNormF16: return "SNormF16"; case DXIL::ComponentType::UNormF16: return "UNormF16"; case DXIL::ComponentType::SNormF32: return "SNormF32"; case DXIL::ComponentType::UNormF32: return "UNormF32"; case DXIL::ComponentType::SNormF64: return "SNormF64"; case DXIL::ComponentType::UNormF64: return "UNormF64"; default: return "<invalid CompType>"; } } LPCSTR SamplerFeedbackTypeToString(DXIL::SamplerFeedbackType SFT) { switch (SFT) { case DXIL::SamplerFeedbackType::MinMip: return "MinMip"; case DXIL::SamplerFeedbackType::MipRegionUsed: return "MipRegionUsed"; default: return "<invalid sampler feedback type>"; } } void PrintResourceProperties(DxilResourceProperties &RP, formatted_raw_ostream &OS) { OS << " resource: "; if (RP.getResourceClass() == DXIL::ResourceClass::CBuffer) { OS << "CBuffer"; return; } else if (RP.getResourceClass() == DXIL::ResourceClass::SRV && RP.getResourceKind() == DXIL::ResourceKind::TBuffer) { OS << "TBuffer"; return; } if (RP.getResourceClass() == DXIL::ResourceClass::Sampler) { if (!RP.Basic.SamplerCmpOrHasCounter) OS << "SamplerState"; else OS << "SamplerComparisonState"; return; } bool bUAV = RP.isUAV(); LPCSTR RW = bUAV ? (RP.Basic.IsROV ? "ROV" : "RW") : ""; LPCSTR GC = bUAV && RP.Basic.IsGloballyCoherent ? "globallycoherent " : ""; LPCSTR COUNTER = bUAV && RP.Basic.SamplerCmpOrHasCounter ? ", counter" : ""; switch (RP.getResourceKind()) { case DXIL::ResourceKind::Texture1D: case DXIL::ResourceKind::Texture2D: case DXIL::ResourceKind::Texture3D: case DXIL::ResourceKind::TextureCube: case DXIL::ResourceKind::Texture1DArray: case DXIL::ResourceKind::Texture2DArray: case DXIL::ResourceKind::TextureCubeArray: case DXIL::ResourceKind::TypedBuffer: case DXIL::ResourceKind::Texture2DMS: case DXIL::ResourceKind::Texture2DMSArray: OS << GC << RW << ResourceKindToString(RP.getResourceKind()); OS << "<"; if (RP.Typed.CompCount > 1) OS << std::to_string(RP.Typed.CompCount) << "x"; OS << CompTypeToString(RP.getCompType()) << ">"; break; case DXIL::ResourceKind::RawBuffer: OS << GC << RW << ResourceKindToString(RP.getResourceKind()); break; case DXIL::ResourceKind::StructuredBuffer: OS << GC << RW << ResourceKindToString(RP.getResourceKind()); OS << "<stride=" << RP.StructStrideInBytes << COUNTER << ">"; break; case DXIL::ResourceKind::RTAccelerationStructure: OS << ResourceKindToString(RP.getResourceKind()); break; case DXIL::ResourceKind::FeedbackTexture2D: case DXIL::ResourceKind::FeedbackTexture2DArray: OS << ResourceKindToString(RP.getResourceKind()); OS << "<" << SamplerFeedbackTypeToString(RP.SamplerFeedbackType) << ">"; break; default: OS << "<invalid resource properties>"; break; } } class DxcAssemblyAnnotationWriter : public llvm::AssemblyAnnotationWriter { public: ~DxcAssemblyAnnotationWriter() {} void printInfoComment(const Value &V, formatted_raw_ostream &OS) override { if (const Instruction *I = dyn_cast<Instruction>(&V)) { if (isa<DbgInfoIntrinsic>(I)) { DILocalVariable *Var = nullptr; DIExpression *Expr = nullptr; if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) { Var = DI->getVariable(); Expr = DI->getExpression(); } else if (const DbgValueInst *DI = dyn_cast<DbgValueInst>(I)) { Var = DI->getVariable(); Expr = DI->getExpression(); } if (Var && Expr) { OS << " ; var:\"" << Var->getName() << "\"" << " "; Expr->printAsBody(OS); if (DISubprogram *SubP = findFunctionScope(Var)) { OS << " func:\"" << SubP->getName() << "\""; } } } else { DebugLoc Loc = I->getDebugLoc(); if (Loc && Loc.getLine() != 0) OS << " ; line:" << Loc.getLine() << " col:" << Loc.getCol(); } } const CallInst *CI = dyn_cast<const CallInst>(&V); if (!CI) { return; } // TODO: annotate high-level operations where possible as well if (CI->getNumArgOperands() == 0 || !CI->getCalledFunction()->getName().startswith("dx.op.")) { return; } const ConstantInt *CInt = dyn_cast<const ConstantInt>(CI->getArgOperand(0)); if (!CInt) { // At this point, we know this is malformed; ignore. return; } unsigned opcodeVal = CInt->getZExtValue(); if (opcodeVal >= (unsigned)DXIL::OpCode::NumOpCodes) { OS << " ; invalid DXIL opcode #" << opcodeVal; return; } // TODO: if an argument references a resource, look it up and write the // name/binding DXIL::OpCode opcode = (DXIL::OpCode)opcodeVal; OS << " ; " << hlsl::OP::GetOpCodeName(opcode) << OpCodeSignatures[opcodeVal]; // Add extra decoding for certain ops switch (opcode) { case DXIL::OpCode::AnnotateHandle: { // Decode resource properties DxilInst_AnnotateHandle AH(const_cast<CallInst *>(CI)); if (Constant *Props = dyn_cast<Constant>(AH.get_props())) { DxilResourceProperties RP = resource_helper::loadPropsFromConstant(*Props); PrintResourceProperties(RP, OS); } } break; default: break; } } static DISubprogram *findFunctionScope(DILocalVariable *var) { auto scope = var->getScope(); if (scope) { return scope->getSubprogram(); } return nullptr; } }; void PrintPipelineStateValidationRuntimeInfo(const char *pBuffer, const uint32_t uBufferSize, DXIL::ShaderKind shaderKind, raw_string_ostream &OS, StringRef comment) { OS << comment << "\n" << comment << " Pipeline Runtime Information: \n" << comment << "\n"; DxilPipelineStateValidation PSV; PSV.InitFromPSV0(pBuffer, uBufferSize); PSV.PrintPSVRuntimeInfo(OS, static_cast<uint8_t>(shaderKind), comment.data()); OS << comment << "\n"; } } // namespace namespace dxcutil { HRESULT Disassemble(IDxcBlob *pProgram, raw_string_ostream &Stream) { CComPtr<IDxcBlob> pPdbContainerBlob; { CComPtr<IStream> pStream; IFR(hlsl::CreateReadOnlyBlobStream(pProgram, &pStream)); if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(DxcGetThreadMallocNoRef(), pStream, &pPdbContainerBlob))) { pProgram = pPdbContainerBlob; } } const char *pIL = (const char *)pProgram->GetBufferPointer(); uint32_t pILLength = pProgram->GetBufferSize(); const char *pReflectionIL = nullptr; uint32_t pReflectionILLength = 0; const DxilPartHeader *pRDATPart = nullptr; if (const DxilContainerHeader *pContainer = IsDxilContainerLike(pIL, pILLength)) { if (!IsValidDxilContainer(pContainer, pILLength)) { return DXC_E_CONTAINER_INVALID; } DxilPartIterator it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_FeatureInfo)); if (it != end(pContainer)) { PrintFeatureInfo( reinterpret_cast<const DxilShaderFeatureInfo *>(GetDxilPartData(*it)), Stream, /*comment*/ ";"); } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_InputSignature)); if (it != end(pContainer)) { PrintSignature( "Input", reinterpret_cast<const DxilProgramSignature *>(GetDxilPartData(*it)), true, Stream, /*comment*/ ";"); } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_OutputSignature)); if (it != end(pContainer)) { PrintSignature( "Output", reinterpret_cast<const DxilProgramSignature *>(GetDxilPartData(*it)), false, Stream, /*comment*/ ";"); } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_PatchConstantSignature)); if (it != end(pContainer)) { PrintSignature( "Patch Constant", reinterpret_cast<const DxilProgramSignature *>(GetDxilPartData(*it)), false, Stream, /*comment*/ ";"); } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_ShaderDebugName)); if (it != end(pContainer)) { const char *pDebugName; if (!GetDxilShaderDebugName(*it, &pDebugName, nullptr)) { Stream << "; shader debug name present; corruption detected\n"; } else if (pDebugName && *pDebugName) { Stream << "; shader debug name: " << pDebugName << "\n"; } } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_ShaderHash)); if (it != end(pContainer)) { const DxilShaderHash *pHashContent = reinterpret_cast<const DxilShaderHash *>(GetDxilPartData(*it)); Stream << "; shader hash: "; for (int i = 0; i < 16; ++i) Stream << format("%.2x", pHashContent->Digest[i]); if (pHashContent->Flags & (uint32_t)DxilShaderHashFlags::IncludesSource) Stream << " (includes source)"; Stream << "\n"; } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_DXIL)); DxilPartIterator dbgit = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_ShaderDebugInfoDXIL)); // Use dbg module if exist. if (dbgit != end(pContainer)) it = dbgit; if (it == end(pContainer)) { return DXC_E_CONTAINER_MISSING_DXIL; } const DxilProgramHeader *pProgramHeader = reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it)); if (!IsValidDxilProgramHeader(pProgramHeader, (*it)->PartSize)) { return DXC_E_CONTAINER_INVALID; } it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_PipelineStateValidation)); if (it != end(pContainer)) { PrintPipelineStateValidationRuntimeInfo( GetDxilPartData(*it), (*it)->PartSize, GetVersionShaderType(pProgramHeader->ProgramVersion), Stream, /*comment*/ ";"); } // RDAT it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_RuntimeData)); if (it != end(pContainer)) { pRDATPart = *it; } GetDxilProgramBitcode(pProgramHeader, &pIL, &pILLength); it = std::find_if(begin(pContainer), end(pContainer), DxilPartIsType(DFCC_ShaderStatistics)); if (it != end(pContainer)) { // If this part exists, use it for reflection data, probably stripped from // DXIL part. const DxilProgramHeader *pReflectionProgramHeader = reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it)); if (IsValidDxilProgramHeader(pReflectionProgramHeader, (*it)->PartSize)) { GetDxilProgramBitcode(pReflectionProgramHeader, &pReflectionIL, &pReflectionILLength); } } } else { const DxilProgramHeader *pProgramHeader = reinterpret_cast<const DxilProgramHeader *>(pIL); if (IsValidDxilProgramHeader(pProgramHeader, pILLength)) { GetDxilProgramBitcode(pProgramHeader, &pIL, &pILLength); } } std::string DiagStr; llvm::LLVMContext llvmContext; std::unique_ptr<llvm::Module> pModule(dxilutil::LoadModuleFromBitcode( llvm::StringRef(pIL, pILLength), llvmContext, DiagStr)); if (pModule.get() == nullptr) { return DXC_E_IR_VERIFICATION_FAILED; } std::unique_ptr<llvm::Module> pReflectionModule; if (pReflectionIL && pReflectionILLength) { pReflectionModule = dxilutil::LoadModuleFromBitcode( llvm::StringRef(pReflectionIL, pReflectionILLength), llvmContext, DiagStr); if (pReflectionModule.get() == nullptr) { return DXC_E_IR_VERIFICATION_FAILED; } } if (pModule->getNamedMetadata("dx.version")) { DxilModule &dxilModule = pModule->GetOrCreateDxilModule(); DxilModule &dxilReflectionModule = pReflectionModule.get() ? pReflectionModule->GetOrCreateDxilModule() : dxilModule; if (!dxilModule.GetShaderModel()->IsLib()) { PrintDxilSignature("Input", dxilModule.GetInputSignature(), Stream, /*comment*/ ";"); if (dxilModule.GetShaderModel()->IsMS()) { PrintDxilSignature("Vertex Output", dxilModule.GetOutputSignature(), Stream, /*comment*/ ";"); PrintDxilSignature("Primitive Output", dxilModule.GetPatchConstOrPrimSignature(), Stream, /*comment*/ ";"); } else { PrintDxilSignature("Output", dxilModule.GetOutputSignature(), Stream, /*comment*/ ";"); PrintDxilSignature("Patch Constant", dxilModule.GetPatchConstOrPrimSignature(), Stream, /*comment*/ ";"); } } PrintBufferDefinitions(dxilReflectionModule, Stream, /*comment*/ ";"); PrintResourceBindings(dxilReflectionModule, Stream, /*comment*/ ";"); PrintViewIdState(dxilReflectionModule, Stream, /*comment*/ ";"); if (pRDATPart) { RDAT::DxilRuntimeData runtimeData(GetDxilPartData(pRDATPart), pRDATPart->PartSize); // TODO: Print the rest of the RDAT info if (runtimeData.GetSubobjectTable()) { dxilModule.ResetSubobjects(new DxilSubobjects()); if (!LoadSubobjectsFromRDAT(*dxilModule.GetSubobjects(), runtimeData)) { Stream << "; error occurred while loading Subobjects from RDAT.\n"; } } } if (dxilModule.GetSubobjects()) { PrintSubobjects(*dxilModule.GetSubobjects(), Stream, /*comment*/ ";"); } } DxcAssemblyAnnotationWriter w; pModule->print(Stream, &w); // if (pReflectionModule) { // Stream << "\n========== Reflection Module from STAT part ==========\n"; // pReflectionModule->print(Stream, &w); // } Stream.flush(); return S_OK; } } // namespace dxcutil
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxcpdbutils.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxilpdbutils.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements IDxcPdbUtils interface, which allows getting basic stuff from // // shader PDBS. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/dxcapi.use.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MSFileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "dxc/DXIL/DxilMetadataHelper.h" #include "dxc/DXIL/DxilModule.h" #include "dxc/DXIL/DxilPDB.h" #include "dxc/DXIL/DxilUtil.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/Path.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "dxc/dxcapi.internal.h" #include "dxc/Support/dxcfilesystem.h" #include "dxcshadersourceinfo.h" #include "dxc/DxilCompression/DxilCompression.h" #include "dxc/DxilContainer/DxilRuntimeReflection.h" #include <algorithm> #include <codecvt> #include <locale> #include <string> #include <vector> #ifdef _WIN32 #include "dxc/dxcpix.h" #include <dia2.h> #endif using namespace dxc; using namespace llvm; struct DxcPdbVersionInfo : public IDxcVersionInfo2, public IDxcVersionInfo3 { private: DXC_MICROCOM_TM_REF_FIELDS() public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcPdbVersionInfo) DxcPdbVersionInfo(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc) {} hlsl::DxilCompilerVersion m_Version = {}; std::string m_VersionCommitSha = {}; std::string m_VersionString = {}; static HRESULT CopyStringToOutStringPtr(const std::string &Str, char **ppOutString) { *ppOutString = nullptr; char *const pString = (char *)CoTaskMemAlloc(Str.size() + 1); if (pString == nullptr) return E_OUTOFMEMORY; std::memcpy(pString, Str.data(), Str.size()); pString[Str.size()] = 0; *ppOutString = pString; return S_OK; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcVersionInfo, IDxcVersionInfo2, IDxcVersionInfo3>(this, iid, ppvObject); } virtual HRESULT STDMETHODCALLTYPE GetVersion(UINT32 *pMajor, UINT32 *pMinor) override { if (!pMajor || !pMinor) return E_POINTER; *pMajor = m_Version.Major; *pMinor = m_Version.Minor; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetFlags(UINT32 *pFlags) override { if (!pFlags) return E_POINTER; *pFlags = m_Version.VersionFlags; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCommitInfo(UINT32 *pCommitCount, char **pCommitHash) override { if (!pCommitHash) return E_POINTER; IFR(CopyStringToOutStringPtr(m_VersionCommitSha, pCommitHash)); *pCommitCount = m_Version.CommitCount; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString(char **pVersionString) override { if (!pVersionString) return E_POINTER; IFR(CopyStringToOutStringPtr(m_VersionString, pVersionString)); return S_OK; } }; // Implement the legacy IDxcPdbUtils interface with an instance of // the new impelmentation. struct DxcPdbUtilsAdapter : public IDxcPdbUtils { private: IDxcPdbUtils2 *m_pImpl; HRESULT CopyBlobWideToBSTR(IDxcBlobWide *pBlob, BSTR *pResult) { if (!pResult) return E_POINTER; *pResult = nullptr; if (pBlob) { CComBSTR pBstr(pBlob->GetStringLength(), pBlob->GetStringPointer()); *pResult = pBstr.Detach(); } return S_OK; } public: DxcPdbUtilsAdapter(IDxcPdbUtils2 *pImpl) : m_pImpl(pImpl) {} ULONG STDMETHODCALLTYPE AddRef() override { return m_pImpl->AddRef(); } ULONG STDMETHODCALLTYPE Release() override { return m_pImpl->Release(); } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return m_pImpl->QueryInterface(iid, ppvObject); } HRESULT STDMETHODCALLTYPE Load(IDxcBlob *pPdbOrDxil) override { return m_pImpl->Load(pPdbOrDxil); } virtual HRESULT STDMETHODCALLTYPE GetSourceCount(UINT32 *pCount) override { return m_pImpl->GetSourceCount(pCount); } virtual HRESULT STDMETHODCALLTYPE GetSource(UINT32 uIndex, IDxcBlobEncoding **ppResult) override { return m_pImpl->GetSource(uIndex, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetSourceName(UINT32 uIndex, BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetSourceName(uIndex, &pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetFlagCount(UINT32 *pCount) override { return m_pImpl->GetFlagCount(pCount); } virtual HRESULT STDMETHODCALLTYPE GetFlag(UINT32 uIndex, BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetFlag(uIndex, &pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetArgCount(UINT32 *pCount) override { return m_pImpl->GetArgCount(pCount); } virtual HRESULT STDMETHODCALLTYPE GetArg(UINT32 uIndex, BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetArg(uIndex, &pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetDefineCount(UINT32 *pCount) override { return m_pImpl->GetDefineCount(pCount); } virtual HRESULT STDMETHODCALLTYPE GetDefine(UINT32 uIndex, BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetDefine(uIndex, &pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(UINT32 *pCount) override { return m_pImpl->GetArgPairCount(pCount); } virtual HRESULT STDMETHODCALLTYPE GetArgPair(UINT32 uIndex, BSTR *pName, BSTR *pValue) override { CComPtr<IDxcBlobWide> pNameBlob; CComPtr<IDxcBlobWide> pValueBlob; IFR(m_pImpl->GetArgPair(uIndex, &pNameBlob, &pValueBlob)); IFR(CopyBlobWideToBSTR(pNameBlob, pName)); IFR(CopyBlobWideToBSTR(pValueBlob, pValue)); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetTargetProfile(&pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetEntryPoint(&pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetMainFileName(BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetMainFileName(&pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual BOOL STDMETHODCALLTYPE IsFullPDB() override { return m_pImpl->IsFullPDB(); } virtual HRESULT STDMETHODCALLTYPE OverrideArgs(DxcArgPair *pArgPairs, UINT32 uNumArgPairs) override { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE OverrideRootSignature(const WCHAR *pRootSignature) override { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE CompileForFullPDB(IDxcResult **ppResult) override { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE GetFullPDB(IDxcBlob **ppFullPDB) override { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE GetHash(IDxcBlob **ppResult) override { return m_pImpl->GetHash(ppResult); } virtual HRESULT STDMETHODCALLTYPE GetName(BSTR *pResult) override { CComPtr<IDxcBlobWide> pBlob; IFR(m_pImpl->GetName(&pBlob)); return CopyBlobWideToBSTR(pBlob, pResult); } virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(IDxcVersionInfo **ppVersionInfo) override { return m_pImpl->GetVersionInfo(ppVersionInfo); } virtual HRESULT STDMETHODCALLTYPE SetCompiler(IDxcCompiler3 *pCompiler) override { return E_NOTIMPL; } }; struct DxcPdbUtils : public IDxcPdbUtils2 #ifdef _WIN32 // Skip Pix debug info on linux for dia dependence. , public IDxcPixDxilDebugInfoFactory #endif { private: // Making the adapter and this interface the same object and share reference // counting. DxcPdbUtilsAdapter m_Adapter; DXC_MICROCOM_TM_REF_FIELDS() struct Source_File { CComPtr<IDxcBlobWide> Name; CComPtr<IDxcBlobEncoding> Content; }; CComPtr<IDxcBlob> m_InputBlob; CComPtr<IDxcBlob> m_pDebugProgramBlob; CComPtr<IDxcBlob> m_ContainerBlob; std::vector<Source_File> m_SourceFiles; CComPtr<IDxcBlobWide> m_EntryPoint; CComPtr<IDxcBlobWide> m_TargetProfile; CComPtr<IDxcBlobWide> m_Name; CComPtr<IDxcBlobWide> m_MainFileName; CComPtr<IDxcBlob> m_HashBlob; CComPtr<IDxcBlob> m_WholeDxil; bool m_HasVersionInfo = false; hlsl::DxilCompilerVersion m_VersionInfo; std::string m_VersionCommitSha; std::string m_VersionString; CComPtr<IDxcResult> m_pCachedRecompileResult; // NOTE: This is not set to null by Reset() since it doesn't // necessarily change across different PDBs. CComPtr<IDxcCompiler3> m_pCompiler; struct ArgPair { CComPtr<IDxcBlobWide> Name; CComPtr<IDxcBlobWide> Value; }; std::vector<ArgPair> m_ArgPairs; std::vector<CComPtr<IDxcBlobWide>> m_Defines; std::vector<CComPtr<IDxcBlobWide>> m_Args; std::vector<CComPtr<IDxcBlobWide>> m_Flags; struct LibraryEntry { std::vector<char> PdbInfo; CComPtr<IDxcBlobWide> pName; }; std::vector<LibraryEntry> m_LibraryPdbs; // std::vector<CComPtr<IDxcBlobWide> > m_LibraryNames; UINT32 m_uCustomToolchainID = 0; CComPtr<IDxcBlob> m_customToolchainData; void ResetAllArgs() { m_ArgPairs.clear(); m_Defines.clear(); m_Args.clear(); m_Flags.clear(); m_EntryPoint = nullptr; m_TargetProfile = nullptr; } void Reset() { m_WholeDxil = 0; m_uCustomToolchainID = 0; m_pDebugProgramBlob = nullptr; m_InputBlob = nullptr; m_ContainerBlob = nullptr; m_SourceFiles.clear(); m_Name = nullptr; m_MainFileName = nullptr; m_HashBlob = nullptr; m_HasVersionInfo = false; m_VersionInfo = {}; m_VersionCommitSha.clear(); m_VersionString.clear(); m_pCachedRecompileResult = nullptr; m_LibraryPdbs.clear(); m_customToolchainData = nullptr; ResetAllArgs(); } HRESULT Utf8ToBlobWide(StringRef str, IDxcBlobWide **ppResult) { CComPtr<IDxcBlobEncoding> pUtf8Blob; IFR(hlsl::DxcCreateBlob(str.data(), str.size(), /*bPinned*/ true, /*bCopy*/ false, /*encodingKnown*/ true, CP_UTF8, m_pMalloc, &pUtf8Blob)); return hlsl::DxcGetBlobAsWide(pUtf8Blob, m_pMalloc, ppResult); } static HRESULT CopyBlobWide(IDxcBlobWide *pBlob, IDxcBlobWide **ppResult) { if (!ppResult) return E_POINTER; *ppResult = nullptr; if (!pBlob) return S_OK; return pBlob->QueryInterface(ppResult); } static bool IsBitcode(const void *ptr, size_t size) { const uint8_t pattern[] = { 'B', 'C', }; if (size < _countof(pattern)) return false; return !memcmp(ptr, pattern, _countof(pattern)); } static std::vector<std::pair<std::string, std::string>> ComputeArgPairs(ArrayRef<const char *> args) { std::vector<std::pair<std::string, std::string>> ret; const llvm::opt::OptTable *optionTable = hlsl::options::getHlslOptTable(); assert(optionTable); if (optionTable) { unsigned missingIndex = 0; unsigned missingCount = 0; llvm::opt::InputArgList argList = optionTable->ParseArgs(args, missingIndex, missingCount); for (llvm::opt::Arg *arg : argList) { std::pair<std::string, std::string> newPair; newPair.first = arg->getOption().getName(); if (arg->getNumValues() > 0) { newPair.second = arg->getValue(); } ret.push_back(std::move(newPair)); } } return ret; } HRESULT AddSource(StringRef name, StringRef content) { Source_File source; IFR(hlsl::DxcCreateBlob(content.data(), content.size(), /*bPinned*/ false, /*bCopy*/ true, /*encodingKnown*/ true, CP_UTF8, m_pMalloc, &source.Content)); std::string normalizedPath = hlsl::NormalizePath(name); IFR(Utf8ToBlobWide(normalizedPath, &source.Name)); // First file is the main file if (m_SourceFiles.empty()) { m_MainFileName = source.Name; } m_SourceFiles.push_back(std::move(source)); return S_OK; } HRESULT LoadFromPDBInfoPart(const hlsl::DxilShaderPDBInfo *header, uint32_t partSize) { if (header->Version > hlsl::DxilShaderPDBInfoVersion::Latest) { return E_FAIL; } hlsl::RDAT::DxilRuntimeData reader; SmallVector<char, 1024> UncompressedBuffer; const void *ptr = nullptr; size_t size = 0; if (header->CompressionType == hlsl::DxilShaderPDBInfoCompressionType::Zlib) { UncompressedBuffer.resize(header->UncompressedSizeInBytes); if (hlsl::ZlibResult::Success != hlsl::ZlibDecompress(DxcGetThreadMallocNoRef(), header + 1, header->SizeInBytes, UncompressedBuffer.data(), UncompressedBuffer.size())) { return E_FAIL; } ptr = UncompressedBuffer.data(); size = UncompressedBuffer.size(); } else if (header->CompressionType == hlsl::DxilShaderPDBInfoCompressionType::Uncompressed) { assert(header->UncompressedSizeInBytes == header->SizeInBytes); ptr = header + 1; size = header->UncompressedSizeInBytes; } else { return E_FAIL; } if (!reader.InitFromRDAT(ptr, size)) { return E_FAIL; } auto pdbInfo = reader.GetDxilPdbInfoTable()[0]; return LoadFromPdbInfoReader(pdbInfo); } HRESULT LoadFromPdbInfoReader(hlsl::RDAT::DxilPdbInfo_Reader &reader) { auto sources = reader.getSources(); for (size_t i = 0; i < sources.Count(); i++) { const char *name = sources[i].getName(); const char *content = sources[i].getContent(); IFR(AddSource(name, content)); } if (reader.sizeWholeDxil()) { assert(!m_WholeDxil); IFR(hlsl::DxcCreateBlobOnHeapCopy(reader.getWholeDxil(), reader.sizeWholeDxil(), &m_WholeDxil)); } m_uCustomToolchainID = reader.getCustomToolchainId(); if (size_t size = reader.sizeCustomToolchainData()) { IFR(hlsl::DxcCreateBlobOnHeapCopy(reader.getCustomToolchainData(), size, &m_customToolchainData)); } auto libraries = reader.getLibraries(); unsigned libCount = libraries.Count(); for (size_t i = 0; i < libCount; i++) { auto libReader = reader.getLibraries()[i]; if (libReader.sizeData() == 0) return E_FAIL; CComPtr<IDxcBlob> pLibraryPdb; CComPtr<IDxcBlobWide> pLibraryName; IFR(hlsl::DxcCreateBlobOnHeapCopy(libReader.getData(), libReader.sizeData(), &pLibraryPdb)); IFR(Utf8ToBlobWide(libReader.getName(), &pLibraryName)); LibraryEntry Entry; Entry.PdbInfo.assign((const char *)libReader.getData(), (const char *)libReader.getData() + libReader.sizeData()); Entry.pName = pLibraryName; m_LibraryPdbs.push_back(std::move(Entry)); } auto argPairs = reader.getArgPairs(); for (size_t i = 0; i + 1 < argPairs.Count(); i += 2) { const char *name = argPairs[i + 0]; const char *value = argPairs[i + 1]; IFR(AddArgPair(name, value)); } assert(!reader.sizeHash() || reader.sizeHash() == sizeof(hlsl::DxilShaderHash)); if (reader.sizeHash() == sizeof(hlsl::DxilShaderHash)) { hlsl::DxilShaderHash hash = {}; memcpy(&hash, reader.getHash(), reader.sizeHash()); if (!m_HashBlob) { IFR(hlsl::DxcCreateBlobOnHeapCopy(&hash, sizeof(hash), &m_HashBlob)); } else { DXASSERT_NOMSG( m_HashBlob->GetBufferSize() == sizeof(hash) && 0 == memcmp(m_HashBlob->GetBufferPointer(), &hash, sizeof(hash))); } } if (!m_Name) { IFR(Utf8ToBlobWide(reader.getPdbName(), &m_Name)); } // Entry point might have been omitted. Set it to main by default. if (!m_EntryPoint) { IFR(Utf8ToBlobWide("main", &m_EntryPoint)); } return S_OK; } HRESULT PopulateSourcesFromProgramHeaderOrBitcode(IDxcBlob *pProgramBlob) { UINT32 bitcode_size = 0; const char *bitcode = nullptr; if (hlsl::IsValidDxilProgramHeader( (hlsl::DxilProgramHeader *)pProgramBlob->GetBufferPointer(), pProgramBlob->GetBufferSize())) { hlsl::GetDxilProgramBitcode( (hlsl::DxilProgramHeader *)pProgramBlob->GetBufferPointer(), &bitcode, &bitcode_size); } else if (IsBitcode(pProgramBlob->GetBufferPointer(), pProgramBlob->GetBufferSize())) { bitcode = (char *)pProgramBlob->GetBufferPointer(); bitcode_size = pProgramBlob->GetBufferSize(); } else { return E_INVALIDARG; } llvm::LLVMContext context; std::unique_ptr<llvm::Module> pModule; // NOTE: this doesn't copy the memory, just references it. std::unique_ptr<llvm::MemoryBuffer> mb = llvm::MemoryBuffer::getMemBuffer(StringRef(bitcode, bitcode_size), "-", /*RequiresNullTerminator*/ false); // Lazily parse the module std::string DiagStr; pModule = hlsl::dxilutil::LoadModuleFromBitcodeLazy(std::move(mb), context, DiagStr); if (!pModule) return E_FAIL; // Materialize only the stuff we need, so it's fast { llvm::StringRef DebugMetadataList[] = { hlsl::DxilMDHelper::kDxilSourceContentsMDName, hlsl::DxilMDHelper::kDxilSourceDefinesMDName, hlsl::DxilMDHelper::kDxilSourceArgsMDName, hlsl::DxilMDHelper::kDxilVersionMDName, hlsl::DxilMDHelper::kDxilShaderModelMDName, hlsl::DxilMDHelper::kDxilEntryPointsMDName, hlsl::DxilMDHelper::kDxilSourceMainFileNameMDName, }; pModule->materializeSelectNamedMetadata(DebugMetadataList); } hlsl::DxilModule &DM = pModule->GetOrCreateDxilModule(); IFR(Utf8ToBlobWide(DM.GetEntryFunctionName(), &m_EntryPoint)); IFR(Utf8ToBlobWide(DM.GetShaderModel()->GetName(), &m_TargetProfile)); // For each all the named metadata node in the module for (llvm::NamedMDNode &node : pModule->named_metadata()) { llvm::StringRef node_name = node.getName(); // dx.source.content if (node_name == hlsl::DxilMDHelper::kDxilSourceContentsMDName || node_name == hlsl::DxilMDHelper::kDxilSourceContentsOldMDName) { for (unsigned i = 0; i < node.getNumOperands(); i++) { llvm::MDTuple *tup = cast<llvm::MDTuple>(node.getOperand(i)); MDString *md_name = cast<MDString>(tup->getOperand(0)); MDString *md_content = cast<MDString>(tup->getOperand(1)); AddSource(md_name->getString(), md_content->getString()); } } // dx.source.mainFileName else if (node_name == hlsl::DxilMDHelper::kDxilSourceMainFileNameMDName || node_name == hlsl::DxilMDHelper::kDxilSourceMainFileNameOldMDName) { MDTuple *tup = cast<MDTuple>(node.getOperand(0)); MDString *str = cast<MDString>(tup->getOperand(0)); std::string normalized = hlsl::NormalizePath(str->getString()); m_MainFileName = nullptr; // This may already be set from reading dx.source content. // If we have a dx.source.mainFileName, we want to use that // here as the source of truth. Set it to nullptr to avoid // leak (and assert). IFR(Utf8ToBlobWide(normalized, &m_MainFileName)); } // dx.source.args else if (node_name == hlsl::DxilMDHelper::kDxilSourceArgsMDName || node_name == hlsl::DxilMDHelper::kDxilSourceArgsOldMDName) { MDTuple *tup = cast<MDTuple>(node.getOperand(0)); std::vector<const char *> args; // Args for (unsigned i = 0; i < tup->getNumOperands(); i++) { StringRef arg = cast<MDString>(tup->getOperand(i))->getString(); args.push_back(arg.data()); } std::vector<std::pair<std::string, std::string>> Pairs = ComputeArgPairs(args); for (std::pair<std::string, std::string> &p : Pairs) { IFR(AddArgPair(p.first, p.second)); } } } return S_OK; } HRESULT HandleDxilContainer(IDxcBlob *pContainer, IDxcBlob **ppDebugProgramBlob) { const hlsl::DxilContainerHeader *header = (const hlsl::DxilContainerHeader *)m_ContainerBlob->GetBufferPointer(); for (auto it = hlsl::begin(header); it != hlsl::end(header); it++) { const hlsl::DxilPartHeader *part = *it; hlsl::DxilFourCC four_cc = (hlsl::DxilFourCC)part->PartFourCC; switch (four_cc) { case hlsl::DFCC_CompilerVersion: { const hlsl::DxilCompilerVersion *header = (const hlsl::DxilCompilerVersion *)(part + 1); m_VersionInfo = *header; m_HasVersionInfo = true; const char *ptr = (const char *)(header + 1); unsigned i = 0; { unsigned commitShaLength = 0; const char *commitSha = (const char *)(header + 1) + i; for (; i < header->VersionStringListSizeInBytes; i++) { if (ptr[i] == 0) { i++; break; } commitShaLength++; } m_VersionCommitSha.assign(commitSha, commitShaLength); } { const char *versionString = (const char *)(header + 1) + i; unsigned versionStringLength = 0; for (; i < header->VersionStringListSizeInBytes; i++) { if (ptr[i] == 0) { i++; break; } versionStringLength++; } m_VersionString.assign(versionString, versionStringLength); } } break; case hlsl::DFCC_ShaderPDBInfo: { const hlsl::DxilShaderPDBInfo *header = (const hlsl::DxilShaderPDBInfo *)(part + 1); IFR(LoadFromPDBInfoPart(header, part->PartSize)); } break; // This is now legacy. case hlsl::DFCC_ShaderSourceInfo: { const hlsl::DxilSourceInfo *header = (const hlsl::DxilSourceInfo *)(part + 1); hlsl::SourceInfoReader reader; if (!reader.Init(header, part->PartSize)) { Reset(); return E_FAIL; } // Args for (unsigned i = 0; i < reader.GetArgPairCount(); i++) { const hlsl::SourceInfoReader::ArgPair &pair = reader.GetArgPair(i); IFR(AddArgPair(pair.Name, pair.Value)); } // Sources for (unsigned i = 0; i < reader.GetSourcesCount(); i++) { hlsl::SourceInfoReader::Source source_data = reader.GetSource(i); IFR(AddSource(source_data.Name, source_data.Content)); } } break; case hlsl::DFCC_ShaderHash: { const hlsl::DxilShaderHash *hash_header = (const hlsl::DxilShaderHash *)(part + 1); IFR(hlsl::DxcCreateBlobOnHeapCopy(hash_header, sizeof(*hash_header), &m_HashBlob)); } break; case hlsl::DFCC_ShaderDebugName: { const hlsl::DxilShaderDebugName *name_header = (const hlsl::DxilShaderDebugName *)(part + 1); const char *ptr = (const char *)(name_header + 1); IFR(Utf8ToBlobWide(ptr, &m_Name)); } break; case hlsl::DFCC_ShaderDebugInfoDXIL: { const hlsl::DxilProgramHeader *program_header = (const hlsl::DxilProgramHeader *)(part + 1); CComPtr<IDxcBlob> pProgramHeaderBlob; IFR(hlsl::DxcCreateBlobFromPinned( program_header, program_header->SizeInUint32 * sizeof(UINT32), &pProgramHeaderBlob)); IFR(pProgramHeaderBlob.QueryInterface(ppDebugProgramBlob)); } break; // hlsl::DFCC_ShaderDebugInfoDXIL } // switch (four_cc) } // For each part return S_OK; } HRESULT AddArgPair(StringRef name, StringRef value) { const llvm::opt::OptTable *optTable = hlsl::options::getHlslOptTable(); // If the value for define is somehow empty, do not add it. if (name == "D" && value.empty()) return S_OK; SmallVector<char, 32> fusedArgStorage; if (name.size() && value.size()) { // Handling case where old positional arguments used to have // <input> written as the option name. if (name == "<input>") { name = ""; } // Check if the option and its value must be merged. Newer compiler // pre-merge them before writing them to the PDB, but older PDBs might // have them separated. else { llvm::opt::Option opt = optTable->findOption(name.data()); if (opt.isValid()) { if (opt.getKind() == llvm::opt::Option::JoinedClass) { StringRef newName = (Twine(name) + Twine(value)).toStringRef(fusedArgStorage); name = newName; value = ""; } } } } CComPtr<IDxcBlobWide> pValueBlob; CComPtr<IDxcBlobWide> pNameBlob; if (name.size()) IFR(Utf8ToBlobWide(name, &pNameBlob)); if (value.size()) IFR(Utf8ToBlobWide(value, &pValueBlob)); bool excludeFromFlags = false; if (name == "E") { m_EntryPoint = pValueBlob; excludeFromFlags = true; } else if (name == "T") { m_TargetProfile = pValueBlob; excludeFromFlags = true; } else if (name == "D") { m_Defines.push_back(pValueBlob); excludeFromFlags = true; } CComPtr<IDxcBlobWide> pNameWithDashBlob; if (name.size()) { SmallVector<char, 32> nameWithDashStorage; StringRef nameWithDash = (Twine("-") + Twine(name)).toStringRef(nameWithDashStorage); IFR(Utf8ToBlobWide(nameWithDash, &pNameWithDashBlob)); } if (!excludeFromFlags) { if (pNameWithDashBlob) m_Flags.push_back(pNameWithDashBlob); if (pValueBlob) m_Flags.push_back(pValueBlob); } if (pNameWithDashBlob) m_Args.push_back(pNameWithDashBlob); if (pValueBlob) m_Args.push_back(pValueBlob); ArgPair newPair; newPair.Name = pNameBlob; newPair.Value = pValueBlob; m_ArgPairs.push_back(std::move(newPair)); return S_OK; } bool NeedToLookInILDB() { return !m_SourceFiles.size() && m_LibraryPdbs.empty(); } public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcPdbUtils) DxcPdbUtils(IMalloc *pMalloc) : m_Adapter(this), m_dwRef(0), m_pMalloc(pMalloc) {} HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { #ifdef _WIN32 HRESULT hr = DoBasicQueryInterface<IDxcPdbUtils2, IDxcPixDxilDebugInfoFactory>( this, iid, ppvObject); #else HRESULT hr = DoBasicQueryInterface<IDxcPdbUtils2>(this, iid, ppvObject); #endif if (FAILED(hr)) { return DoBasicQueryInterface<IDxcPdbUtils>(&m_Adapter, iid, ppvObject); } return hr; } HRESULT STDMETHODCALLTYPE Load(IDxcBlob *pPdbOrDxil) override { if (!pPdbOrDxil) return E_POINTER; try { DxcThreadMalloc TM(m_pMalloc); ::llvm::sys::fs::MSFileSystem *msfPtr = nullptr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); // Remove all the data Reset(); m_InputBlob = pPdbOrDxil; CComPtr<IStream> pStream; IFR(hlsl::CreateReadOnlyBlobStream(pPdbOrDxil, &pStream)); // PDB if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(m_pMalloc, pStream, &m_ContainerBlob))) { IFR(HandleDxilContainer(m_ContainerBlob, &m_pDebugProgramBlob)); if (NeedToLookInILDB()) { if (m_pDebugProgramBlob) { IFR(PopulateSourcesFromProgramHeaderOrBitcode(m_pDebugProgramBlob)); } else { return E_FAIL; } } } // DXIL Container else if (hlsl::IsValidDxilContainer((const hlsl::DxilContainerHeader *) pPdbOrDxil->GetBufferPointer(), pPdbOrDxil->GetBufferSize())) { m_ContainerBlob = pPdbOrDxil; IFR(HandleDxilContainer(m_ContainerBlob, &m_pDebugProgramBlob)); // If we have a Debug DXIL, populate the debug info. if (m_pDebugProgramBlob && NeedToLookInILDB()) { IFR(PopulateSourcesFromProgramHeaderOrBitcode(m_pDebugProgramBlob)); } } // DXIL program header or bitcode else { CComPtr<IDxcBlob> pProgramHeaderBlob; IFR(hlsl::DxcCreateBlobFromPinned( (hlsl::DxilProgramHeader *)pPdbOrDxil->GetBufferPointer(), pPdbOrDxil->GetBufferSize(), &pProgramHeaderBlob)); IFR(pProgramHeaderBlob.QueryInterface(&m_pDebugProgramBlob)); IFR(PopulateSourcesFromProgramHeaderOrBitcode(m_pDebugProgramBlob)); } IFR(SetEntryPointToDefaultIfEmpty()); } CATCH_CPP_RETURN_HRESULT(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetSourceCount(UINT32 *pCount) override { if (!pCount) return E_POINTER; *pCount = (UINT32)m_SourceFiles.size(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetSource(UINT32 uIndex, IDxcBlobEncoding **ppResult) override { if (uIndex >= m_SourceFiles.size()) return E_INVALIDARG; if (!ppResult) return E_POINTER; *ppResult = nullptr; return m_SourceFiles[uIndex].Content.QueryInterface(ppResult); } virtual HRESULT STDMETHODCALLTYPE GetSourceName(UINT32 uIndex, IDxcBlobWide **ppResult) override { if (uIndex >= m_SourceFiles.size()) return E_INVALIDARG; return m_SourceFiles[uIndex].Name.QueryInterface(ppResult); } static inline HRESULT GetStringCount(const std::vector<CComPtr<IDxcBlobWide>> &list, UINT32 *pCount) { if (!pCount) return E_POINTER; *pCount = (UINT32)list.size(); return S_OK; } static inline HRESULT GetStringOption(const std::vector<CComPtr<IDxcBlobWide>> &list, UINT32 uIndex, IDxcBlobWide **ppResult) { if (uIndex >= list.size()) return E_INVALIDARG; return list[uIndex].QueryInterface(ppResult); } virtual HRESULT STDMETHODCALLTYPE GetFlagCount(UINT32 *pCount) override { return GetStringCount(m_Flags, pCount); } virtual HRESULT STDMETHODCALLTYPE GetFlag(UINT32 uIndex, IDxcBlobWide **ppResult) override { return GetStringOption(m_Flags, uIndex, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetArgCount(UINT32 *pCount) override { return GetStringCount(m_Args, pCount); } virtual HRESULT STDMETHODCALLTYPE GetArg(UINT32 uIndex, IDxcBlobWide **ppResult) override { return GetStringOption(m_Args, uIndex, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetDefineCount(UINT32 *pCount) override { return GetStringCount(m_Defines, pCount); } virtual HRESULT STDMETHODCALLTYPE GetDefine(UINT32 uIndex, IDxcBlobWide **ppResult) override { return GetStringOption(m_Defines, uIndex, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(UINT32 *pCount) override { if (!pCount) return E_POINTER; *pCount = (UINT32)m_ArgPairs.size(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetArgPair( UINT32 uIndex, IDxcBlobWide **ppName, IDxcBlobWide **ppValue) override { if (!ppName || !ppValue) return E_POINTER; if (uIndex >= m_ArgPairs.size()) return E_INVALIDARG; const ArgPair &pair = m_ArgPairs[uIndex]; *ppName = nullptr; *ppValue = nullptr; if (pair.Name) { IFR(pair.Name.QueryInterface(ppName)); } if (pair.Value) { IFR(pair.Value.QueryInterface(ppValue)); } return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(IDxcBlobWide **ppResult) override { return CopyBlobWide(m_TargetProfile, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(IDxcBlobWide **ppResult) override { return CopyBlobWide(m_EntryPoint, ppResult); } virtual HRESULT STDMETHODCALLTYPE GetMainFileName(IDxcBlobWide **ppResult) override { return CopyBlobWide(m_MainFileName, ppResult); } virtual BOOL STDMETHODCALLTYPE IsFullPDB() override { return m_pDebugProgramBlob != nullptr; } virtual BOOL STDMETHODCALLTYPE IsPDBRef() override { return m_LibraryPdbs.size() == 0 && m_SourceFiles.size() == 0 && !m_WholeDxil; } HRESULT SetEntryPointToDefaultIfEmpty() { // Entry point might have been omitted. Set it to main by default. // Don't set entry point if this instance is non-debug DXIL and has no // arguments at all. if ((!m_EntryPoint || m_EntryPoint->GetStringLength() == 0) && !m_ArgPairs.empty()) { // Don't set the name if the target is a lib if (!m_TargetProfile || m_TargetProfile->GetStringLength() < 3 || 0 != wcsncmp(m_TargetProfile->GetStringPointer(), L"lib", 3)) { m_EntryPoint = nullptr; IFR(Utf8ToBlobWide("main", &m_EntryPoint)); } } return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetHash(IDxcBlob **ppResult) override { if (!ppResult) return E_POINTER; *ppResult = nullptr; if (m_HashBlob) return m_HashBlob.QueryInterface(ppResult); return E_FAIL; } virtual HRESULT STDMETHODCALLTYPE GetWholeDxil(IDxcBlob **ppResult) override { if (!ppResult) return E_POINTER; *ppResult = nullptr; if (m_WholeDxil) return m_WholeDxil.QueryInterface(ppResult); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetName(IDxcBlobWide **ppResult) override { return CopyBlobWide(m_Name, ppResult); } #ifdef _WIN32 virtual STDMETHODIMP NewDxcPixDxilDebugInfo(IDxcPixDxilDebugInfo **ppDxilDebugInfo) override { if (!m_pDebugProgramBlob) return E_FAIL; DxcThreadMalloc TM(m_pMalloc); CComPtr<IDiaDataSource> pDataSource; IFR(DxcCreateInstance2(m_pMalloc, CLSID_DxcDiaDataSource, IID_PPV_ARGS(&pDataSource))); CComPtr<IStream> pStream; IFR(hlsl::CreateReadOnlyBlobStream(m_pDebugProgramBlob, &pStream)); IFR(pDataSource->loadDataFromIStream(pStream)); CComPtr<IDiaSession> pSession; IFR(pDataSource->openSession(&pSession)); CComPtr<IDxcPixDxilDebugInfoFactory> pFactory; IFR(pSession.QueryInterface(&pFactory)); return pFactory->NewDxcPixDxilDebugInfo(ppDxilDebugInfo); } virtual STDMETHODIMP NewDxcPixCompilationInfo( IDxcPixCompilationInfo **ppCompilationInfo) override { return E_NOTIMPL; } #endif virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(IDxcVersionInfo **ppVersionInfo) override { if (!ppVersionInfo) return E_POINTER; *ppVersionInfo = nullptr; if (!m_HasVersionInfo) return E_FAIL; DxcThreadMalloc TM(m_pMalloc); CComPtr<DxcPdbVersionInfo> result = CreateOnMalloc<DxcPdbVersionInfo>(m_pMalloc); if (result == nullptr) { return E_OUTOFMEMORY; } result->m_Version = m_VersionInfo; result->m_VersionCommitSha = m_VersionCommitSha; result->m_VersionString = m_VersionString; *ppVersionInfo = result.Detach(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetLibraryPDBCount(UINT32 *pCount) override { if (!pCount) return E_POINTER; *pCount = (UINT32)m_LibraryPdbs.size(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetLibraryPDB(UINT32 uIndex, IDxcPdbUtils2 **ppOutPdbUtils, IDxcBlobWide **ppLibraryName) override { if (!ppOutPdbUtils) return E_POINTER; if (uIndex >= m_LibraryPdbs.size()) return E_INVALIDARG; LibraryEntry &Entry = m_LibraryPdbs[uIndex]; hlsl::RDAT::DxilRuntimeData rdat; if (!rdat.InitFromRDAT(Entry.PdbInfo.data(), Entry.PdbInfo.size())) return E_FAIL; if (rdat.GetDxilPdbInfoTable().Count() != 1) return E_FAIL; auto reader = rdat.GetDxilPdbInfoTable()[0]; CComPtr<DxcPdbUtils> pNewPdbUtils = DxcPdbUtils::Alloc(m_pMalloc); IFR(pNewPdbUtils->LoadFromPdbInfoReader(reader)); pNewPdbUtils.QueryInterface(ppOutPdbUtils); if (ppLibraryName) { *ppLibraryName = nullptr; if (Entry.pName) { IFR(Entry.pName.QueryInterface(ppLibraryName)); } } return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainID(UINT32 *pID) override { if (!pID) return E_POINTER; *pID = m_uCustomToolchainID; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainData(IDxcBlob **ppBlob) override { if (!ppBlob) return E_POINTER; *ppBlob = nullptr; if (m_customToolchainData) return m_customToolchainData.QueryInterface(ppBlob); return S_OK; } }; HRESULT CreateDxcPdbUtils(REFIID riid, LPVOID *ppv) { if (!ppv) return E_POINTER; *ppv = nullptr; if (riid == __uuidof(IDxcPdbUtils)) { CComPtr<DxcPdbUtils> pdbUtils2 = CreateOnMalloc<DxcPdbUtils>(DxcGetThreadMallocNoRef()); if (!pdbUtils2) return E_OUTOFMEMORY; return pdbUtils2.p->QueryInterface(riid, ppv); } else { CComPtr<DxcPdbUtils> result = CreateOnMalloc<DxcPdbUtils>(DxcGetThreadMallocNoRef()); if (result == nullptr) return E_OUTOFMEMORY; return result.p->QueryInterface(riid, ppv); } return E_NOINTERFACE; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxillib.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxillib.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides access to dxil.dll // // // /////////////////////////////////////////////////////////////////////////////// #include "dxillib.h" #include "dxc/Support/Global.h" // For DXASSERT #include "dxc/Support/dxcapi.use.h" #include "llvm/Support/Mutex.h" using namespace dxc; static DxcDllSupport g_DllSupport; static HRESULT g_DllLibResult = S_OK; static llvm::sys::Mutex *cs = nullptr; // Check if we can successfully get IDxcValidator from dxil.dll // This function is to prevent multiple attempts to load dxil.dll HRESULT DxilLibInitialize() { cs = new llvm::sys::Mutex; cs->lock(); g_DllLibResult = g_DllSupport.InitializeForDll(kDxilLib, "DxcCreateInstance"); cs->unlock(); return S_OK; } HRESULT DxilLibCleanup(DxilLibCleanUpType type) { HRESULT hr = S_OK; if (type == DxilLibCleanUpType::ProcessTermination) { g_DllSupport.Detach(); } else if (type == DxilLibCleanUpType::UnloadLibrary) { g_DllSupport.Cleanup(); } else { hr = E_INVALIDARG; } delete cs; cs = nullptr; return hr; } // g_DllLibResult is S_OK by default, check again to see if dxil.dll is loaded // If we fail to load dxil.dll, set g_DllLibResult to E_FAIL so that we don't // have multiple attempts to load dxil.dll bool DxilLibIsEnabled() { cs->lock(); if (SUCCEEDED(g_DllLibResult)) { if (!g_DllSupport.IsEnabled()) { g_DllLibResult = g_DllSupport.InitializeForDll(kDxilLib, "DxcCreateInstance"); } } cs->unlock(); return SUCCEEDED(g_DllLibResult); } HRESULT DxilLibCreateInstance(REFCLSID rclsid, REFIID riid, IUnknown **ppInterface) { DXASSERT_NOMSG(ppInterface != nullptr); HRESULT hr = E_FAIL; if (DxilLibIsEnabled()) { cs->lock(); hr = g_DllSupport.CreateInstance(rclsid, riid, ppInterface); cs->unlock(); } return hr; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/DXCompiler.def
LIBRARY dxcompiler EXPORTS DxcCreateInstance DxcCreateInstance2
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxcompiler/dxillib.h
/////////////////////////////////////////////////////////////////////////////// // // // dxillib.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides wrappers to handle calls to dxil.dll // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __DXC_DXILLIB__ #define __DXC_DXILLIB__ #include "dxc/Support/WinIncludes.h" #include "dxc/WinAdapter.h" // Initialize Dxil library. HRESULT DxilLibInitialize(); // When dxcompiler is detached from process, // we should not call FreeLibrary on process termination. // So the caller has to specify if cleaning is from FreeLibrary or process // termination enum class DxilLibCleanUpType { UnloadLibrary, ProcessTermination }; HRESULT DxilLibCleanup(DxilLibCleanUpType type); // Check if can access dxil.dll bool DxilLibIsEnabled(); HRESULT DxilLibCreateInstance(REFCLSID rclsid, REFIID riid, IUnknown **ppInterface); template <class TInterface> HRESULT DxilLibCreateInstance(REFCLSID rclsid, TInterface **ppInterface) { return DxilLibCreateInstance(rclsid, __uuidof(TInterface), (IUnknown **)ppInterface); } #endif // __DXC_DXILLIB__
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxopt/dxopt.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxopt.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides the entry point for the dxopt console program. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/Global.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/WinIncludes.h" #include <string> #include <vector> #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/dxcapi.use.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "dxc/dxcapi.internal.h" #include "dxc/dxctools.h" #include <iostream> #include <limits> #include "llvm/Support/FileSystem.h" inline bool wcseq(LPCWSTR a, LPCWSTR b) { return (a == nullptr && b == nullptr) || (a != nullptr && b != nullptr && wcscmp(a, b) == 0); } inline bool wcsieq(LPCWSTR a, LPCWSTR b) { return _wcsicmp(a, b) == 0; } inline bool wcsistarts(LPCWSTR text, LPCWSTR prefix) { return wcslen(text) >= wcslen(prefix) && _wcsnicmp(text, prefix, wcslen(prefix)) == 0; } inline bool wcsieqopt(LPCWSTR text, LPCWSTR opt) { return (text[0] == L'-' || text[0] == L'/') && wcsieq(text + 1, opt); } static dxc::DxcDllSupport g_DxcSupport; enum class ProgramAction { PrintHelp, PrintPasses, PrintPassesWithDetails, RunOptimizer, }; const wchar_t *STDIN_FILE_NAME = L"-"; bool isStdIn(LPCWSTR fName) { return wcscmp(STDIN_FILE_NAME, fName) == 0; } // Arg does not start with '-' or '/' and so assume it is a filename, // or next arg equals '-' which is the name of stdin. bool isFileInputArg(LPCWSTR arg) { const bool isNonOptionArg = !wcsistarts(arg, L"-") && wcsrchr(arg, L'/') != arg; return isNonOptionArg || isStdIn(arg); } static HRESULT ReadStdin(std::string &input) { bool emptyLine = false; while (!std::cin.eof()) { std::string line; std::getline(std::cin, line); if (line.empty()) { emptyLine = true; continue; } std::copy(line.begin(), line.end(), std::back_inserter(input)); input.push_back('\n'); } DWORD lastError = GetLastError(); // Make sure we reached finished successfully. if (std::cin.eof()) return S_OK; // Or reached the end of a pipe. else if (!std::cin.good() && emptyLine && lastError == ERROR_BROKEN_PIPE) return S_OK; else return HRESULT_FROM_WIN32(lastError); } static void BlobFromFile(LPCWSTR pFileName, IDxcBlob **ppBlob) { CComPtr<IDxcLibrary> pLibrary; CComPtr<IDxcBlobEncoding> pFileBlob; IFT(g_DxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary)); if (isStdIn(pFileName)) { std::string input; IFT(ReadStdin(input)); IFTBOOL(input.size() < std::numeric_limits<UINT32>::max(), E_FAIL); IFT(pLibrary->CreateBlobWithEncodingOnHeapCopy( input.data(), (UINT32)input.size(), CP_UTF8, &pFileBlob)) } else { IFT(pLibrary->CreateBlobFromFile(pFileName, nullptr, &pFileBlob)); } *ppBlob = pFileBlob.Detach(); } static void PrintOptOutput(LPCWSTR pFileName, IDxcBlob *pBlob, IDxcBlobEncoding *pOutputText) { CComPtr<IDxcLibrary> pLibrary; CComPtr<IDxcBlobEncoding> pOutputText16; IFT(g_DxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary)); #ifdef _WIN32 IFT(pLibrary->GetBlobAsWide(pOutputText, &pOutputText16)); wprintf(L"%*s", (int)pOutputText16->GetBufferSize(), (wchar_t *)pOutputText16->GetBufferPointer()); #else IFT(pLibrary->GetBlobAsUtf8(pOutputText, &pOutputText16)); printf("%*s", (int)pOutputText16->GetBufferSize(), (char *)pOutputText16->GetBufferPointer()); #endif if (pBlob && pFileName && *pFileName) { dxc::WriteBlobToFile(pBlob, pFileName, DXC_CP_UTF8); // TODO: Support DefaultTextCodePage } } static void PrintPasses(IDxcOptimizer *pOptimizer, bool includeDetails) { UINT32 passCount; IFT(pOptimizer->GetAvailablePassCount(&passCount)); for (UINT32 i = 0; i < passCount; ++i) { CComPtr<IDxcOptimizerPass> pPass; CComHeapPtr<wchar_t> pName; IFT(pOptimizer->GetAvailablePass(i, &pPass)); IFT(pPass->GetOptionName(&pName)); if (!includeDetails) { wprintf(L"%s\n", pName.m_pData); continue; } CComHeapPtr<wchar_t> pDescription; IFT(pPass->GetDescription(&pDescription)); if (*pDescription) { wprintf(L"%s - %s\n", pName.m_pData, pDescription.m_pData); } else { wprintf(L"%s\n", pName.m_pData); } UINT32 argCount; IFT(pPass->GetOptionArgCount(&argCount)); if (argCount) { wprintf(L"%s", L"Options:\n"); for (UINT32 argIdx = 0; argIdx < argCount; ++argIdx) { CComHeapPtr<wchar_t> pArgName; CComHeapPtr<wchar_t> pArgDescription; IFT(pPass->GetOptionArgName(argIdx, &pArgName)); IFT(pPass->GetOptionArgDescription(argIdx, &pArgDescription)); if (pArgDescription.m_pData && *pArgDescription.m_pData && !wcsieq(L"None", pArgDescription.m_pData)) { wprintf(L" %s - %s\n", pArgName.m_pData, pArgDescription.m_pData); } else { wprintf(L" %s\n", pArgName.m_pData); } } wprintf(L"%s", L"\n"); } } } static void ReadFileOpts(LPCWSTR pPassFileName, IDxcBlobEncoding **ppPassOpts, std::vector<LPCWSTR> &passes, LPCWSTR **pOptArgs, UINT32 *pOptArgCount) { *ppPassOpts = nullptr; // If there is no file, there is no work to be done. if (!pPassFileName || !*pPassFileName) { return; } CComPtr<IDxcBlob> pPassOptsBlob; CComPtr<IDxcBlobWide> pPassOpts; BlobFromFile(pPassFileName, &pPassOptsBlob); IFT(hlsl::DxcGetBlobAsWide(pPassOptsBlob, hlsl::GetGlobalHeapMalloc(), &pPassOpts)); LPWSTR pCursor = const_cast<LPWSTR>(pPassOpts->GetStringPointer()); while (*pCursor) { passes.push_back(pCursor); while (*pCursor && *pCursor != L'\n' && *pCursor != L'\r') { ++pCursor; } while (*pCursor && (*pCursor == L'\n' || *pCursor == L'\r')) { *pCursor = L'\0'; ++pCursor; } } // Remove empty entries and comments. size_t i = passes.size(); do { --i; if (wcslen(passes[i]) == 0 || passes[i][0] == L'#') { passes.erase(passes.begin() + i); } } while (i != 0); *pOptArgs = passes.data(); *pOptArgCount = passes.size(); pPassOpts->QueryInterface(ppPassOpts); } static void PrintHelp() { wprintf( L"%s", L"Performs optimizations on a bitcode file by running a sequence of " L"passes.\n\n" L"dxopt [-? | -passes | -pass-details | -pf [PASS-FILE] | [-o=OUT-FILE] " L"| IN-FILE OPT-ARGUMENTS ...]\n\n" L"Arguments:\n" L" -? Displays this help message\n" L" -passes Displays a list of pass names\n" L" -pass-details Displays a list of passes with detailed information\n" L" -pf PASS-FILE Loads passes from the specified file\n" L" -o=OUT-FILE Output file for processed module\n" L" IN-FILE File with with bitcode to optimize\n" L" OPT-ARGUMENTS One or more passes to run in sequence\n" L"\n" L"Text that is traced during optimization is written to the standard " L"output.\n"); } #ifdef _WIN32 int __cdecl wmain(int argc, const wchar_t **argv_) { #else int main(int argc, const char **argv) { // Convert argv to wchar. WArgV ArgV(argc, argv); const wchar_t **argv_ = ArgV.argv(); #endif const char *pStage = "Operation"; int retVal = 0; if (llvm::sys::fs::SetupPerThreadFileSystem()) return 1; llvm::sys::fs::AutoCleanupPerThreadFileSystem auto_cleanup_fs; try { // Parse command line options. pStage = "Argument processing"; ProgramAction action = ProgramAction::PrintHelp; LPCWSTR inFileName = nullptr; LPCWSTR outFileName = nullptr; LPCWSTR externalLib = nullptr; LPCWSTR externalFn = nullptr; LPCWSTR passFileName = nullptr; const wchar_t **optArgs = nullptr; UINT32 optArgCount = 0; int argIdx = 1; while (argIdx < argc) { LPCWSTR arg = argv_[argIdx]; if (wcsieqopt(arg, L"?")) { action = ProgramAction::PrintHelp; } else if (wcsieqopt(arg, L"passes")) { action = ProgramAction::PrintPasses; } else if (wcsieqopt(arg, L"pass-details")) { action = ProgramAction::PrintPassesWithDetails; } else if (wcsieqopt(arg, L"external")) { ++argIdx; if (argIdx == argc) { PrintHelp(); return 1; } externalLib = argv_[argIdx]; } else if (wcsieqopt(arg, L"external-fn")) { ++argIdx; if (argIdx == argc) { PrintHelp(); return 1; } externalFn = argv_[argIdx]; } else if (wcsieqopt(arg, L"pf")) { ++argIdx; if (argIdx == argc) { PrintHelp(); return 1; } passFileName = argv_[argIdx]; } else if (wcsistarts(arg, L"-o=")) { outFileName = argv_[argIdx] + 3; } else { action = ProgramAction::RunOptimizer; // See if arg is file input specifier. if (isFileInputArg(arg)) { inFileName = arg; argIdx++; } // No filename argument give so read from stdin. else { inFileName = STDIN_FILE_NAME; } // The remaining arguments are optimizer args. optArgs = argv_ + argIdx; optArgCount = argc - argIdx; break; } ++argIdx; } if (action == ProgramAction::PrintHelp) { PrintHelp(); return retVal; } if (passFileName && optArgCount) { wprintf(L"%s", L"Cannot specify both command-line options and an pass " L"option file.\n"); return 1; } if (externalLib) { CW2A externalFnA(externalFn); CW2A externalLibA(externalLib); IFT(g_DxcSupport.InitializeForDll(externalLibA, externalFnA)); } else { IFT(g_DxcSupport.Initialize()); } CComPtr<IDxcBlob> pBlob; CComPtr<IDxcBlob> pOutputModule; CComPtr<IDxcBlobEncoding> pOutputText; CComPtr<IDxcOptimizer> pOptimizer; CComPtr<IDxcBlobEncoding> pPassOpts; std::vector<LPCWSTR> passes; IFT(g_DxcSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer)); switch (action) { case ProgramAction::PrintPasses: pStage = "Printing passes..."; PrintPasses(pOptimizer, false); break; case ProgramAction::PrintPassesWithDetails: pStage = "Printing pass details..."; PrintPasses(pOptimizer, true); break; case ProgramAction::RunOptimizer: pStage = "Optimizer processing"; BlobFromFile(inFileName, &pBlob); ReadFileOpts(passFileName, &pPassOpts, passes, &optArgs, &optArgCount); IFT(pOptimizer->RunOptimizer(pBlob, optArgs, optArgCount, &pOutputModule, &pOutputText)); PrintOptOutput(outFileName, pOutputModule, pOutputText); break; } } catch (const ::hlsl::Exception &hlslException) { try { const char *msg = hlslException.what(); Unicode::acp_char printBuffer[128]; // printBuffer is safe to treat as // UTF-8 because we use ASCII only errors if (msg == nullptr || *msg == '\0') { sprintf_s(printBuffer, _countof(printBuffer), "Operation failed - error code 0x%08x.\n", hlslException.hr); msg = printBuffer; } dxc::WriteUtf8ToConsoleSizeT(msg, strlen(msg)); printf("\n"); } catch (...) { printf("%s failed - unable to retrieve error message.\n", pStage); } return 1; } catch (std::bad_alloc &) { printf("%s failed - out of memory.\n", pStage); return 1; } catch (...) { printf("%s failed - unknown error.\n", pStage); return 1; } return retVal; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxopt/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. # Builds dxopt.exe set( LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} dxcsupport Support # just for assert and raw streams ) add_clang_executable(dxopt dxopt.cpp ) target_link_libraries(dxopt dxcompiler ) if (MINGW) target_link_options(dxopt PRIVATE -mconsole -municode) endif() set_target_properties(dxopt PROPERTIES VERSION ${CLANG_EXECUTABLE_VERSION}) add_dependencies(dxopt dxcompiler) if(UNIX) set(CLANGXX_LINK_OR_COPY create_symlink) # Create a relative symlink set(dxopt_binary "dxopt${CMAKE_EXECUTABLE_SUFFIX}") else() set(CLANGXX_LINK_OR_COPY copy) set(dxopt_binary "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/dxopt${CMAKE_EXECUTABLE_SUFFIX}") endif() install(TARGETS dxopt RUNTIME DESTINATION bin)
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxopt/dxopt.rc
// Copyright (c) Microsoft Corporation. All rights reserved. // #include <windows.h> #include <ntverp.h> #define VER_FILETYPE VFT_DLL #define VER_FILESUBTYPE VFT_UNKNOWN #define VER_FILEDESCRIPTION_STR "DX Optimizer" #define VER_INTERNALNAME_STR "DX Optimizer" #define VER_ORIGINALFILENAME_STR "dxopt.exe" #include <common.ver>
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxclib/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. # Builds dxclib if (MSVC) find_package(DiaSDK REQUIRED) # Used for constants and declarations. endif (MSVC) set( LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} dxcsupport DXIL DxilContainer HLSL Option # option library Support # just for assert and raw streams ) add_clang_library(dxclib dxc.cpp ) if (MINGW) target_link_options(dxclib PUBLIC -mconsole -municode) target_link_libraries(dxclib PRIVATE version) endif() if(ENABLE_SPIRV_CODEGEN) target_link_libraries(dxclib PRIVATE SPIRV-Tools) target_link_libraries(dxclib PRIVATE clangSPIRV) endif() if (MSVC) include_directories(AFTER ${DIASDK_INCLUDE_DIRS}) endif (MSVC) target_compile_definitions(dxclib PRIVATE VERSION_STRING_SUFFIX=" for ${CMAKE_SYSTEM_NAME}") add_dependencies(dxclib TablegenHLSLOptions dxcompiler)
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxclib/dxc.h
/////////////////////////////////////////////////////////////////////////////// // // // dxc.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides wrappers to dxc main function. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __DXC_DXCLIB__ #define __DXC_DXCLIB__ namespace llvm { class raw_ostream; } namespace dxc { class DxcDllSupport; // Writes compiler version info to stream void WriteDxCompilerVersionInfo(llvm::raw_ostream &OS, const char *ExternalLib, const char *ExternalFn, dxc::DxcDllSupport &DxcSupport); void WriteDXILVersionInfo(llvm::raw_ostream &OS, dxc::DxcDllSupport &DxilSupport); #ifdef _WIN32 int main(int argc, const wchar_t **argv_); #else int main(int argc, const char **argv_); #endif // _WIN32 } // namespace dxc #endif // __DXC_DXCLIB__
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxclib/dxc.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxc.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides the entry point for the dxc console program. // // // /////////////////////////////////////////////////////////////////////////////// // // Some unimplemented flags as compared to fxc: // // /compress - Compress DX10 shader bytecode from files. // /decompress - Decompress DX10 shader bytecode from first file. // /Fx <file> - Output assembly code and hex listing file. // /Fl <file> - Output a library. // /Gch - Compile as a child effect for fx_4_x profiles. // /Gdp - Disable effect performance mode. // /Gec - Enable backwards compatibility mode. // /Ges - Enable strict mode. // /Gpp - Force partial precision. // /Lx - Output hexadecimal literals // /Op - Disable preshaders // // Unimplemented but on roadmap: // // /matchUAVs - Match template shader UAV slot allocations in the current // shader /mergeUAVs - Merge UAV slot allocations of template shader and the // current shader /Ni - Output instruction numbers in assembly listings // /No - Output instruction byte offset in assembly listings // /Qstrip_reflect // /res_may_alias // /shtemplate // /verifyrootsignature // #include "dxc.h" #include "dxc/Support/Global.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "dxc/dxcerrors.h" #include <sstream> #include <string> #include <vector> #include "dxc/DXIL/DxilShaderModel.h" #include "dxc/DxilContainer/DxilContainer.h" #include "dxc/DxilRootSignature/DxilRootSignature.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/dxcapi.use.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.h" #include "dxc/dxcapi.internal.h" #include "dxc/dxctools.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #ifdef _WIN32 #include <comdef.h> #include <dia2.h> #endif #include <algorithm> #include <unordered_map> #ifdef _WIN32 #pragma comment(lib, "version.lib") #endif // SPIRV Change Starts #ifdef ENABLE_SPIRV_CODEGEN #include "spirv-tools/libspirv.hpp" #include "clang/SPIRV/FeatureManager.h" static bool DisassembleSpirv(IDxcBlob *binaryBlob, IDxcLibrary *library, IDxcBlobEncoding **assemblyBlob, bool withColor, bool withByteOffset, spv_target_env target_env) { if (!binaryBlob) return true; size_t num32BitWords = (binaryBlob->GetBufferSize() + 3) / 4; std::string binaryStr((char *)binaryBlob->GetBufferPointer(), binaryBlob->GetBufferSize()); binaryStr.resize(num32BitWords * 4, 0); std::vector<uint32_t> words; words.resize(num32BitWords, 0); memcpy(words.data(), binaryStr.data(), binaryStr.size()); std::string assembly; spvtools::SpirvTools spirvTools(target_env); uint32_t options = (SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES | SPV_BINARY_TO_TEXT_OPTION_INDENT); if (withColor) options |= SPV_BINARY_TO_TEXT_OPTION_COLOR; if (withByteOffset) options |= SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET; if (!spirvTools.Disassemble(words, &assembly, options)) return false; IFT(library->CreateBlobWithEncodingOnHeapCopy( assembly.data(), assembly.size(), CP_UTF8, assemblyBlob)); return true; } #endif // SPIRV Change Ends inline bool wcseq(LPCWSTR a, LPCWSTR b) { return (a == nullptr && b == nullptr) || (a != nullptr && b != nullptr && wcscmp(a, b) == 0); } using namespace dxc; using namespace llvm::opt; using namespace hlsl::options; class DxcContext { private: DxcOpts &m_Opts; DxcDllSupport &m_dxcSupport; int ActOnBlob(IDxcBlob *pBlob); int ActOnBlob(IDxcBlob *pBlob, IDxcBlob *pDebugBlob, LPCWSTR pDebugBlobName); void UpdatePart(IDxcBlob *pBlob, IDxcBlob **ppResult); bool UpdatePartRequired(); void WriteHeader(IDxcBlobEncoding *pDisassembly, IDxcBlob *pCode, llvm::Twine &pVariableName, LPCWSTR pPath); HRESULT ReadFileIntoPartContent(hlsl::DxilFourCC fourCC, LPCWSTR fileName, IDxcBlob **ppResult); // Dia is only supported on Windows. #ifdef _WIN32 // TODO : Refactor two functions below. There are duplicate functions in // DxcContext in dxa.cpp HRESULT GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob, IDiaTable **ppTable, LPCWSTR tableName); #endif // _WIN32 HRESULT FindModuleBlob(hlsl::DxilFourCC fourCC, IDxcBlob *pSource, IDxcLibrary *pLibrary, IDxcBlob **ppTargetBlob); void ExtractRootSignature(IDxcBlob *pBlob, IDxcBlob **ppResult); int VerifyRootSignature(); template <typename TInterface> HRESULT CreateInstance(REFCLSID clsid, TInterface **pResult) { return m_dxcSupport.CreateInstance(clsid, pResult); } public: DxcContext(DxcOpts &Opts, DxcDllSupport &dxcSupport) : m_Opts(Opts), m_dxcSupport(dxcSupport) {} int Compile(); void Recompile(IDxcBlob *pSource, IDxcLibrary *pLibrary, IDxcCompiler *pCompiler, std::vector<LPCWSTR> &args, std::wstring &outputPDBPath, CComPtr<IDxcBlob> &pDebugBlob, IDxcOperationResult **pCompileResult); int DumpBinary(); int Link(); void Preprocess(); void GetCompilerVersionInfo(llvm::raw_string_ostream &OS); }; static void WriteBlobToFile(IDxcBlob *pBlob, llvm::StringRef FName, UINT32 defaultTextCodePage) { ::dxc::WriteBlobToFile(pBlob, StringRefWide(FName), defaultTextCodePage); } static void WritePartToFile(IDxcBlob *pBlob, hlsl::DxilFourCC CC, llvm::StringRef FName) { const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike( pBlob->GetBufferPointer(), pBlob->GetBufferSize()); if (!pContainer) { throw hlsl::Exception(E_FAIL, "Unable to find required part in blob"); } hlsl::DxilPartIsType pred(CC); hlsl::DxilPartIterator it = std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer), pred); if (it == hlsl::end(pContainer)) { throw hlsl::Exception(E_FAIL, "Unable to find required part in blob"); } const char *pData = hlsl::GetDxilPartData(*it); DWORD dataLen = (*it)->PartSize; StringRefWide WideName(FName); CHandle file(CreateFileW(WideName, GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); if (file == INVALID_HANDLE_VALUE) { IFT_Data(HRESULT_FROM_WIN32(GetLastError()), WideName); } DWORD written; if (FALSE == WriteFile(file, pData, dataLen, &written, nullptr)) { IFT_Data(HRESULT_FROM_WIN32(GetLastError()), WideName); } } static void WriteDxcOutputToFile(DXC_OUT_KIND kind, IDxcResult *pResult, UINT32 textCodePage) { if (pResult->HasOutput(kind)) { CComPtr<IDxcBlob> pData; CComPtr<IDxcBlobWide> pName; IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pData), &pName)); if (pName && pName->GetStringLength() > 0) WriteBlobToFile(pData, pName->GetStringPointer(), textCodePage); } } static bool StringBlobEqualWide(IDxcBlobWide *pBlob, const WCHAR *pStr) { size_t uSize = wcslen(pStr); if (pBlob && pBlob->GetStringLength() == uSize) { return 0 == memcmp(pBlob->GetBufferPointer(), pStr, pBlob->GetBufferSize()); } return false; } static void WriteDxcExtraOuputs(IDxcResult *pResult) { DXC_OUT_KIND kind = DXC_OUT_EXTRA_OUTPUTS; if (!pResult->HasOutput(kind)) { return; } CComPtr<IDxcExtraOutputs> pOutputs; CComPtr<IDxcBlobWide> pName; IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pOutputs), &pName)); UINT32 uOutputCount = pOutputs->GetOutputCount(); for (UINT32 i = 0; i < uOutputCount; i++) { CComPtr<IDxcBlobWide> pFileName; CComPtr<IDxcBlobWide> pType; CComPtr<IDxcBlob> pBlob; HRESULT hr = pOutputs->GetOutput(i, IID_PPV_ARGS(&pBlob), &pType, &pFileName); // Not a blob if (FAILED(hr)) continue; UINT32 uCodePage = CP_ACP; CComPtr<IDxcBlobEncoding> pBlobEncoding; if (SUCCEEDED(pBlob.QueryInterface(&pBlobEncoding))) { BOOL bKnown = FALSE; UINT32 uKnownCodePage = CP_ACP; IFT(pBlobEncoding->GetEncoding(&bKnown, &uKnownCodePage)); if (bKnown) { uCodePage = uKnownCodePage; } } if (pFileName && pFileName->GetStringLength() > 0) { if (StringBlobEqualWide(pFileName, DXC_EXTRA_OUTPUT_NAME_STDOUT)) { if (uCodePage != CP_ACP) { WriteBlobToConsole(pBlob, STD_OUTPUT_HANDLE); } } else if (StringBlobEqualWide(pFileName, DXC_EXTRA_OUTPUT_NAME_STDERR)) { if (uCodePage != CP_ACP) { WriteBlobToConsole(pBlob, STD_ERROR_HANDLE); } } else { WriteBlobToFile(pBlob, pFileName->GetStringPointer(), uCodePage); } } } } static void WriteDxcOutputToConsole(IDxcResult *pResult, DXC_OUT_KIND kind) { if (!pResult->HasOutput(kind)) return; CComPtr<IDxcBlob> pBlob; IFT(pResult->GetOutput(kind, IID_PPV_ARGS(&pBlob), nullptr)); llvm::StringRef outputString((LPSTR)pBlob->GetBufferPointer(), pBlob->GetBufferSize()); llvm::SmallVector<llvm::StringRef, 20> lines; outputString.split(lines, "\n"); std::string outputStr; llvm::raw_string_ostream SS(outputStr); for (auto line : lines) { SS << "; " << line << "\n"; } WriteUtf8ToConsole(outputStr.data(), outputStr.size()); } std::string getDependencyOutputFileName(llvm::StringRef inputFileName) { return inputFileName.substr(0, inputFileName.rfind('.')).str() + ".d"; } // This function is called either after the compilation is done or /dumpbin // option is provided Performing options that are used to process dxil // container. int DxcContext::ActOnBlob(IDxcBlob *pBlob) { return ActOnBlob(pBlob, nullptr, nullptr); } int DxcContext::ActOnBlob(IDxcBlob *pBlob, IDxcBlob *pDebugBlob, LPCWSTR pDebugBlobName) { int retVal = 0; if (m_Opts.DumpDependencies) { if (!m_Opts.OutputFileForDependencies.empty()) { CComPtr<IDxcBlob> pResult; UpdatePart(pBlob, &pResult); WriteBlobToFile(pResult, m_Opts.OutputFileForDependencies, m_Opts.DefaultTextCodePage); } else if (m_Opts.WriteDependencies) { CComPtr<IDxcBlob> pResult; UpdatePart(pBlob, &pResult); WriteBlobToFile(pResult, getDependencyOutputFileName(m_Opts.InputFile), m_Opts.DefaultTextCodePage); } else { WriteBlobToConsole(pBlob); } return retVal; } // Text output. if (m_Opts.AstDump || m_Opts.OptDump || m_Opts.VerifyDiagnostics) { WriteBlobToConsole(pBlob); return retVal; } // Write the output blob. if (!m_Opts.OutputObject.empty()) { // For backward compatability: fxc requires /Fo for /extractrootsignature if (!m_Opts.ExtractRootSignature) { CComPtr<IDxcBlob> pResult; UpdatePart(pBlob, &pResult); WriteBlobToFile(pResult, m_Opts.OutputObject, m_Opts.DefaultTextCodePage); } } // Verify Root Signature if (!m_Opts.VerifyRootSignatureSource.empty()) { return VerifyRootSignature(); } // Extract and write the PDB/debug information. if (!m_Opts.DebugFile.empty()) { IFTBOOLMSG(m_Opts.GeneratePDB(), E_INVALIDARG, "/Fd specified, but no Debug Info was " "found in the shader, please use the " "/Zi or /Zs switch to generate debug " "information compiling this shader."); if (pDebugBlob != nullptr) { IFTBOOLMSG(pDebugBlobName && *pDebugBlobName, E_INVALIDARG, "/Fd was specified but no debug name was produced"); WriteBlobToFile(pDebugBlob, pDebugBlobName, m_Opts.DefaultTextCodePage); } else { // Note: This is for load from binary case WritePartToFile(pBlob, hlsl::DFCC_ShaderDebugInfoDXIL, m_Opts.DebugFile); } } // Extract and write root signature information. if (m_Opts.ExtractRootSignature) { CComPtr<IDxcBlob> pRootSignatureContainer; ExtractRootSignature(pBlob, &pRootSignatureContainer); WriteBlobToFile(pRootSignatureContainer, m_Opts.OutputObject, m_Opts.DefaultTextCodePage); } // Extract and write private data. if (!m_Opts.ExtractPrivateFile.empty()) { WritePartToFile(pBlob, hlsl::DFCC_PrivateData, m_Opts.ExtractPrivateFile); } // OutputObject suppresses console dump. bool needDisassembly = !m_Opts.OutputHeader.empty() || !m_Opts.AssemblyCode.empty() || (m_Opts.OutputObject.empty() && m_Opts.DebugFile.empty() && m_Opts.ExtractPrivateFile.empty() && m_Opts.VerifyRootSignatureSource.empty() && !m_Opts.ExtractRootSignature); if (!needDisassembly) return retVal; CComPtr<IDxcBlobEncoding> pDisassembleResult; // SPIRV Change Starts #ifdef ENABLE_SPIRV_CODEGEN if (m_Opts.GenSPIRV) { CComPtr<IDxcLibrary> pLibrary; IFT(m_dxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary)); llvm::Optional<spv_target_env> target_env = clang::spirv::FeatureManager::stringToSpvEnvironment( m_Opts.SpirvOptions.targetEnv); IFTBOOLMSG(target_env, E_INVALIDARG, "Cannot parse SPIR-V target env."); IFTBOOLMSG(DisassembleSpirv(pBlob, pLibrary, &pDisassembleResult, m_Opts.ColorCodeAssembly, m_Opts.DisassembleByteOffset, *target_env), E_FAIL, "dxc failed : Internal Compiler Error - " "unable to disassemble generated SPIR-V."); } else { #endif // ENABLE_SPIRV_CODEGEN // SPIRV Change Ends if (m_Opts.IsRootSignatureProfile()) { // keep the same behavior as fxc, people may want to embed the root // signatures in their code bases. CComPtr<IDxcLibrary> pLibrary; IFT(m_dxcSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary)); std::string Message = "Disassembly failed"; IFT(pLibrary->CreateBlobWithEncodingOnHeapCopy( (LPBYTE)&Message[0], Message.size(), CP_ACP, &pDisassembleResult)); } else { CComPtr<IDxcCompiler> pCompiler; IFT(CreateInstance(CLSID_DxcCompiler, &pCompiler)); IFT(pCompiler->Disassemble(pBlob, &pDisassembleResult)); } // SPIRV Change Starts #ifdef ENABLE_SPIRV_CODEGEN } #endif // ENABLE_SPIRV_CODEGEN // SPIRV Change Ends bool disassemblyWritten = false; if (!m_Opts.OutputHeader.empty()) { llvm::Twine varName = m_Opts.VariableName.empty() ? llvm::Twine("g_", m_Opts.EntryPoint) : m_Opts.VariableName; WriteHeader(pDisassembleResult, pBlob, varName, StringRefWide(m_Opts.OutputHeader)); disassemblyWritten = true; } if (!m_Opts.AssemblyCode.empty()) { WriteBlobToFile(pDisassembleResult, m_Opts.AssemblyCode, m_Opts.DefaultTextCodePage); disassemblyWritten = true; } if (!disassemblyWritten) { WriteBlobToConsole(pDisassembleResult); } return retVal; } // Given a dxil container, update the dxil container by processing container // specific options. void DxcContext::UpdatePart(IDxcBlob *pSource, IDxcBlob **ppResult) { DXASSERT(pSource && ppResult, "otherwise blob cannot be updated"); if (!UpdatePartRequired()) { *ppResult = pSource; pSource->AddRef(); return; } CComPtr<IDxcContainerBuilder> pContainerBuilder; CComPtr<IDxcBlob> pResult; IFT(CreateInstance(CLSID_DxcContainerBuilder, &pContainerBuilder)); // Load original container and update blob for each given option IFT(pContainerBuilder->Load(pSource)); // Update parts based on dxc options if (m_Opts.StripDebug) { IFT(pContainerBuilder->RemovePart( hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL)); } if (m_Opts.StripPrivate) { IFT(pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_PrivateData)); } if (m_Opts.StripRootSignature) { IFT(pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature)); } if (!m_Opts.PrivateSource.empty()) { CComPtr<IDxcBlob> privateBlob; IFT(ReadFileIntoPartContent(hlsl::DxilFourCC::DFCC_PrivateData, StringRefWide(m_Opts.PrivateSource), &privateBlob)); // setprivate option can replace existing private part. // Try removing the private data if exists pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_PrivateData); IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_PrivateData, privateBlob)); } if (!m_Opts.RootSignatureSource.empty()) { // set rootsignature assumes that the given input is a dxil container. // We only want to add RTS0 part to the container builder. CComPtr<IDxcBlob> RootSignatureBlob; IFT(ReadFileIntoPartContent(hlsl::DxilFourCC::DFCC_RootSignature, StringRefWide(m_Opts.RootSignatureSource), &RootSignatureBlob)); // setrootsignature option can replace existing rootsignature part // Try removing rootsignature if exists pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature); IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_RootSignature, RootSignatureBlob)); } // Get the final blob from container builder CComPtr<IDxcOperationResult> pBuilderResult; IFT(pContainerBuilder->SerializeContainer(&pBuilderResult)); if (!m_Opts.OutputWarningsFile.empty()) { CComPtr<IDxcBlobEncoding> pErrors; IFT(pBuilderResult->GetErrorBuffer(&pErrors)); if (pErrors != nullptr) { WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile, m_Opts.DefaultTextCodePage); } } else { WriteOperationErrorsToConsole(pBuilderResult, m_Opts.OutputWarnings); } HRESULT status; IFT(pBuilderResult->GetStatus(&status)); IFT(status); IFT(pBuilderResult->GetResult(ppResult)); } bool DxcContext::UpdatePartRequired() { return (m_Opts.StripDebug || m_Opts.StripPrivate || m_Opts.StripRootSignature || !m_Opts.PrivateSource.empty() || !m_Opts.RootSignatureSource.empty()) && (m_Opts.Link || m_Opts.DumpBin || !m_Opts.Preprocess.empty()); } // This function reads the file from input file and constructs a blob with // fourCC parts Used for setprivate and setrootsignature option HRESULT DxcContext::ReadFileIntoPartContent(hlsl::DxilFourCC fourCC, LPCWSTR fileName, IDxcBlob **ppResult) { DXASSERT(fourCC == hlsl::DxilFourCC::DFCC_PrivateData || fourCC == hlsl::DxilFourCC::DFCC_RootSignature, "Otherwise we provided wrong part to read for updating part."); // Read result, if it's private data, then return the blob if (fourCC == hlsl::DxilFourCC::DFCC_PrivateData) { CComPtr<IDxcBlobEncoding> pResult; ReadFileIntoBlob(m_dxcSupport, fileName, &pResult); *ppResult = pResult.Detach(); } // If root signature, check if it's a dxil container that contains // rootsignature part, then construct a blob of root signature part if (fourCC == hlsl::DxilFourCC::DFCC_RootSignature) { CComPtr<IDxcBlob> pResult; CComHeapPtr<BYTE> pData; DWORD dataSize; IFT(hlsl::ReadBinaryFile(fileName, (void **)&pData, &dataSize)); DXASSERT(pData != nullptr, "otherwise ReadBinaryFile should throw an exception"); hlsl::DxilContainerHeader *pHeader = hlsl::IsDxilContainerLike(pData.m_pData, dataSize); IFRBOOL(hlsl::IsValidDxilContainer(pHeader, dataSize), E_INVALIDARG); hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_RootSignature); IFRBOOL(pPartHeader != nullptr, E_INVALIDARG); hlsl::DxcCreateBlobOnHeapCopy(hlsl::GetDxilPartData(pPartHeader), pPartHeader->PartSize, &pResult); *ppResult = pResult.Detach(); } return S_OK; } // Constructs a dxil container builder with only root signature part. // Right now IDxcContainerBuilder assumes that we are building a full dxil // container, but we are building a container with only rootsignature part void DxcContext::ExtractRootSignature(IDxcBlob *pBlob, IDxcBlob **ppResult) { DXASSERT_NOMSG(pBlob != nullptr && ppResult != nullptr); const hlsl::DxilContainerHeader *pHeader = (hlsl::DxilContainerHeader *)(pBlob->GetBufferPointer()); IFTBOOL(hlsl::IsValidDxilContainer(pHeader, pHeader->ContainerSizeInBytes), DXC_E_CONTAINER_INVALID); const hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_RootSignature); IFTBOOL(pPartHeader != nullptr, DXC_E_MISSING_PART); // Get new header and allocate memory for new container hlsl::DxilContainerHeader newHeader; uint32_t containerSize = hlsl::GetDxilContainerSizeFromParts(1, pPartHeader->PartSize); hlsl::InitDxilContainer(&newHeader, 1, containerSize); CComPtr<hlsl::AbstractMemoryStream> pMemoryStream; IFT(hlsl::CreateMemoryStream(DxcGetThreadMallocNoRef(), &pMemoryStream)); ULONG cbWritten; // Write Container Header IFT(pMemoryStream->Write(&newHeader, sizeof(hlsl::DxilContainerHeader), &cbWritten)); IFTBOOL(cbWritten == sizeof(hlsl::DxilContainerHeader), E_OUTOFMEMORY); // Write Part Offset uint32_t offset = sizeof(hlsl::DxilContainerHeader) + hlsl::GetOffsetTableSize(1); IFT(pMemoryStream->Write(&offset, sizeof(uint32_t), &cbWritten)); IFTBOOL(cbWritten == sizeof(uint32_t), E_OUTOFMEMORY); // Write Root Signature Header IFT(pMemoryStream->Write(pPartHeader, sizeof(hlsl::DxilPartHeader), &cbWritten)); IFTBOOL(cbWritten == sizeof(hlsl::DxilPartHeader), E_OUTOFMEMORY); const char *partContent = hlsl::GetDxilPartData(pPartHeader); // Write Root Signature Content IFT(pMemoryStream->Write(partContent, pPartHeader->PartSize, &cbWritten)); IFTBOOL(cbWritten == pPartHeader->PartSize, E_OUTOFMEMORY); // Return Result CComPtr<IDxcBlob> pResult; IFT(pMemoryStream->QueryInterface(&pResult)); *ppResult = pResult.Detach(); } int DxcContext::VerifyRootSignature() { // Get dxil container from file CComPtr<IDxcBlobEncoding> pSource; ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource); hlsl::DxilContainerHeader *pSourceHeader = (hlsl::DxilContainerHeader *)pSource->GetBufferPointer(); IFTBOOLMSG(hlsl::IsValidDxilContainer(pSourceHeader, pSourceHeader->ContainerSizeInBytes), E_INVALIDARG, "invalid DXIL container to verify."); // Get rootsignature from file CComPtr<IDxcBlob> pRootSignature; IFTMSG(ReadFileIntoPartContent( hlsl::DxilFourCC::DFCC_RootSignature, StringRefWide(m_Opts.VerifyRootSignatureSource), &pRootSignature), "invalid root signature to verify."); // TODO : Right now we are just going to bild a new blob with updated root // signature to verify root signature Since dxil container builder will verify // on its behalf. This does unnecessary memory allocation. We can improve this // later. CComPtr<IDxcContainerBuilder> pContainerBuilder; IFT(CreateInstance(CLSID_DxcContainerBuilder, &pContainerBuilder)); IFT(pContainerBuilder->Load(pSource)); // Try removing root signature if it already exists pContainerBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature); IFT(pContainerBuilder->AddPart(hlsl::DxilFourCC::DFCC_RootSignature, pRootSignature)); CComPtr<IDxcOperationResult> pOperationResult; pContainerBuilder->SerializeContainer(&pOperationResult); HRESULT status = E_FAIL; CComPtr<IDxcBlob> pResult; IFT(pOperationResult->GetStatus(&status)); if (FAILED(status)) { if (!m_Opts.OutputWarningsFile.empty()) { CComPtr<IDxcBlobEncoding> pErrors; IFT(pOperationResult->GetErrorBuffer(&pErrors)); WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile, m_Opts.DefaultTextCodePage); } else { WriteOperationErrorsToConsole(pOperationResult, m_Opts.OutputWarnings); } return 1; } else { printf("root signature verification succeeded."); return 0; } } class DxcIncludeHandlerForInjectedSources : public IDxcIncludeHandler { private: DXC_MICROCOM_REF_FIELD(m_dwRef) public: DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef) DxcIncludeHandlerForInjectedSources() : m_dwRef(0){}; std::unordered_map<std::wstring, CComPtr<IDxcBlob>> includeFiles; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject); } HRESULT insertIncludeFile(LPCWSTR pFilename, IDxcBlobEncoding *pBlob, UINT32 dataLen) { try { #ifdef _WIN32 includeFiles.try_emplace(std::wstring(pFilename), pBlob); #else // Note: try_emplace is only available in C++17 on Linux. // try_emplace does nothing if the key already exists in the map. if (includeFiles.find(std::wstring(pFilename)) == includeFiles.end()) includeFiles.emplace(std::wstring(pFilename), pBlob); #endif // _WIN32 } CATCH_CPP_RETURN_HRESULT() return S_OK; } HRESULT STDMETHODCALLTYPE LoadSource(LPCWSTR pFilename, IDxcBlob **ppIncludeSource) override { try { // Convert pFilename into native form for indexing as is done when the MD // is created std::string FilenameStr8 = Unicode::WideToUTF8StringOrThrow(pFilename); llvm::SmallString<128> NormalizedPath; llvm::sys::path::native(FilenameStr8, NormalizedPath); std::wstring FilenameStr16 = Unicode::UTF8ToWideStringOrThrow(NormalizedPath.c_str()); *ppIncludeSource = includeFiles.at(FilenameStr16); (*ppIncludeSource)->AddRef(); } CATCH_CPP_RETURN_HRESULT() return S_OK; } }; void DxcContext::Recompile(IDxcBlob *pSource, IDxcLibrary *pLibrary, IDxcCompiler *pCompiler, std::vector<LPCWSTR> &args, std::wstring &outputPDBPath, CComPtr<IDxcBlob> &pDebugBlob, IDxcOperationResult **ppCompileResult) { CComPtr<IDxcPdbUtils> pPdbUtils; IFT(CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils)); IFT(pPdbUtils->Load(pSource)); UINT32 uNumFlags = 0; IFT(pPdbUtils->GetFlagCount(&uNumFlags)); std::vector<const WCHAR *> NewArgs; std::vector<std::wstring> NewArgsStorage; for (UINT32 i = 0; i < uNumFlags; i++) { CComBSTR pFlag; IFT(pPdbUtils->GetFlag(i, &pFlag)); NewArgsStorage.push_back(std::wstring(pFlag)); } for (const std::wstring &flag : NewArgsStorage) NewArgs.push_back(flag.c_str()); UINT32 uNumDefines = 0; IFT(pPdbUtils->GetDefineCount(&uNumDefines)); std::vector<std::wstring> NewDefinesStorage; std::vector<DxcDefine> NewDefines; for (UINT32 i = 0; i < uNumDefines; i++) { CComBSTR pDefine; IFT(pPdbUtils->GetDefine(i, &pDefine)); NewDefinesStorage.push_back(std::wstring(pDefine)); } for (std::wstring &Define : NewDefinesStorage) { wchar_t *pDefineStart = &Define[0]; wchar_t *pDefineEnd = pDefineStart + Define.size(); DxcDefine D = {}; D.Name = pDefineStart; D.Value = nullptr; for (wchar_t *pCursor = pDefineStart; pCursor < pDefineEnd; ++pCursor) { if (*pCursor == L'=') { *pCursor = L'\0'; D.Value = (pCursor + 1); break; } } NewDefines.push_back(D); } CComBSTR pMainFileName; CComBSTR pTargetProfile; CComBSTR pEntryPoint; IFT(pPdbUtils->GetMainFileName(&pMainFileName)); IFT(pPdbUtils->GetTargetProfile(&pTargetProfile)); IFT(pPdbUtils->GetEntryPoint(&pEntryPoint)); CComPtr<IDxcBlobEncoding> pCompileSource; CComPtr<DxcIncludeHandlerForInjectedSources> pIncludeHandler = new DxcIncludeHandlerForInjectedSources(); UINT32 uSourceCount = 0; IFT(pPdbUtils->GetSourceCount(&uSourceCount)); for (UINT32 i = 0; i < uSourceCount; i++) { CComPtr<IDxcBlobEncoding> pSourceFile; CComBSTR pFileName; IFT(pPdbUtils->GetSource(i, &pSourceFile)); IFT(pPdbUtils->GetSourceName(i, &pFileName)); IFT(pIncludeHandler->insertIncludeFile(pFileName, pSourceFile, 0)); if (pMainFileName == pFileName) { // Transfer pSourceFile to avoid extra AddRef+Release. pCompileSource.Attach(pSourceFile.Detach()); } } CComPtr<IDxcOperationResult> pResult; if (!m_Opts.DebugFile.empty()) { CComPtr<IDxcCompiler2> pCompiler2; CComHeapPtr<WCHAR> pDebugName; Unicode::UTF8ToWideString(m_Opts.DebugFile.str().c_str(), &outputPDBPath); IFT(pCompiler->QueryInterface(&pCompiler2)); IFT(pCompiler2->CompileWithDebug( pCompileSource, pMainFileName, pEntryPoint, pTargetProfile, NewArgs.data(), NewArgs.size(), NewDefines.data(), NewDefines.size(), pIncludeHandler, &pResult, &pDebugName, &pDebugBlob)); if (pDebugName.m_pData && m_Opts.DebugFileIsDirectory()) { outputPDBPath += pDebugName.m_pData; } } else { IFT(pCompiler->Compile(pCompileSource, pMainFileName, pEntryPoint, pTargetProfile, NewArgs.data(), NewArgs.size(), NewDefines.data(), NewDefines.size(), pIncludeHandler, &pResult)); } *ppCompileResult = pResult.Detach(); } int DxcContext::Compile() { CComPtr<IDxcCompiler> pCompiler; CComPtr<IDxcOperationResult> pCompileResult; CComPtr<IDxcBlob> pDebugBlob; std::wstring outputPDBPath; { CComPtr<IDxcBlobEncoding> pSource; std::vector<std::wstring> argStrings; CopyArgsToWStrings(m_Opts.Args, CoreOption, argStrings); std::vector<LPCWSTR> args; args.reserve(argStrings.size()); for (const std::wstring &a : argStrings) args.push_back(a.data()); if (m_Opts.AstDump) args.push_back(L"-ast-dump"); CComPtr<IDxcLibrary> pLibrary; IFT(CreateInstance(CLSID_DxcLibrary, &pLibrary)); IFT(CreateInstance(CLSID_DxcCompiler, &pCompiler)); ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource); IFTARG(pSource->GetBufferSize() >= 4); if (m_Opts.RecompileFromBinary) { Recompile(pSource, pLibrary, pCompiler, args, outputPDBPath, pDebugBlob, &pCompileResult); } else { CComPtr<IDxcIncludeHandler> pIncludeHandler; IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler)); // Upgrade profile to 6.0 version from minimum recognized shader model llvm::StringRef TargetProfile = m_Opts.TargetProfile; const hlsl::ShaderModel *SM = hlsl::ShaderModel::GetByName(m_Opts.TargetProfile.str().c_str()); if (SM->IsValid() && SM->GetMajor() < 6) { TargetProfile = hlsl::ShaderModel::Get(SM->GetKind(), 6, 0)->GetName(); std::string versionWarningString = "warning: Promoting older shader model profile to 6.0 version."; fprintf(stderr, "%s\n", versionWarningString.data()); if (!SM->IsSM51Plus()) { // Add flag for backcompat with SM 5.0 resource reservation args.push_back(L"-flegacy-resource-reservation"); } } if (!m_Opts.DebugFile.empty()) { CComPtr<IDxcCompiler2> pCompiler2; CComHeapPtr<WCHAR> pDebugName; Unicode::UTF8ToWideString(m_Opts.DebugFile.str().c_str(), &outputPDBPath); IFT(pCompiler.QueryInterface(&pCompiler2)); IFT(pCompiler2->CompileWithDebug( pSource, StringRefWide(m_Opts.InputFile), StringRefWide(m_Opts.EntryPoint), StringRefWide(TargetProfile), args.data(), args.size(), m_Opts.Defines.data(), m_Opts.Defines.size(), pIncludeHandler, &pCompileResult, &pDebugName, &pDebugBlob)); if (pDebugName.m_pData && m_Opts.DebugFileIsDirectory()) { outputPDBPath += pDebugName.m_pData; } } else { IFT(pCompiler->Compile( pSource, StringRefWide(m_Opts.InputFile), StringRefWide(m_Opts.EntryPoint), StringRefWide(TargetProfile), args.data(), args.size(), m_Opts.Defines.data(), m_Opts.Defines.size(), pIncludeHandler, &pCompileResult)); } } // When compiling we don't embed debug info if options don't ask for it. // If user specified /Qstrip_debug, remove from m_Opts now so we don't // try to modify the container to strip debug info that isn't there. if (!m_Opts.EmbedDebugInfo()) { m_Opts.StripDebug = false; } } if (!m_Opts.OutputWarningsFile.empty()) { CComPtr<IDxcBlobEncoding> pErrors; IFT(pCompileResult->GetErrorBuffer(&pErrors)); WriteBlobToFile(pErrors, m_Opts.OutputWarningsFile, m_Opts.DefaultTextCodePage); } else { WriteOperationErrorsToConsole(pCompileResult, m_Opts.OutputWarnings); } HRESULT status; IFT(pCompileResult->GetStatus(&status)); if (SUCCEEDED(status) || m_Opts.AstDump || m_Opts.OptDump || m_Opts.DumpDependencies || m_Opts.VerifyDiagnostics) { CComPtr<IDxcBlob> pProgram; IFT(pCompileResult->GetResult(&pProgram)); if (pProgram.p != nullptr) { ActOnBlob(pProgram.p, pDebugBlob, outputPDBPath.c_str()); // Now write out extra parts CComPtr<IDxcResult> pResult; if (SUCCEEDED(pCompileResult->QueryInterface(&pResult))) { WriteDxcOutputToConsole(pResult, DXC_OUT_REMARKS); WriteDxcOutputToConsole(pResult, DXC_OUT_TIME_REPORT); if (m_Opts.TimeTrace == "-") WriteDxcOutputToConsole(pResult, DXC_OUT_TIME_TRACE); else if (!m_Opts.TimeTrace.empty()) { CComPtr<IDxcBlob> pData; CComPtr<IDxcBlobWide> pName; IFT(pResult->GetOutput(DXC_OUT_TIME_TRACE, IID_PPV_ARGS(&pData), &pName)); WriteBlobToFile(pData, m_Opts.TimeTrace, m_Opts.DefaultTextCodePage); } WriteDxcOutputToFile(DXC_OUT_ROOT_SIGNATURE, pResult, m_Opts.DefaultTextCodePage); WriteDxcOutputToFile(DXC_OUT_SHADER_HASH, pResult, m_Opts.DefaultTextCodePage); WriteDxcOutputToFile(DXC_OUT_REFLECTION, pResult, m_Opts.DefaultTextCodePage); WriteDxcExtraOuputs(pResult); } } } return status; } int DxcContext::Link() { CComPtr<IDxcLinker> pLinker; IFT(CreateInstance(CLSID_DxcLinker, &pLinker)); llvm::StringRef InputFiles = m_Opts.InputFile; llvm::StringRef InputFilesRef(InputFiles); llvm::SmallVector<llvm::StringRef, 2> InputFileList; InputFilesRef.split(InputFileList, ";"); std::vector<std::wstring> wInputFiles; wInputFiles.reserve(InputFileList.size()); std::vector<LPCWSTR> wpInputFiles; wpInputFiles.reserve(InputFileList.size()); for (auto &file : InputFileList) { wInputFiles.emplace_back(StringRefWide(file.str())); wpInputFiles.emplace_back(wInputFiles.back().c_str()); CComPtr<IDxcBlobEncoding> pLib; ReadFileIntoBlob(m_dxcSupport, wInputFiles.back().c_str(), &pLib); IFT(pLinker->RegisterLibrary(wInputFiles.back().c_str(), pLib)); } CComPtr<IDxcOperationResult> pLinkResult; std::vector<std::wstring> argStrings; CopyArgsToWStrings(m_Opts.Args, CoreOption, argStrings); std::vector<LPCWSTR> args; args.reserve(argStrings.size()); for (const std::wstring &a : argStrings) args.push_back(a.data()); IFT(pLinker->Link(StringRefWide(m_Opts.EntryPoint), StringRefWide(m_Opts.TargetProfile), wpInputFiles.data(), wpInputFiles.size(), args.data(), args.size(), &pLinkResult)); HRESULT status; IFT(pLinkResult->GetStatus(&status)); if (SUCCEEDED(status)) { CComPtr<IDxcBlob> pContainer; IFT(pLinkResult->GetResult(&pContainer)); if (pContainer.p != nullptr) { ActOnBlob(pContainer.p); } } else { CComPtr<IDxcBlobEncoding> pErrors; IFT(pLinkResult->GetErrorBuffer(&pErrors)); if (pErrors != nullptr) { printf("Link failed:\n%s", static_cast<char *>(pErrors->GetBufferPointer())); } return 1; } return 0; } int DxcContext::DumpBinary() { CComPtr<IDxcBlobEncoding> pSource; ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource); return ActOnBlob(pSource.p); } void DxcContext::Preprocess() { DXASSERT(!m_Opts.Preprocess.empty(), "else option reading should have failed"); CComPtr<IDxcCompiler> pCompiler; CComPtr<IDxcOperationResult> pPreprocessResult; CComPtr<IDxcBlobEncoding> pSource; std::vector<std::wstring> argStrings; CopyArgsToWStrings(m_Opts.Args, CoreOption, argStrings); std::vector<LPCWSTR> args; args.reserve(argStrings.size()); for (const std::wstring &a : argStrings) args.push_back(a.data()); CComPtr<IDxcLibrary> pLibrary; CComPtr<IDxcIncludeHandler> pIncludeHandler; IFT(CreateInstance(CLSID_DxcLibrary, &pLibrary)); IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler)); ReadFileIntoBlob(m_dxcSupport, StringRefWide(m_Opts.InputFile), &pSource); IFT(CreateInstance(CLSID_DxcCompiler, &pCompiler)); IFT(pCompiler->Preprocess(pSource, StringRefWide(m_Opts.InputFile), args.data(), args.size(), m_Opts.Defines.data(), m_Opts.Defines.size(), pIncludeHandler, &pPreprocessResult)); WriteOperationErrorsToConsole(pPreprocessResult, m_Opts.OutputWarnings); HRESULT status; IFT(pPreprocessResult->GetStatus(&status)); if (SUCCEEDED(status)) { CComPtr<IDxcBlob> pProgram; IFT(pPreprocessResult->GetResult(&pProgram)); WriteBlobToFile(pProgram, m_Opts.Preprocess, m_Opts.DefaultTextCodePage); } } void DxcContext::WriteHeader(IDxcBlobEncoding *pDisassembly, IDxcBlob *pCode, llvm::Twine &pVariableName, LPCWSTR pFileName) { // Use older interface for compatibility with older DLL. CComPtr<IDxcLibrary> pLibrary; IFT(CreateInstance(CLSID_DxcLibrary, &pLibrary)); std::string s; llvm::raw_string_ostream OS(s); { // Not safe to assume pDisassembly is utf8, must GetBlobAsUtf8 first. CComPtr<IDxcBlobEncoding> pDisasmEncoding; IFT(pLibrary->GetBlobAsUtf8(pDisassembly, &pDisasmEncoding)); // Don't fail if this QI doesn't succeed (older dll, perhaps) CComPtr<IDxcBlobUtf8> pDisasmUtf8; pDisasmEncoding->QueryInterface(&pDisasmUtf8); LPCSTR pBytes = pDisasmUtf8 ? pDisasmUtf8->GetStringPointer() : (LPCSTR)pDisasmEncoding->GetBufferPointer(); // IDxcBlobUtf8's GetStringLength will return length without null character size_t len = pDisasmUtf8 ? pDisasmUtf8->GetStringLength() : pDisasmEncoding->GetBufferSize(); // Just in case there are still any null characters at the end, get rid of // them. while (len && pBytes[len - 1] == '\0') len -= 1; // Note: with \r\n line endings, writing the disassembly could be a simple // WriteBlobToHandle with a prior and following WriteString for #ifs OS << "#if 0\r\n"; s.reserve(len + len * 0.1f); // rough estimate for (size_t i = 0; i < len; ++i) { if (pBytes[i] == '\n') OS << '\r'; OS << pBytes[i]; } OS << "\r\n#endif\r\n"; } { OS << "\r\nconst unsigned char " << pVariableName << "[] = {"; const uint8_t *pBytes = (const uint8_t *)pCode->GetBufferPointer(); size_t len = pCode->GetBufferSize(); s.reserve(100 + len * 6 + (len / 12) * 3); // rough estimate for (size_t i = 0; i < len; ++i) { if (i != 0) OS << ','; if ((i % 12) == 0) OS << "\r\n "; OS << " 0x"; if (pBytes[i] < 0x10) OS << '0'; OS.write_hex(pBytes[i]); } OS << "\r\n};\r\n"; } OS.flush(); // Respect user's -encoding option CComPtr<IDxcBlobEncoding> pOutBlob; pLibrary->CreateBlobWithEncodingFromPinned(s.data(), s.length(), DXC_CP_UTF8, &pOutBlob); WriteBlobToFile(pOutBlob, pFileName, m_Opts.DefaultTextCodePage); } // Finds DXIL module from the blob assuming blob is either DxilContainer, // DxilPartHeader, or DXIL module HRESULT DxcContext::FindModuleBlob(hlsl::DxilFourCC fourCC, IDxcBlob *pSource, IDxcLibrary *pLibrary, IDxcBlob **ppTargetBlob) { if (!pSource || !pLibrary || !ppTargetBlob) return E_INVALIDARG; const UINT32 BC_C0DE = ((INT32)(INT8)'B' | (INT32)(INT8)'C' << 8 | (INT32)0xDEC0 << 16); // BC0xc0de in big endian if (BC_C0DE == *(UINT32 *)pSource->GetBufferPointer()) { *ppTargetBlob = pSource; pSource->AddRef(); return S_OK; } const char *pBitcode = nullptr; const hlsl::DxilPartHeader *pDxilPartHeader = (hlsl::DxilPartHeader *) pSource->GetBufferPointer(); // Initialize assuming that source is // starting with DXIL part if (hlsl::IsValidDxilContainer( (hlsl::DxilContainerHeader *)pSource->GetBufferPointer(), pSource->GetBufferSize())) { hlsl::DxilContainerHeader *pDxilContainerHeader = (hlsl::DxilContainerHeader *)pSource->GetBufferPointer(); pDxilPartHeader = hlsl::GetDxilPartByType(pDxilContainerHeader, fourCC); IFTBOOL(pDxilPartHeader != nullptr, DXC_E_CONTAINER_MISSING_DEBUG); } if (fourCC == pDxilPartHeader->PartFourCC) { UINT32 pBlobSize; const hlsl::DxilProgramHeader *pDxilProgramHeader = (const hlsl::DxilProgramHeader *)(pDxilPartHeader + 1); hlsl::GetDxilProgramBitcode(pDxilProgramHeader, &pBitcode, &pBlobSize); UINT32 offset = (UINT32)(pBitcode - (const char *)pSource->GetBufferPointer()); pLibrary->CreateBlobFromBlob(pSource, offset, pBlobSize, ppTargetBlob); return S_OK; } return E_INVALIDARG; } // This function is currently only supported on Windows due to usage of // IDiaTable. #ifdef _WIN32 // TODO : There is an identical code in DxaContext in Dxa.cpp. Refactor this // function. HRESULT DxcContext::GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob, IDiaTable **ppTable, LPCWSTR tableName) { if (!pLibrary || !pTargetBlob || !ppTable) return E_INVALIDARG; CComPtr<IDiaDataSource> pDataSource; CComPtr<IStream> pSourceStream; CComPtr<IDiaSession> pSession; CComPtr<IDiaEnumTables> pEnumTables; IFT(CreateInstance(CLSID_DxcDiaDataSource, &pDataSource)); IFT(pLibrary->CreateStreamFromBlobReadOnly(pTargetBlob, &pSourceStream)); IFT(pDataSource->loadDataFromIStream(pSourceStream)); IFT(pDataSource->openSession(&pSession)); IFT(pSession->getEnumTables(&pEnumTables)); CComPtr<IDiaTable> pTable; for (;;) { ULONG fetched; pTable.Release(); IFT(pEnumTables->Next(1, &pTable, &fetched)); if (fetched == 0) { pTable.Release(); break; } CComBSTR name; IFT(pTable->get_name(&name)); if (wcscmp(name, tableName) == 0) { break; } } *ppTable = pTable.Detach(); return S_OK; } #endif // _WIN32 bool GetDLLFileVersionInfo(const char *dllPath, unsigned int *version) { // This function is used to get version information from the DLL file. // This information in is not available through a Unix interface. #ifdef _WIN32 DWORD dwVerHnd = 0; DWORD size = GetFileVersionInfoSize(dllPath, &dwVerHnd); if (size == 0) return false; std::unique_ptr<BYTE[]> VfInfo(new BYTE[size]); if (GetFileVersionInfo(dllPath, NULL, size, VfInfo.get())) { LPVOID versionInfo; UINT size; if (VerQueryValue(VfInfo.get(), "\\", &versionInfo, &size)) { if (size >= sizeof(VS_FIXEDFILEINFO)) { VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)versionInfo; version[0] = (verInfo->dwFileVersionMS >> 16) & 0xffff; version[1] = (verInfo->dwFileVersionMS >> 0) & 0xffff; version[2] = (verInfo->dwFileVersionLS >> 16) & 0xffff; version[3] = (verInfo->dwFileVersionLS >> 0) & 0xffff; return true; } } } #endif // _WIN32 return false; } bool GetDLLProductVersionInfo(const char *dllPath, std::string &productVersion) { // This function is used to get product version information from the DLL file. // This information in is not available through a Unix interface. #ifdef _WIN32 DWORD dwVerHnd = 0; DWORD size = GetFileVersionInfoSize(dllPath, &dwVerHnd); if (size == 0) return false; std::unique_ptr<BYTE[]> VfInfo(new BYTE[size]); if (GetFileVersionInfo(dllPath, NULL, size, VfInfo.get())) { LPVOID pvProductVersion = NULL; unsigned int iProductVersionLen = 0; // 040904b0 == code page US English, Unicode if (VerQueryValue(VfInfo.get(), "\\StringFileInfo\\040904b0\\ProductVersion", &pvProductVersion, &iProductVersionLen)) { productVersion = (LPCSTR)pvProductVersion; return true; } } #endif // _WIN32 return false; } namespace dxc { // Writes compiler version info to stream void WriteDxCompilerVersionInfo(llvm::raw_ostream &OS, const char *ExternalLib, const char *ExternalFn, DxcDllSupport &DxcSupport) { if (DxcSupport.IsEnabled()) { UINT32 compilerMajor = 1; UINT32 compilerMinor = 0; CComPtr<IDxcVersionInfo> VerInfo; #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO UINT32 commitCount = 0; CComHeapPtr<char> commitHash; CComPtr<IDxcVersionInfo2> VerInfo2; #endif // SUPPORT_QUERY_GIT_COMMIT_INFO const char *dllName = !ExternalLib ? kDxCompilerLib : ExternalLib; std::string compilerName(dllName); if (ExternalFn) compilerName = compilerName + "!" + ExternalFn; if (SUCCEEDED(DxcSupport.CreateInstance(CLSID_DxcCompiler, &VerInfo))) { VerInfo->GetVersion(&compilerMajor, &compilerMinor); #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO if (SUCCEEDED(VerInfo->QueryInterface(&VerInfo2))) VerInfo2->GetCommitInfo(&commitCount, &commitHash); #endif // SUPPORT_QUERY_GIT_COMMIT_INFO OS << compilerName << ": " << compilerMajor << "." << compilerMinor; } // compiler.dll 1.0 did not support IdxcVersionInfo else if (!ExternalLib) { OS << compilerName << ": " << 1 << "." << 0; } else { // ExternalLib/ExternalFn, no version info: OS << compilerName; } #ifdef _WIN32 unsigned int version[4]; if (GetDLLFileVersionInfo(dllName, version)) { // back-compat - old dev buidls had version 3.7.0.0 if (version[0] == 3 && version[1] == 7 && version[2] == 0 && version[3] == 0) { #endif OS << "(dev" #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO << ";" << commitCount << "-" << (commitHash.m_pData ? commitHash.m_pData : "<unknown-git-hash>") #endif // SUPPORT_QUERY_GIT_COMMIT_I#else << ")"; #ifdef _WIN32 } else { std::string productVersion; if (GetDLLProductVersionInfo(dllName, productVersion)) { OS << " - " << productVersion; } } } #endif } } // Writes compiler version info to stream void WriteDXILVersionInfo(llvm::raw_ostream &OS, DxcDllSupport &DxilSupport) { if (DxilSupport.IsEnabled()) { CComPtr<IDxcVersionInfo> VerInfo; if (SUCCEEDED(DxilSupport.CreateInstance(CLSID_DxcValidator, &VerInfo))) { UINT32 validatorMajor, validatorMinor = 0; VerInfo->GetVersion(&validatorMajor, &validatorMinor); OS << "; " << kDxilLib << ": " << validatorMajor << "." << validatorMinor; } // dxil.dll 1.0 did not support IdxcVersionInfo else { OS << "; " << kDxilLib << ": " << 1 << "." << 0; } unsigned int version[4]; if (GetDLLFileVersionInfo(kDxilLib, version)) { OS << "(" << version[0] << "." << version[1] << "." << version[2] << "." << version[3] << ")"; } } } } // namespace dxc // Collects compiler/validator version info void DxcContext::GetCompilerVersionInfo(llvm::raw_string_ostream &OS) { WriteDxCompilerVersionInfo( OS, m_Opts.ExternalLib.empty() ? nullptr : m_Opts.ExternalLib.data(), m_Opts.ExternalFn.empty() ? nullptr : m_Opts.ExternalFn.data(), m_dxcSupport); // Print validator if exists DxcDllSupport DxilSupport; DxilSupport.InitializeForDll(kDxilLib, "DxcCreateInstance"); WriteDXILVersionInfo(OS, DxilSupport); } #ifndef VERSION_STRING_SUFFIX #define VERSION_STRING_SUFFIX "" #endif #ifdef _WIN32 // Unhandled exception filter called when an unhandled exception occurs // to at least print an generic error message instead of crashing silently. // passes exception along to allow crash dumps to be generated static LONG CALLBACK ExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo) { static char scratch[32]; fputs("Internal compiler error: ", stderr); if (!pExceptionInfo || !pExceptionInfo->ExceptionRecord) { // No information at all, it's not much, but it's the best we can do fputs("Unknown", stderr); return EXCEPTION_CONTINUE_SEARCH; } switch (pExceptionInfo->ExceptionRecord->ExceptionCode) { // native exceptions case EXCEPTION_ACCESS_VIOLATION: { fputs("access violation. Attempted to ", stderr); if (pExceptionInfo->ExceptionRecord->ExceptionInformation[0]) fputs("write", stderr); else fputs("read", stderr); fputs(" from address ", stderr); sprintf_s(scratch, _countof(scratch), "0x%p\n", (void *)pExceptionInfo->ExceptionRecord->ExceptionInformation[1]); fputs(scratch, stderr); } break; case EXCEPTION_STACK_OVERFLOW: fputs("stack overflow\n", stderr); break; // LLVM exceptions case STATUS_LLVM_ASSERT: fputs("LLVM Assert\n", stderr); break; case STATUS_LLVM_UNREACHABLE: fputs("LLVM Unreachable\n", stderr); break; case STATUS_LLVM_FATAL: fputs("LLVM Fatal Error\n", stderr); break; case EXCEPTION_LOAD_LIBRARY_FAILED: if (pExceptionInfo->ExceptionRecord->ExceptionInformation[0]) { fputs("cannot not load ", stderr); fputws((const wchar_t *) pExceptionInfo->ExceptionRecord->ExceptionInformation[0], stderr); fputs(" library.\n", stderr); } else { fputs("cannot not load library.\n", stderr); } break; default: fputs("Terminal Error ", stderr); sprintf_s(scratch, _countof(scratch), "0x%08x\n", pExceptionInfo->ExceptionRecord->ExceptionCode); fputs(scratch, stderr); } // Continue search to pass along the exception return EXCEPTION_CONTINUE_SEARCH; } #endif #ifdef _WIN32 int dxc::main(int argc, const wchar_t **argv_) { #else int dxc::main(int argc, const char **argv_) { #endif // _WIN32 const char *pStage = "Operation"; int retVal = 0; if (FAILED(DxcInitThreadMalloc())) return 1; DxcSetThreadMallocToDefault(); try { pStage = "Argument processing"; if (initHlslOptTable()) throw std::bad_alloc(); // Parse command line options. const OptTable *optionTable = getHlslOptTable(); MainArgs argStrings(argc, argv_); DxcOpts dxcOpts; DxcDllSupport dxcSupport; // Read options and check errors. { std::string errorString; llvm::raw_string_ostream errorStream(errorString); int optResult = ReadDxcOpts(optionTable, DxcFlags, argStrings, dxcOpts, errorStream); errorStream.flush(); if (errorString.size()) { if (optResult) fprintf(stderr, "dxc failed : %s\n", errorString.data()); else fprintf(stderr, "dxc warning : %s\n", errorString.data()); } if (optResult != 0) { return optResult; } } // Apply defaults. if (dxcOpts.EntryPoint.empty() && !dxcOpts.RecompileFromBinary) { dxcOpts.EntryPoint = "main"; } #ifdef _WIN32 // Set exception handler if enabled if (dxcOpts.HandleExceptions) SetUnhandledExceptionFilter(ExceptionFilter); #endif // Setup a helper DLL. { std::string dllErrorString; llvm::raw_string_ostream dllErrorStream(dllErrorString); int dllResult = SetupDxcDllSupport(dxcOpts, dxcSupport, dllErrorStream); dllErrorStream.flush(); if (dllErrorString.size()) { fprintf(stderr, "%s\n", dllErrorString.data()); } if (dllResult) return dllResult; } EnsureEnabled(dxcSupport); DxcContext context(dxcOpts, dxcSupport); // Handle help request, which overrides any other processing. if (dxcOpts.ShowHelp) { std::string helpString; llvm::raw_string_ostream helpStream(helpString); std::string version; llvm::raw_string_ostream versionStream(version); context.GetCompilerVersionInfo(versionStream); optionTable->PrintHelp( helpStream, "dxc.exe", "HLSL Compiler" VERSION_STRING_SUFFIX, versionStream.str().c_str(), dxcOpts.ShowHelpHidden); helpStream.flush(); WriteUtf8ToConsoleSizeT(helpString.data(), helpString.size()); return 0; } if (dxcOpts.ShowVersion) { std::string version; llvm::raw_string_ostream versionStream(version); context.GetCompilerVersionInfo(versionStream); versionStream.flush(); WriteUtf8ToConsoleSizeT(version.data(), version.size()); return 0; } // TODO: implement all other actions. if (!dxcOpts.Preprocess.empty()) { pStage = "Preprocessing"; context.Preprocess(); } else if (dxcOpts.DumpBin) { pStage = "Dumping existing binary"; retVal = context.DumpBinary(); } else if (dxcOpts.Link) { pStage = "Linking"; retVal = context.Link(); } else { pStage = "Compilation"; retVal = context.Compile(); } } catch (const ::hlsl::Exception &hlslException) { try { const char *msg = hlslException.what(); Unicode::acp_char printBuffer[128]; // printBuffer is safe to treat as // UTF-8 because we use ASCII only errors if (msg == nullptr || *msg == '\0') { switch (hlslException.hr) { case DXC_E_DUPLICATE_PART: sprintf_s( printBuffer, _countof(printBuffer), "dxc failed : DXIL container already contains the given part."); break; case DXC_E_MISSING_PART: sprintf_s( printBuffer, _countof(printBuffer), "dxc failed : DXIL container does not contain the given part."); break; case DXC_E_CONTAINER_INVALID: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : Invalid DXIL container."); break; case DXC_E_CONTAINER_MISSING_DXIL: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : DXIL container is missing DXIL part."); break; case DXC_E_CONTAINER_MISSING_DEBUG: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : DXIL container is missing Debug Info part."); break; case DXC_E_LLVM_FATAL_ERROR: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : Internal Compiler Error - LLVM Fatal Error!"); break; case DXC_E_LLVM_UNREACHABLE: sprintf_s( printBuffer, _countof(printBuffer), "dxc failed : Internal Compiler Error - UNREACHABLE executed!"); break; case DXC_E_LLVM_CAST_ERROR: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : Internal Compiler Error - Cast of " "incompatible type!"); break; case E_OUTOFMEMORY: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : Out of Memory."); break; case E_INVALIDARG: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : Invalid argument."); break; default: sprintf_s(printBuffer, _countof(printBuffer), "dxc failed : error code 0x%08x.\n", hlslException.hr); } msg = printBuffer; } WriteUtf8ToConsoleSizeT(msg, strlen(msg), STD_ERROR_HANDLE); printf("\n"); } catch (...) { printf("%s failed - unable to retrieve error message.\n", pStage); } return 1; } catch (std::bad_alloc &) { printf("%s failed - out of memory.\n", pStage); return 1; } catch (...) { printf("%s failed - unknown error.\n", pStage); return 1; } return retVal; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexInclusionStack.cpp
//===- CIndexInclusionStack.cpp - Clang-C Source Indexing Library ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a callback mechanism for clients to get the inclusion // stack from a translation unit. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CXSourceLocation.h" #include "CXTranslationUnit.h" #include "clang/AST/DeclVisitor.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; // extern "C" { // HLSL Change -Don't use c linkage. void clang_getInclusions(CXTranslationUnit TU, CXInclusionVisitor CB, CXClientData clientData) { if (cxtu::isNotUsableTU(TU)) { LOG_BAD_TU(TU); return; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); SourceManager &SM = CXXUnit->getSourceManager(); ASTContext &Ctx = CXXUnit->getASTContext(); SmallVector<CXSourceLocation, 10> InclusionStack; unsigned n = SM.local_sloc_entry_size(); // In the case where all the SLocEntries are in an external source, traverse // those SLocEntries as well. This is the case where we are looking // at the inclusion stack of an AST/PCH file. const SrcMgr::SLocEntry &(SourceManager::*Getter)(unsigned, bool*) const; if (n == 1) { Getter = &SourceManager::getLoadedSLocEntry; n = SM.loaded_sloc_entry_size(); } else Getter = &SourceManager::getLocalSLocEntry; for (unsigned i = 0 ; i < n ; ++i) { bool Invalid = false; const SrcMgr::SLocEntry &SL = (SM.*Getter)(i, &Invalid); if (!SL.isFile() || Invalid) continue; const SrcMgr::FileInfo &FI = SL.getFile(); if (!FI.getContentCache()->OrigEntry) continue; // Build the inclusion stack. SourceLocation L = FI.getIncludeLoc(); InclusionStack.clear(); while (L.isValid()) { PresumedLoc PLoc = SM.getPresumedLoc(L); InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L)); L = PLoc.isValid()? PLoc.getIncludeLoc() : SourceLocation(); } // Callback to the client. // FIXME: We should have a function to construct CXFiles. CB(static_cast<CXFile>( const_cast<FileEntry *>(FI.getContentCache()->OrigEntry)), InclusionStack.data(), InclusionStack.size(), clientData); } } // } // end extern C // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXType.cpp
//===- CXTypes.cpp - Implements 'CXTypes' aspect of libclang ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===--------------------------------------------------------------------===// // // This file implements the 'CXTypes' API hooks in the Clang-C library. // //===--------------------------------------------------------------------===// #include "CIndexer.h" #include "CXCursor.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "CXType.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "clang/Frontend/ASTUnit.h" using namespace clang; static CXTypeKind GetBuiltinTypeKind(const BuiltinType *BT) { #define BTCASE(K) case BuiltinType::K: return CXType_##K switch (BT->getKind()) { BTCASE(Void); BTCASE(Bool); BTCASE(Char_U); BTCASE(UChar); BTCASE(Char16); BTCASE(Char32); BTCASE(UShort); BTCASE(UInt); BTCASE(ULong); BTCASE(ULongLong); BTCASE(UInt128); BTCASE(Char_S); BTCASE(SChar); case BuiltinType::WChar_S: return CXType_WChar; case BuiltinType::WChar_U: return CXType_WChar; BTCASE(Short); BTCASE(Int); BTCASE(Long); BTCASE(LongLong); BTCASE(Int128); BTCASE(Float); BTCASE(Double); BTCASE(LongDouble); BTCASE(NullPtr); BTCASE(Overload); BTCASE(Dependent); BTCASE(ObjCId); BTCASE(ObjCClass); BTCASE(ObjCSel); default: return CXType_Unexposed; } #undef BTCASE } static CXTypeKind GetTypeKind(QualType T) { const Type *TP = T.getTypePtrOrNull(); if (!TP) return CXType_Invalid; #define TKCASE(K) case Type::K: return CXType_##K switch (TP->getTypeClass()) { case Type::Builtin: return GetBuiltinTypeKind(cast<BuiltinType>(TP)); TKCASE(Complex); TKCASE(Pointer); TKCASE(BlockPointer); TKCASE(LValueReference); TKCASE(RValueReference); TKCASE(Record); TKCASE(Enum); TKCASE(Typedef); TKCASE(ObjCInterface); TKCASE(ObjCObjectPointer); TKCASE(FunctionNoProto); TKCASE(FunctionProto); TKCASE(ConstantArray); TKCASE(IncompleteArray); TKCASE(VariableArray); TKCASE(DependentSizedArray); TKCASE(Vector); TKCASE(MemberPointer); default: return CXType_Unexposed; } #undef TKCASE } CXType cxtype::MakeCXType(QualType T, CXTranslationUnit TU) { CXTypeKind TK = CXType_Invalid; if (TU && !T.isNull()) { ASTContext &Ctx = cxtu::getASTUnit(TU)->getASTContext(); if (Ctx.getLangOpts().ObjC1) { QualType UnqualT = T.getUnqualifiedType(); if (Ctx.isObjCIdType(UnqualT)) TK = CXType_ObjCId; else if (Ctx.isObjCClassType(UnqualT)) TK = CXType_ObjCClass; else if (Ctx.isObjCSelType(UnqualT)) TK = CXType_ObjCSel; } /* Handle decayed types as the original type */ if (const DecayedType *DT = T->getAs<DecayedType>()) { return MakeCXType(DT->getOriginalType(), TU); } } if (TK == CXType_Invalid) TK = GetTypeKind(T); CXType CT = { TK, { TK == CXType_Invalid ? nullptr : T.getAsOpaquePtr(), TU } }; return CT; } using cxtype::MakeCXType; static inline QualType GetQualType(CXType CT) { return QualType::getFromOpaquePtr(CT.data[0]); } static inline CXTranslationUnit GetTU(CXType CT) { return static_cast<CXTranslationUnit>(CT.data[1]); } // extern "C" { // HLSL Change -Don't use c linkage. CXType clang_getCursorType(CXCursor C) { using namespace cxcursor; CXTranslationUnit TU = cxcursor::getCursorTU(C); if (!TU) return MakeCXType(QualType(), TU); ASTContext &Context = cxtu::getASTUnit(TU)->getASTContext(); if (clang_isExpression(C.kind)) { QualType T = cxcursor::getCursorExpr(C)->getType(); return MakeCXType(T, TU); } if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return MakeCXType(QualType(), TU); if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) return MakeCXType(Context.getTypeDeclType(TD), TU); if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) return MakeCXType(Context.getObjCInterfaceType(ID), TU); if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) return MakeCXType(TSInfo->getType(), TU); return MakeCXType(DD->getType(), TU); } if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) return MakeCXType(VD->getType(), TU); if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) return MakeCXType(PD->getType(), TU); if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) { if (TypeSourceInfo *TSInfo = FTD->getTemplatedDecl()->getTypeSourceInfo()) return MakeCXType(TSInfo->getType(), TU); return MakeCXType(FTD->getTemplatedDecl()->getType(), TU); } return MakeCXType(QualType(), TU); } if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: { QualType T = Context.getObjCInterfaceType(getCursorObjCSuperClassRef(C).first); return MakeCXType(T, TU); } case CXCursor_ObjCClassRef: { QualType T = Context.getObjCInterfaceType(getCursorObjCClassRef(C).first); return MakeCXType(T, TU); } case CXCursor_TypeRef: { QualType T = Context.getTypeDeclType(getCursorTypeRef(C).first); return MakeCXType(T, TU); } case CXCursor_CXXBaseSpecifier: return cxtype::MakeCXType(getCursorCXXBaseSpecifier(C)->getType(), TU); case CXCursor_MemberRef: return cxtype::MakeCXType(getCursorMemberRef(C).first->getType(), TU); case CXCursor_VariableRef: return cxtype::MakeCXType(getCursorVariableRef(C).first->getType(), TU); case CXCursor_ObjCProtocolRef: case CXCursor_TemplateRef: case CXCursor_NamespaceRef: case CXCursor_OverloadedDeclRef: default: break; } return MakeCXType(QualType(), TU); } return MakeCXType(QualType(), TU); } CXString clang_getTypeSpelling(CXType CT) { QualType T = GetQualType(CT); if (T.isNull()) return cxstring::createEmpty(); CXTranslationUnit TU = GetTU(CT); SmallString<64> Str; llvm::raw_svector_ostream OS(Str); PrintingPolicy PP(cxtu::getASTUnit(TU)->getASTContext().getLangOpts()); T.print(OS, PP); return cxstring::createDup(OS.str()); } CXType clang_getTypedefDeclUnderlyingType(CXCursor C) { using namespace cxcursor; CXTranslationUnit TU = cxcursor::getCursorTU(C); if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const TypedefNameDecl *TD = dyn_cast_or_null<TypedefNameDecl>(D)) { QualType T = TD->getUnderlyingType(); return MakeCXType(T, TU); } return MakeCXType(QualType(), TU); } return MakeCXType(QualType(), TU); } CXType clang_getEnumDeclIntegerType(CXCursor C) { using namespace cxcursor; CXTranslationUnit TU = cxcursor::getCursorTU(C); if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const EnumDecl *TD = dyn_cast_or_null<EnumDecl>(D)) { QualType T = TD->getIntegerType(); return MakeCXType(T, TU); } return MakeCXType(QualType(), TU); } return MakeCXType(QualType(), TU); } long long clang_getEnumConstantDeclValue(CXCursor C) { using namespace cxcursor; if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const EnumConstantDecl *TD = dyn_cast_or_null<EnumConstantDecl>(D)) { return TD->getInitVal().getSExtValue(); } return LLONG_MIN; } return LLONG_MIN; } unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor C) { using namespace cxcursor; if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const EnumConstantDecl *TD = dyn_cast_or_null<EnumConstantDecl>(D)) { return TD->getInitVal().getZExtValue(); } return ULLONG_MAX; } return ULLONG_MAX; } int clang_getFieldDeclBitWidth(CXCursor C) { using namespace cxcursor; if (clang_isDeclaration(C.kind)) { const Decl *D = getCursorDecl(C); if (const FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { if (FD->isBitField()) return FD->getBitWidthValue(getCursorContext(C)); } } return -1; } CXType clang_getCanonicalType(CXType CT) { if (CT.kind == CXType_Invalid) return CT; QualType T = GetQualType(CT); CXTranslationUnit TU = GetTU(CT); if (T.isNull()) return MakeCXType(QualType(), GetTU(CT)); return MakeCXType(cxtu::getASTUnit(TU)->getASTContext() .getCanonicalType(T), TU); } unsigned clang_isConstQualifiedType(CXType CT) { QualType T = GetQualType(CT); return T.isLocalConstQualified(); } unsigned clang_isVolatileQualifiedType(CXType CT) { QualType T = GetQualType(CT); return T.isLocalVolatileQualified(); } unsigned clang_isRestrictQualifiedType(CXType CT) { QualType T = GetQualType(CT); return T.isLocalRestrictQualified(); } CXType clang_getPointeeType(CXType CT) { QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (!TP) return MakeCXType(QualType(), GetTU(CT)); switch (TP->getTypeClass()) { case Type::Pointer: T = cast<PointerType>(TP)->getPointeeType(); break; case Type::BlockPointer: T = cast<BlockPointerType>(TP)->getPointeeType(); break; case Type::LValueReference: case Type::RValueReference: T = cast<ReferenceType>(TP)->getPointeeType(); break; case Type::ObjCObjectPointer: T = cast<ObjCObjectPointerType>(TP)->getPointeeType(); break; case Type::MemberPointer: T = cast<MemberPointerType>(TP)->getPointeeType(); break; default: T = QualType(); break; } return MakeCXType(T, GetTU(CT)); } CXCursor clang_getTypeDeclaration(CXType CT) { if (CT.kind == CXType_Invalid) return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound); QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (!TP) return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound); Decl *D = nullptr; try_again: switch (TP->getTypeClass()) { case Type::Typedef: D = cast<TypedefType>(TP)->getDecl(); break; case Type::ObjCObject: D = cast<ObjCObjectType>(TP)->getInterface(); break; case Type::ObjCInterface: D = cast<ObjCInterfaceType>(TP)->getDecl(); break; case Type::Record: case Type::Enum: D = cast<TagType>(TP)->getDecl(); break; case Type::TemplateSpecialization: if (const RecordType *Record = TP->getAs<RecordType>()) D = Record->getDecl(); else D = cast<TemplateSpecializationType>(TP)->getTemplateName() .getAsTemplateDecl(); break; case Type::InjectedClassName: D = cast<InjectedClassNameType>(TP)->getDecl(); break; // FIXME: Template type parameters! case Type::Elaborated: TP = cast<ElaboratedType>(TP)->getNamedType().getTypePtrOrNull(); goto try_again; default: break; } if (!D) return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound); return cxcursor::MakeCXCursor(D, GetTU(CT)); } CXString clang_getTypeKindSpelling(enum CXTypeKind K) { const char *s = nullptr; #define TKIND(X) case CXType_##X: s = "" #X ""; break switch (K) { TKIND(Invalid); TKIND(Unexposed); TKIND(Void); TKIND(Bool); TKIND(Char_U); TKIND(UChar); TKIND(Char16); TKIND(Char32); TKIND(UShort); TKIND(UInt); TKIND(ULong); TKIND(ULongLong); TKIND(UInt128); TKIND(Char_S); TKIND(SChar); case CXType_WChar: s = "WChar"; break; TKIND(Short); TKIND(Int); TKIND(Long); TKIND(LongLong); TKIND(Int128); TKIND(Float); TKIND(Double); TKIND(LongDouble); TKIND(NullPtr); TKIND(Overload); TKIND(Dependent); TKIND(ObjCId); TKIND(ObjCClass); TKIND(ObjCSel); TKIND(Complex); TKIND(Pointer); TKIND(BlockPointer); TKIND(LValueReference); TKIND(RValueReference); TKIND(Record); TKIND(Enum); TKIND(Typedef); TKIND(ObjCInterface); TKIND(ObjCObjectPointer); TKIND(FunctionNoProto); TKIND(FunctionProto); TKIND(ConstantArray); TKIND(IncompleteArray); TKIND(VariableArray); TKIND(DependentSizedArray); TKIND(Vector); TKIND(MemberPointer); } #undef TKIND return cxstring::createRef(s); } unsigned clang_equalTypes(CXType A, CXType B) { return A.data[0] == B.data[0] && A.data[1] == B.data[1]; } unsigned clang_isFunctionTypeVariadic(CXType X) { QualType T = GetQualType(X); if (T.isNull()) return 0; if (const FunctionProtoType *FD = T->getAs<FunctionProtoType>()) return (unsigned)FD->isVariadic(); if (T->getAs<FunctionNoProtoType>()) return 1; return 0; } CXCallingConv clang_getFunctionTypeCallingConv(CXType X) { QualType T = GetQualType(X); if (T.isNull()) return CXCallingConv_Invalid; if (const FunctionType *FD = T->getAs<FunctionType>()) { #define TCALLINGCONV(X) case CC_##X: return CXCallingConv_##X switch (FD->getCallConv()) { TCALLINGCONV(C); TCALLINGCONV(X86StdCall); TCALLINGCONV(X86FastCall); TCALLINGCONV(X86ThisCall); TCALLINGCONV(X86Pascal); TCALLINGCONV(X86VectorCall); TCALLINGCONV(X86_64Win64); TCALLINGCONV(X86_64SysV); TCALLINGCONV(AAPCS); TCALLINGCONV(AAPCS_VFP); TCALLINGCONV(IntelOclBicc); case CC_SpirFunction: return CXCallingConv_Unexposed; case CC_SpirKernel: return CXCallingConv_Unexposed; break; } #undef TCALLINGCONV } return CXCallingConv_Invalid; } int clang_getNumArgTypes(CXType X) { QualType T = GetQualType(X); if (T.isNull()) return -1; if (const FunctionProtoType *FD = T->getAs<FunctionProtoType>()) { return FD->getNumParams(); } if (T->getAs<FunctionNoProtoType>()) { return 0; } return -1; } CXType clang_getArgType(CXType X, unsigned i) { QualType T = GetQualType(X); if (T.isNull()) return MakeCXType(QualType(), GetTU(X)); if (const FunctionProtoType *FD = T->getAs<FunctionProtoType>()) { unsigned numParams = FD->getNumParams(); if (i >= numParams) return MakeCXType(QualType(), GetTU(X)); return MakeCXType(FD->getParamType(i), GetTU(X)); } return MakeCXType(QualType(), GetTU(X)); } CXType clang_getResultType(CXType X) { QualType T = GetQualType(X); if (T.isNull()) return MakeCXType(QualType(), GetTU(X)); if (const FunctionType *FD = T->getAs<FunctionType>()) return MakeCXType(FD->getReturnType(), GetTU(X)); return MakeCXType(QualType(), GetTU(X)); } CXType clang_getCursorResultType(CXCursor C) { if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) return MakeCXType(MD->getReturnType(), cxcursor::getCursorTU(C)); return clang_getResultType(clang_getCursorType(C)); } return MakeCXType(QualType(), cxcursor::getCursorTU(C)); } unsigned clang_isPODType(CXType X) { QualType T = GetQualType(X); if (T.isNull()) return 0; CXTranslationUnit TU = GetTU(X); return T.isPODType(cxtu::getASTUnit(TU)->getASTContext()) ? 1 : 0; } CXType clang_getElementType(CXType CT) { QualType ET = QualType(); QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (TP) { switch (TP->getTypeClass()) { case Type::ConstantArray: ET = cast<ConstantArrayType> (TP)->getElementType(); break; case Type::IncompleteArray: ET = cast<IncompleteArrayType> (TP)->getElementType(); break; case Type::VariableArray: ET = cast<VariableArrayType> (TP)->getElementType(); break; case Type::DependentSizedArray: ET = cast<DependentSizedArrayType> (TP)->getElementType(); break; case Type::Vector: ET = cast<VectorType> (TP)->getElementType(); break; case Type::Complex: ET = cast<ComplexType> (TP)->getElementType(); break; default: break; } } return MakeCXType(ET, GetTU(CT)); } long long clang_getNumElements(CXType CT) { long long result = -1; QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (TP) { switch (TP->getTypeClass()) { case Type::ConstantArray: result = cast<ConstantArrayType> (TP)->getSize().getSExtValue(); break; case Type::Vector: result = cast<VectorType> (TP)->getNumElements(); break; default: break; } } return result; } CXType clang_getArrayElementType(CXType CT) { QualType ET = QualType(); QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (TP) { switch (TP->getTypeClass()) { case Type::ConstantArray: ET = cast<ConstantArrayType> (TP)->getElementType(); break; case Type::IncompleteArray: ET = cast<IncompleteArrayType> (TP)->getElementType(); break; case Type::VariableArray: ET = cast<VariableArrayType> (TP)->getElementType(); break; case Type::DependentSizedArray: ET = cast<DependentSizedArrayType> (TP)->getElementType(); break; default: break; } } return MakeCXType(ET, GetTU(CT)); } long long clang_getArraySize(CXType CT) { long long result = -1; QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (TP) { switch (TP->getTypeClass()) { case Type::ConstantArray: result = cast<ConstantArrayType> (TP)->getSize().getSExtValue(); break; default: break; } } return result; } long long clang_Type_getAlignOf(CXType T) { if (T.kind == CXType_Invalid) return CXTypeLayoutError_Invalid; ASTContext &Ctx = cxtu::getASTUnit(GetTU(T))->getASTContext(); QualType QT = GetQualType(T); // [expr.alignof] p1: return size_t value for complete object type, reference // or array. // [expr.alignof] p3: if reference type, return size of referenced type if (QT->isReferenceType()) QT = QT.getNonReferenceType(); if (QT->isIncompleteType()) return CXTypeLayoutError_Incomplete; if (QT->isDependentType()) return CXTypeLayoutError_Dependent; // Exceptions by GCC extension - see ASTContext.cpp:1313 getTypeInfoImpl // if (QT->isFunctionType()) return 4; // Bug #15511 - should be 1 // if (QT->isVoidType()) return 1; return Ctx.getTypeAlignInChars(QT).getQuantity(); } CXType clang_Type_getClassType(CXType CT) { QualType ET = QualType(); QualType T = GetQualType(CT); const Type *TP = T.getTypePtrOrNull(); if (TP && TP->getTypeClass() == Type::MemberPointer) { ET = QualType(cast<MemberPointerType> (TP)->getClass(), 0); } return MakeCXType(ET, GetTU(CT)); } long long clang_Type_getSizeOf(CXType T) { if (T.kind == CXType_Invalid) return CXTypeLayoutError_Invalid; ASTContext &Ctx = cxtu::getASTUnit(GetTU(T))->getASTContext(); QualType QT = GetQualType(T); // [expr.sizeof] p2: if reference type, return size of referenced type if (QT->isReferenceType()) QT = QT.getNonReferenceType(); // [expr.sizeof] p1: return -1 on: func, incomplete, bitfield, incomplete // enumeration // Note: We get the cxtype, not the cxcursor, so we can't call // FieldDecl->isBitField() // [expr.sizeof] p3: pointer ok, function not ok. // [gcc extension] lib/AST/ExprConstant.cpp:1372 HandleSizeof : vla == error if (QT->isIncompleteType()) return CXTypeLayoutError_Incomplete; if (QT->isDependentType()) return CXTypeLayoutError_Dependent; if (!QT->isConstantSizeType()) return CXTypeLayoutError_NotConstantSize; // [gcc extension] lib/AST/ExprConstant.cpp:1372 // HandleSizeof : {voidtype,functype} == 1 // not handled by ASTContext.cpp:1313 getTypeInfoImpl if (QT->isVoidType() || QT->isFunctionType()) return 1; return Ctx.getTypeSizeInChars(QT).getQuantity(); } static long long visitRecordForValidation(const RecordDecl *RD) { for (const auto *I : RD->fields()){ QualType FQT = I->getType(); if (FQT->isIncompleteType()) return CXTypeLayoutError_Incomplete; if (FQT->isDependentType()) return CXTypeLayoutError_Dependent; // recurse if (const RecordType *ChildType = I->getType()->getAs<RecordType>()) { if (const RecordDecl *Child = ChildType->getDecl()) { long long ret = visitRecordForValidation(Child); if (ret < 0) return ret; } } // else try next field } return 0; } static long long validateFieldParentType(CXCursor PC, CXType PT){ if (clang_isInvalid(PC.kind)) return CXTypeLayoutError_Invalid; const RecordDecl *RD = dyn_cast_or_null<RecordDecl>(cxcursor::getCursorDecl(PC)); // validate parent declaration if (!RD || RD->isInvalidDecl()) return CXTypeLayoutError_Invalid; RD = RD->getDefinition(); if (!RD) return CXTypeLayoutError_Incomplete; if (RD->isInvalidDecl()) return CXTypeLayoutError_Invalid; // validate parent type QualType RT = GetQualType(PT); if (RT->isIncompleteType()) return CXTypeLayoutError_Incomplete; if (RT->isDependentType()) return CXTypeLayoutError_Dependent; // We recurse into all record fields to detect incomplete and dependent types. long long Error = visitRecordForValidation(RD); if (Error < 0) return Error; return 0; } long long clang_Type_getOffsetOf(CXType PT, const char *S) { // check that PT is not incomplete/dependent CXCursor PC = clang_getTypeDeclaration(PT); long long Error = validateFieldParentType(PC,PT); if (Error < 0) return Error; if (!S) return CXTypeLayoutError_InvalidFieldName; // lookup field ASTContext &Ctx = cxtu::getASTUnit(GetTU(PT))->getASTContext(); IdentifierInfo *II = &Ctx.Idents.get(S); DeclarationName FieldName(II); const RecordDecl *RD = dyn_cast_or_null<RecordDecl>(cxcursor::getCursorDecl(PC)); // verified in validateFieldParentType RD = RD->getDefinition(); RecordDecl::lookup_result Res = RD->lookup(FieldName); // If a field of the parent record is incomplete, lookup will fail. // and we would return InvalidFieldName instead of Incomplete. // But this erroneous results does protects again a hidden assertion failure // in the RecordLayoutBuilder if (Res.size() != 1) return CXTypeLayoutError_InvalidFieldName; if (const FieldDecl *FD = dyn_cast<FieldDecl>(Res.front())) return Ctx.getFieldOffset(FD); if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(Res.front())) return Ctx.getFieldOffset(IFD); // we don't want any other Decl Type. return CXTypeLayoutError_InvalidFieldName; } long long clang_Cursor_getOffsetOfField(CXCursor C) { if (clang_isDeclaration(C.kind)) { // we need to validate the parent type CXCursor PC = clang_getCursorSemanticParent(C); CXType PT = clang_getCursorType(PC); long long Error = validateFieldParentType(PC,PT); if (Error < 0) return Error; // proceed with the offset calculation const Decl *D = cxcursor::getCursorDecl(C); ASTContext &Ctx = cxcursor::getCursorContext(C); if (const FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) return Ctx.getFieldOffset(FD); if (const IndirectFieldDecl *IFD = dyn_cast_or_null<IndirectFieldDecl>(D)) return Ctx.getFieldOffset(IFD); } return -1; } enum CXRefQualifierKind clang_Type_getCXXRefQualifier(CXType T) { QualType QT = GetQualType(T); if (QT.isNull()) return CXRefQualifier_None; const FunctionProtoType *FD = QT->getAs<FunctionProtoType>(); if (!FD) return CXRefQualifier_None; switch (FD->getRefQualifier()) { case RQ_None: return CXRefQualifier_None; case RQ_LValue: return CXRefQualifier_LValue; case RQ_RValue: return CXRefQualifier_RValue; } return CXRefQualifier_None; } unsigned clang_Cursor_isBitField(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const FieldDecl *FD = dyn_cast_or_null<FieldDecl>(cxcursor::getCursorDecl(C)); if (!FD) return 0; return FD->isBitField(); } CXString clang_getDeclObjCTypeEncoding(CXCursor C) { if (!clang_isDeclaration(C.kind)) return cxstring::createEmpty(); const Decl *D = cxcursor::getCursorDecl(C); ASTContext &Ctx = cxcursor::getCursorContext(C); std::string encoding; if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { if (Ctx.getObjCEncodingForMethodDecl(OMD, encoding)) return cxstring::createRef("?"); } else if (const ObjCPropertyDecl *OPD = dyn_cast<ObjCPropertyDecl>(D)) Ctx.getObjCEncodingForPropertyDecl(OPD, nullptr, encoding); else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) Ctx.getObjCEncodingForFunctionDecl(FD, encoding); else { QualType Ty; if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) Ty = Ctx.getTypeDeclType(TD); if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) Ty = VD->getType(); else return cxstring::createRef("?"); Ctx.getObjCEncodingForType(Ty, encoding); } return cxstring::createDup(encoding); } int clang_Type_getNumTemplateArguments(CXType CT) { QualType T = GetQualType(CT); if (T.isNull()) return -1; const CXXRecordDecl *RecordDecl = T->getAsCXXRecordDecl(); if (!RecordDecl) return -1; const ClassTemplateSpecializationDecl *TemplateDecl = dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl); if (!TemplateDecl) return -1; return TemplateDecl->getTemplateArgs().size(); } CXType clang_Type_getTemplateArgumentAsType(CXType CT, unsigned i) { QualType T = GetQualType(CT); if (T.isNull()) return MakeCXType(QualType(), GetTU(CT)); const CXXRecordDecl *RecordDecl = T->getAsCXXRecordDecl(); if (!RecordDecl) return MakeCXType(QualType(), GetTU(CT)); const ClassTemplateSpecializationDecl *TemplateDecl = dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl); if (!TemplateDecl) return MakeCXType(QualType(), GetTU(CT)); const TemplateArgumentList &TA = TemplateDecl->getTemplateArgs(); if (TA.size() <= i) return MakeCXType(QualType(), GetTU(CT)); const TemplateArgument &A = TA.get(i); if (A.getKind() != TemplateArgument::Type) return MakeCXType(QualType(), GetTU(CT)); return MakeCXType(A.getAsType(), GetTU(CT)); } unsigned clang_Type_visitFields(CXType PT, CXFieldVisitor visitor, CXClientData client_data){ CXCursor PC = clang_getTypeDeclaration(PT); if (clang_isInvalid(PC.kind)) return false; const RecordDecl *RD = dyn_cast_or_null<RecordDecl>(cxcursor::getCursorDecl(PC)); if (!RD || RD->isInvalidDecl()) return false; RD = RD->getDefinition(); if (!RD || RD->isInvalidDecl()) return false; for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); I != E; ++I){ const FieldDecl *FD = dyn_cast_or_null<FieldDecl>((*I)); // Callback to the client. switch (visitor(cxcursor::MakeCXCursor(FD, GetTU(PT)), client_data)){ case CXVisit_Break: return true; case CXVisit_Continue: break; } } return true; } unsigned clang_Cursor_isAnonymous(CXCursor C){ if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(C); if (const RecordDecl *FD = dyn_cast_or_null<RecordDecl>(D)) return FD->isAnonymousStructOrUnion(); return 0; } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/ARCMigrate.cpp
//===- ARCMigrate.cpp - Clang-C ARC Migration Library ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the main API hooks in the Clang-C ARC Migration library. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "CXString.h" #include "clang/ARCMigrate/ARCMT.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "llvm/Support/FileSystem.h" using namespace clang; using namespace arcmt; namespace { struct Remap { std::vector<std::pair<std::string, std::string> > Vec; }; } // anonymous namespace. //===----------------------------------------------------------------------===// // libClang public APIs. //===----------------------------------------------------------------------===// extern "C" { CXRemapping clang_getRemappings(const char *migrate_dir_path) { #ifndef CLANG_ENABLE_ARCMT llvm::errs() << "error: feature not enabled in this build\n"; return nullptr; #else bool Logging = ::getenv("LIBCLANG_LOGGING"); if (!migrate_dir_path) { if (Logging) llvm::errs() << "clang_getRemappings was called with NULL parameter\n"; return nullptr; } if (!llvm::sys::fs::exists(migrate_dir_path)) { if (Logging) { llvm::errs() << "Error by clang_getRemappings(\"" << migrate_dir_path << "\")\n"; llvm::errs() << "\"" << migrate_dir_path << "\" does not exist\n"; } return nullptr; } TextDiagnosticBuffer diagBuffer; std::unique_ptr<Remap> remap(new Remap()); bool err = arcmt::getFileRemappings(remap->Vec, migrate_dir_path,&diagBuffer); if (err) { if (Logging) { llvm::errs() << "Error by clang_getRemappings(\"" << migrate_dir_path << "\")\n"; for (TextDiagnosticBuffer::const_iterator I = diagBuffer.err_begin(), E = diagBuffer.err_end(); I != E; ++I) llvm::errs() << I->second << '\n'; } return nullptr; } return remap.release(); #endif } CXRemapping clang_getRemappingsFromFileList(const char **filePaths, unsigned numFiles) { #ifndef CLANG_ENABLE_ARCMT llvm::errs() << "error: feature not enabled in this build\n"; return nullptr; #else bool Logging = ::getenv("LIBCLANG_LOGGING"); std::unique_ptr<Remap> remap(new Remap()); if (numFiles == 0) { if (Logging) llvm::errs() << "clang_getRemappingsFromFileList was called with " "numFiles=0\n"; return remap.release(); } if (!filePaths) { if (Logging) llvm::errs() << "clang_getRemappingsFromFileList was called with " "NULL filePaths\n"; return nullptr; } TextDiagnosticBuffer diagBuffer; SmallVector<StringRef, 32> Files(filePaths, filePaths + numFiles); bool err = arcmt::getFileRemappingsFromFileList(remap->Vec, Files, &diagBuffer); if (err) { if (Logging) { llvm::errs() << "Error by clang_getRemappingsFromFileList\n"; for (TextDiagnosticBuffer::const_iterator I = diagBuffer.err_begin(), E = diagBuffer.err_end(); I != E; ++I) llvm::errs() << I->second << '\n'; } return remap.release(); } return remap.release(); #endif } unsigned clang_remap_getNumFiles(CXRemapping map) { return static_cast<Remap *>(map)->Vec.size(); } void clang_remap_getFilenames(CXRemapping map, unsigned index, CXString *original, CXString *transformed) { if (original) *original = cxstring::createDup( static_cast<Remap *>(map)->Vec[index].first); if (transformed) *transformed = cxstring::createDup( static_cast<Remap *>(map)->Vec[index].second); } void clang_remap_dispose(CXRemapping map) { delete static_cast<Remap *>(map); } } // end: extern "C"
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/dxcisenseimpl.h
/////////////////////////////////////////////////////////////////////////////// // // // dxcisenseimpl.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Compiler IntelliSense component. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef __DXC_ISENSEIMPL__ #define __DXC_ISENSEIMPL__ #include "dxc/Support/DxcLangExtensionsCommonHelper.h" #include "dxc/Support/DxcLangExtensionsHelper.h" #include "dxc/Support/microcom.h" #include "dxc/dxcapi.internal.h" #include "dxc/dxcisense.h" #include "clang-c/Index.h" #include "clang/AST/Decl.h" #include "clang/Frontend/CompilerInstance.h" // Forward declarations. class DxcCursor; class DxcDiagnostic; class DxcFile; class DxcIndex; class DxcIntelliSense; class DxcSourceLocation; class DxcSourceRange; class DxcTranslationUnit; class DxcToken; struct IMalloc; class DxcCursor : public IDxcCursor { private: DXC_MICROCOM_TM_REF_FIELDS() CXCursor m_cursor; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcCursor) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcCursor>(this, iid, ppvObject); } void Initialize(const CXCursor &cursor); static HRESULT Create(const CXCursor &cursor, IDxcCursor **pObject); HRESULT STDMETHODCALLTYPE GetExtent(IDxcSourceRange **pRange) override; HRESULT STDMETHODCALLTYPE GetLocation(IDxcSourceLocation **pResult) override; HRESULT STDMETHODCALLTYPE GetKind(DxcCursorKind *pResult) override; HRESULT STDMETHODCALLTYPE GetKindFlags(DxcCursorKindFlags *pResult) override; HRESULT STDMETHODCALLTYPE GetSemanticParent(IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE GetLexicalParent(IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE GetCursorType(IDxcType **pResult) override; HRESULT STDMETHODCALLTYPE GetNumArguments(int *pResult) override; HRESULT STDMETHODCALLTYPE GetArgumentAt(int index, IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE GetReferencedCursor(IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE GetDefinitionCursor(IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE FindReferencesInFile(IDxcFile *file, unsigned skip, unsigned top, unsigned *pResultLength, IDxcCursor ***pResult) override; HRESULT STDMETHODCALLTYPE GetSpelling(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE IsEqualTo(IDxcCursor *other, BOOL *pResult) override; HRESULT STDMETHODCALLTYPE IsNull(BOOL *pResult) override; HRESULT STDMETHODCALLTYPE IsDefinition(BOOL *pResult) override; /// <summary>Gets the display name for the cursor, including e.g. parameter /// types for a function.</summary> HRESULT STDMETHODCALLTYPE GetDisplayName(BSTR *pResult) override; /// <summary>Gets the qualified name for the symbol the cursor refers /// to.</summary> HRESULT STDMETHODCALLTYPE GetQualifiedName(BOOL includeTemplateArgs, BSTR *pResult) override; /// <summary>Gets a name for the cursor, applying the specified formatting /// flags.</summary> HRESULT STDMETHODCALLTYPE GetFormattedName(DxcCursorFormatting formatting, BSTR *pResult) override; /// <summary>Gets children in pResult up to top elements.</summary> HRESULT STDMETHODCALLTYPE GetChildren(unsigned skip, unsigned top, unsigned *pResultLength, IDxcCursor ***pResult) override; /// <summary>Gets the cursor following a location within a compound /// cursor.</summary> HRESULT STDMETHODCALLTYPE GetSnappedChild(IDxcSourceLocation *location, IDxcCursor **pResult) override; }; class DxcDiagnostic : public IDxcDiagnostic { private: DXC_MICROCOM_TM_REF_FIELDS() CXDiagnostic m_diagnostic; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcDiagnostic) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcDiagnostic>(this, iid, ppvObject); } DxcDiagnostic(IMalloc *pMalloc); ~DxcDiagnostic(); void Initialize(const CXDiagnostic &diagnostic); static HRESULT Create(const CXDiagnostic &diagnostic, IDxcDiagnostic **pObject); HRESULT STDMETHODCALLTYPE FormatDiagnostic( DxcDiagnosticDisplayOptions options, LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE GetSeverity(DxcDiagnosticSeverity *pResult) override; HRESULT STDMETHODCALLTYPE GetLocation(IDxcSourceLocation **pResult) override; HRESULT STDMETHODCALLTYPE GetSpelling(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE GetCategoryText(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE GetNumRanges(unsigned *pResult) override; HRESULT STDMETHODCALLTYPE GetRangeAt(unsigned index, IDxcSourceRange **pResult) override; HRESULT STDMETHODCALLTYPE GetNumFixIts(unsigned *pResult) override; HRESULT STDMETHODCALLTYPE GetFixItAt(unsigned index, IDxcSourceRange **pReplacementRange, LPSTR *pText) override; }; class DxcFile : public IDxcFile { private: DXC_MICROCOM_TM_REF_FIELDS() CXFile m_file; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcFile) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcFile>(this, iid, ppvObject); } void Initialize(const CXFile &file); static HRESULT Create(const CXFile &file, IDxcFile **pObject); const CXFile &GetFile() const { return m_file; } HRESULT STDMETHODCALLTYPE GetName(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE IsEqualTo(IDxcFile *other, BOOL *pResult) override; }; class DxcInclusion : public IDxcInclusion { private: DXC_MICROCOM_TM_REF_FIELDS() CXFile m_file; CXSourceLocation *m_locations; unsigned m_locationLength; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcInclusion) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcInclusion>(this, iid, ppvObject); } DxcInclusion(IMalloc *pMalloc); ~DxcInclusion(); HRESULT Initialize(CXFile file, unsigned locations, CXSourceLocation *pLocation); static HRESULT Create(CXFile file, unsigned locations, CXSourceLocation *pLocation, IDxcInclusion **pResult); HRESULT STDMETHODCALLTYPE GetIncludedFile(IDxcFile **pResult) override; HRESULT STDMETHODCALLTYPE GetStackLength(unsigned *pResult) override; HRESULT STDMETHODCALLTYPE GetStackItem(unsigned index, IDxcSourceLocation **pResult) override; }; class DxcIndex : public IDxcIndex { private: DXC_MICROCOM_TM_REF_FIELDS() CXIndex m_index; DxcGlobalOptions m_options; hlsl::DxcLangExtensionsHelper m_langHelper; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcIndex) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcIndex>(this, iid, ppvObject); } DxcIndex(IMalloc *pMalloc); ~DxcIndex(); HRESULT Initialize(hlsl::DxcLangExtensionsHelper &langHelper); static HRESULT Create(hlsl::DxcLangExtensionsHelper &langHelper, DxcIndex **index); HRESULT STDMETHODCALLTYPE SetGlobalOptions(DxcGlobalOptions options) override; HRESULT STDMETHODCALLTYPE GetGlobalOptions(DxcGlobalOptions *options) override; HRESULT STDMETHODCALLTYPE ParseTranslationUnit( const char *source_filename, const char *const *command_line_args, int num_command_line_args, IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files, DxcTranslationUnitFlags options, IDxcTranslationUnit **pTranslationUnit) override; }; class DxcIntelliSense : public IDxcIntelliSense, public IDxcLangExtensions3 { private: DXC_MICROCOM_TM_REF_FIELDS() hlsl::DxcLangExtensionsHelper m_langHelper; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL(); DXC_MICROCOM_TM_CTOR(DxcIntelliSense) DXC_LANGEXTENSIONS_HELPER_IMPL(m_langHelper); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcIntelliSense, IDxcLangExtensions, IDxcLangExtensions2, IDxcLangExtensions3>( this, iid, ppvObject); } HRESULT STDMETHODCALLTYPE CreateIndex(IDxcIndex **index) override; HRESULT STDMETHODCALLTYPE GetNullLocation(IDxcSourceLocation **location) override; HRESULT STDMETHODCALLTYPE GetNullRange(IDxcSourceRange **location) override; HRESULT STDMETHODCALLTYPE GetRange(IDxcSourceLocation *start, IDxcSourceLocation *end, IDxcSourceRange **location) override; HRESULT STDMETHODCALLTYPE GetDefaultDiagnosticDisplayOptions( DxcDiagnosticDisplayOptions *pValue) override; HRESULT STDMETHODCALLTYPE GetDefaultEditingTUOptions(DxcTranslationUnitFlags *pValue) override; HRESULT STDMETHODCALLTYPE CreateUnsavedFile(LPCSTR fileName, LPCSTR contents, unsigned contentLength, IDxcUnsavedFile **pResult) override; }; class DxcSourceLocation : public IDxcSourceLocation { private: DXC_MICROCOM_TM_REF_FIELDS() CXSourceLocation m_location; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcSourceLocation) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcSourceLocation>(this, iid, ppvObject); } void Initialize(const CXSourceLocation &location); static HRESULT Create(const CXSourceLocation &location, IDxcSourceLocation **pObject); const CXSourceLocation &GetLocation() const { return m_location; } HRESULT STDMETHODCALLTYPE IsEqualTo(IDxcSourceLocation *other, BOOL *pValue) override; HRESULT STDMETHODCALLTYPE GetSpellingLocation(IDxcFile **pFile, unsigned *pLine, unsigned *pCol, unsigned *pOffset) override; HRESULT STDMETHODCALLTYPE IsNull(BOOL *pResult) override; HRESULT STDMETHODCALLTYPE GetPresumedLocation(LPSTR *pFilename, unsigned *pLine, unsigned *pCol) override; }; class DxcSourceRange : public IDxcSourceRange { private: DXC_MICROCOM_TM_REF_FIELDS() CXSourceRange m_range; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcSourceRange) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcSourceRange>(this, iid, ppvObject); } void Initialize(const CXSourceRange &range); static HRESULT Create(const CXSourceRange &range, IDxcSourceRange **pObject); const CXSourceRange &GetRange() const { return m_range; } HRESULT STDMETHODCALLTYPE IsNull(BOOL *pValue) override; HRESULT STDMETHODCALLTYPE GetStart(IDxcSourceLocation **pValue) override; HRESULT STDMETHODCALLTYPE GetEnd(IDxcSourceLocation **pValue) override; HRESULT STDMETHODCALLTYPE GetOffsets(unsigned *startOffset, unsigned *endOffset) override; }; class DxcToken : public IDxcToken { private: DXC_MICROCOM_TM_REF_FIELDS() CXToken m_token; CXTranslationUnit m_tu; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcToken) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcToken>(this, iid, ppvObject); } void Initialize(const CXTranslationUnit &tu, const CXToken &token); static HRESULT Create(const CXTranslationUnit &tu, const CXToken &token, IDxcToken **pObject); HRESULT STDMETHODCALLTYPE GetKind(DxcTokenKind *pValue) override; HRESULT STDMETHODCALLTYPE GetLocation(IDxcSourceLocation **pValue) override; HRESULT STDMETHODCALLTYPE GetExtent(IDxcSourceRange **pValue) override; HRESULT STDMETHODCALLTYPE GetSpelling(LPSTR *pValue) override; }; class DxcTranslationUnit : public IDxcTranslationUnit { private: DXC_MICROCOM_TM_REF_FIELDS() CXTranslationUnit m_tu; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcTranslationUnit) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcTranslationUnit>(this, iid, ppvObject); } DxcTranslationUnit(IMalloc *pMalloc); ~DxcTranslationUnit(); void Initialize(CXTranslationUnit tu); HRESULT STDMETHODCALLTYPE GetCursor(IDxcCursor **pCursor) override; HRESULT STDMETHODCALLTYPE Tokenize(IDxcSourceRange *range, IDxcToken ***pTokens, unsigned *pTokenCount) override; HRESULT STDMETHODCALLTYPE GetLocation(IDxcFile *file, unsigned line, unsigned column, IDxcSourceLocation **pResult) override; HRESULT STDMETHODCALLTYPE GetNumDiagnostics(unsigned *pValue) override; HRESULT STDMETHODCALLTYPE GetDiagnostic(unsigned index, IDxcDiagnostic **pValue) override; HRESULT STDMETHODCALLTYPE GetFile(const char *name, IDxcFile **pResult) override; HRESULT STDMETHODCALLTYPE GetFileName(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE Reparse(IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files) override; HRESULT STDMETHODCALLTYPE GetCursorForLocation(IDxcSourceLocation *location, IDxcCursor **pResult) override; HRESULT STDMETHODCALLTYPE GetLocationForOffset( IDxcFile *file, unsigned offset, IDxcSourceLocation **pResult) override; HRESULT STDMETHODCALLTYPE GetSkippedRanges(IDxcFile *file, unsigned *pResultCount, IDxcSourceRange ***pResult) override; HRESULT STDMETHODCALLTYPE GetDiagnosticDetails( unsigned index, DxcDiagnosticDisplayOptions options, unsigned *errorCode, unsigned *errorLine, unsigned *errorColumn, BSTR *errorFile, unsigned *errorOffset, unsigned *errorLength, BSTR *errorMessage) override; HRESULT STDMETHODCALLTYPE GetInclusionList(unsigned *pResultCount, IDxcInclusion ***pResult) override; HRESULT STDMETHODCALLTYPE CodeCompleteAt( const char *fileName, unsigned line, unsigned column, IDxcUnsavedFile **pUnsavedFiles, unsigned numUnsavedFiles, DxcCodeCompleteFlags options, IDxcCodeCompleteResults **pResult) override; }; class DxcType : public IDxcType { private: DXC_MICROCOM_TM_REF_FIELDS() CXType m_type; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcType) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcType>(this, iid, ppvObject); } void Initialize(const CXType &type); static HRESULT Create(const CXType &type, IDxcType **pObject); HRESULT STDMETHODCALLTYPE GetSpelling(LPSTR *pResult) override; HRESULT STDMETHODCALLTYPE IsEqualTo(IDxcType *other, BOOL *pResult) override; HRESULT STDMETHODCALLTYPE GetKind(DxcTypeKind *pResult) override; }; class DxcCodeCompleteResults : public IDxcCodeCompleteResults { private: DXC_MICROCOM_TM_REF_FIELDS() CXCodeCompleteResults *m_ccr; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcCodeCompleteResults) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcCodeCompleteResults>(this, iid, ppvObject); } ~DxcCodeCompleteResults(); void Initialize(CXCodeCompleteResults *ccr); HRESULT STDMETHODCALLTYPE GetNumResults(unsigned *pResult) override; HRESULT STDMETHODCALLTYPE GetResultAt(unsigned index, IDxcCompletionResult **pResult) override; }; class DxcCompletionResult : public IDxcCompletionResult { private: DXC_MICROCOM_TM_REF_FIELDS() CXCompletionResult m_cr; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcCompletionResult) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcCompletionResult>(this, iid, ppvObject); } void Initialize(const CXCompletionResult &cr); HRESULT STDMETHODCALLTYPE GetCursorKind(DxcCursorKind *pResult) override; HRESULT STDMETHODCALLTYPE GetCompletionString(IDxcCompletionString **pResult) override; }; class DxcCompletionString : public IDxcCompletionString { private: DXC_MICROCOM_TM_REF_FIELDS() CXCompletionString m_cs; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcCompletionString) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcCompletionString>(this, iid, ppvObject); } void Initialize(const CXCompletionString &cs); HRESULT STDMETHODCALLTYPE GetNumCompletionChunks(unsigned *pResult) override; HRESULT STDMETHODCALLTYPE GetCompletionChunkKind( unsigned chunkNumber, DxcCompletionChunkKind *pResult) override; HRESULT STDMETHODCALLTYPE GetCompletionChunkText(unsigned chunkNumber, LPSTR *pResult) override; }; HRESULT CreateDxcIntelliSense(REFIID riid, LPVOID *ppv) throw(); #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CursorVisitor.h
//===- CursorVisitor.h - CursorVisitor interface ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CURSORVISITOR_H #define LLVM_CLANG_TOOLS_LIBCLANG_CURSORVISITOR_H #include "CXCursor.h" #include "CXTranslationUnit.h" #include "Index_Internal.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/TypeLocVisitor.h" namespace clang { class PreprocessingRecord; class ASTUnit; namespace cxcursor { class VisitorJob { public: enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind, TypeLocVisitKind, OverloadExprPartsKind, DeclRefExprPartsKind, LabelRefVisitKind, ExplicitTemplateArgsVisitKind, NestedNameSpecifierLocVisitKind, DeclarationNameInfoVisitKind, MemberRefVisitKind, SizeOfPackExprPartsKind, LambdaExprPartsKind, PostChildrenVisitKind }; protected: const void *data[3]; CXCursor parent; Kind K; VisitorJob(CXCursor C, Kind k, const void *d1, const void *d2 = nullptr, const void *d3 = nullptr) : parent(C), K(k) { data[0] = d1; data[1] = d2; data[2] = d3; } public: Kind getKind() const { return K; } const CXCursor &getParent() const { return parent; } }; typedef SmallVector<VisitorJob, 10> VisitorWorkList; // Cursor visitor. class CursorVisitor : public DeclVisitor<CursorVisitor, bool>, public TypeLocVisitor<CursorVisitor, bool> { public: /// \brief Callback called after child nodes of a cursor have been visited. /// Return true to break visitation or false to continue. typedef bool (*PostChildrenVisitorTy)(CXCursor cursor, CXClientData client_data); private: /// \brief The translation unit we are traversing. CXTranslationUnit TU; ASTUnit *AU; /// \brief The parent cursor whose children we are traversing. CXCursor Parent; /// \brief The declaration that serves at the parent of any statement or /// expression nodes. const Decl *StmtParent; /// \brief The visitor function. CXCursorVisitor Visitor; PostChildrenVisitorTy PostChildrenVisitor; /// \brief The opaque client data, to be passed along to the visitor. CXClientData ClientData; /// \brief Whether we should visit the preprocessing record entries last, /// after visiting other declarations. bool VisitPreprocessorLast; /// \brief Whether we should visit declarations or preprocessing record /// entries that are #included inside the \arg RegionOfInterest. bool VisitIncludedEntities; /// \brief When valid, a source range to which the cursor should restrict /// its search. SourceRange RegionOfInterest; /// \brief Whether we should only visit declarations and not preprocessing /// record entries. bool VisitDeclsOnly; // FIXME: Eventually remove. This part of a hack to support proper // iteration over all Decls contained lexically within an ObjC container. DeclContext::decl_iterator *DI_current; DeclContext::decl_iterator DE_current; SmallVectorImpl<Decl *>::iterator *FileDI_current; SmallVectorImpl<Decl *>::iterator FileDE_current; // Cache of pre-allocated worklists for data-recursion walk of Stmts. SmallVector<VisitorWorkList*, 5> WorkListFreeList; SmallVector<VisitorWorkList*, 5> WorkListCache; using DeclVisitor<CursorVisitor, bool>::Visit; using TypeLocVisitor<CursorVisitor, bool>::Visit; /// \brief Determine whether this particular source range comes before, comes /// after, or overlaps the region of interest. /// /// \param R a half-open source range retrieved from the abstract syntax tree. RangeComparisonResult CompareRegionOfInterest(SourceRange R); bool visitDeclsFromFileRegion(FileID File, unsigned Offset, unsigned Length); class SetParentRAII { CXCursor &Parent; const Decl *&StmtParent; CXCursor OldParent; public: SetParentRAII(CXCursor &Parent, const Decl *&StmtParent, CXCursor NewParent) : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) { Parent = NewParent; if (clang_isDeclaration(Parent.kind)) StmtParent = getCursorDecl(Parent); } ~SetParentRAII() { Parent = OldParent; if (clang_isDeclaration(Parent.kind)) StmtParent = getCursorDecl(Parent); } }; public: CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor, CXClientData ClientData, bool VisitPreprocessorLast, bool VisitIncludedPreprocessingEntries = false, SourceRange RegionOfInterest = SourceRange(), bool VisitDeclsOnly = false, PostChildrenVisitorTy PostChildrenVisitor = nullptr) : TU(TU), AU(cxtu::getASTUnit(TU)), Visitor(Visitor), PostChildrenVisitor(PostChildrenVisitor), ClientData(ClientData), VisitPreprocessorLast(VisitPreprocessorLast), VisitIncludedEntities(VisitIncludedPreprocessingEntries), RegionOfInterest(RegionOfInterest), VisitDeclsOnly(VisitDeclsOnly), DI_current(nullptr), FileDI_current(nullptr) { Parent.kind = CXCursor_NoDeclFound; Parent.data[0] = nullptr; Parent.data[1] = nullptr; Parent.data[2] = nullptr; StmtParent = nullptr; } ~CursorVisitor() { // Free the pre-allocated worklists for data-recursion. for (SmallVectorImpl<VisitorWorkList*>::iterator I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) { delete *I; } } ASTUnit *getASTUnit() const { return AU; } CXTranslationUnit getTU() const { return TU; } bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); /// \brief Visit declarations and preprocessed entities for the file region /// designated by \see RegionOfInterest. bool visitFileRegion(); bool visitPreprocessedEntitiesInRegion(); bool shouldVisitIncludedEntities() const { return VisitIncludedEntities; } template<typename InputIterator> bool visitPreprocessedEntities(InputIterator First, InputIterator Last, PreprocessingRecord &PPRec, FileID FID = FileID()); bool VisitChildren(CXCursor Parent); // Declaration visitors bool VisitTypeAliasDecl(TypeAliasDecl *D); bool VisitAttributes(Decl *D); bool VisitBlockDecl(BlockDecl *B); bool VisitCXXRecordDecl(CXXRecordDecl *D); Optional<bool> shouldVisitCursor(CXCursor C); bool VisitDeclContext(DeclContext *DC); bool VisitTranslationUnitDecl(TranslationUnitDecl *D); bool VisitTypedefDecl(TypedefDecl *D); bool VisitTagDecl(TagDecl *D); bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); bool VisitClassTemplatePartialSpecializationDecl( ClassTemplatePartialSpecializationDecl *D); bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); bool VisitEnumConstantDecl(EnumConstantDecl *D); bool VisitDeclaratorDecl(DeclaratorDecl *DD); bool VisitFunctionDecl(FunctionDecl *ND); bool VisitFieldDecl(FieldDecl *D); bool VisitVarDecl(VarDecl *); bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D); bool VisitClassTemplateDecl(ClassTemplateDecl *D); bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); bool VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); bool VisitObjCMethodDecl(ObjCMethodDecl *ND); bool VisitObjCContainerDecl(ObjCContainerDecl *D); bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD); bool VisitObjCTypeParamList(ObjCTypeParamList *typeParamList); bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); bool VisitObjCImplDecl(ObjCImplDecl *D); bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD); bool VisitLinkageSpecDecl(LinkageSpecDecl *D); bool VisitNamespaceDecl(NamespaceDecl *D); bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D); bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D); bool VisitUsingDecl(UsingDecl *D); bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); // Name visitor bool VisitDeclarationNameInfo(DeclarationNameInfo Name); bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range); bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS); // Template visitors bool VisitTemplateParameters(const TemplateParameterList *Params); bool VisitTemplateName(TemplateName Name, SourceLocation Loc); bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL); bool VisitHLSLBufferDecl(HLSLBufferDecl *D); // HLSL Change // Type visitors #define ABSTRACT_TYPELOC(CLASS, PARENT) #define TYPELOC(CLASS, PARENT) \ bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); #include "clang/AST/TypeLocNodes.def" bool VisitTagTypeLoc(TagTypeLoc TL); bool VisitArrayTypeLoc(ArrayTypeLoc TL); bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); // Data-recursive visitor functions. bool IsInRegionOfInterest(CXCursor C); bool RunVisitorWorkList(VisitorWorkList &WL); void EnqueueWorkList(VisitorWorkList &WL, const Stmt *S); LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S); }; } } #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexHigh.cpp
//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CursorVisitor.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXTranslationUnit.h" #include "clang/AST/DeclObjC.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/Support/Compiler.h" using namespace clang; using namespace cxcursor; using namespace cxindex; static void getTopOverriddenMethods(CXTranslationUnit TU, const Decl *D, SmallVectorImpl<const Decl *> &Methods) { if (!D) return; if (!isa<ObjCMethodDecl>(D) && !isa<CXXMethodDecl>(D)) return; SmallVector<CXCursor, 8> Overridden; cxcursor::getOverriddenCursors(cxcursor::MakeCXCursor(D, TU), Overridden); if (Overridden.empty()) { Methods.push_back(D->getCanonicalDecl()); return; } for (SmallVectorImpl<CXCursor>::iterator I = Overridden.begin(), E = Overridden.end(); I != E; ++I) getTopOverriddenMethods(TU, cxcursor::getCursorDecl(*I), Methods); } namespace { struct FindFileIdRefVisitData { CXTranslationUnit TU; FileID FID; const Decl *Dcl; int SelectorIdIdx; CXCursorAndRangeVisitor visitor; typedef SmallVector<const Decl *, 8> TopMethodsTy; TopMethodsTy TopMethods; FindFileIdRefVisitData(CXTranslationUnit TU, FileID FID, const Decl *D, int selectorIdIdx, CXCursorAndRangeVisitor visitor) : TU(TU), FID(FID), SelectorIdIdx(selectorIdIdx), visitor(visitor) { Dcl = getCanonical(D); getTopOverriddenMethods(TU, Dcl, TopMethods); } ASTContext &getASTContext() const { return cxtu::getASTUnit(TU)->getASTContext(); } /// \brief We are looking to find all semantically relevant identifiers, /// so the definition of "canonical" here is different than in the AST, e.g. /// /// \code /// class C { /// C() {} /// }; /// \endcode /// /// we consider the canonical decl of the constructor decl to be the class /// itself, so both 'C' can be highlighted. const Decl *getCanonical(const Decl *D) const { if (!D) return nullptr; D = D->getCanonicalDecl(); if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) { if (ImplD->getClassInterface()) return getCanonical(ImplD->getClassInterface()); } else if (const CXXConstructorDecl *CXXCtorD = dyn_cast<CXXConstructorDecl>(D)) { return getCanonical(CXXCtorD->getParent()); } return D; } bool isHit(const Decl *D) const { if (!D) return false; D = getCanonical(D); if (D == Dcl) return true; if (isa<ObjCMethodDecl>(D) || isa<CXXMethodDecl>(D)) return isOverriddingMethod(D); return false; } private: bool isOverriddingMethod(const Decl *D) const { if (std::find(TopMethods.begin(), TopMethods.end(), D) != TopMethods.end()) return true; TopMethodsTy methods; getTopOverriddenMethods(TU, D, methods); for (TopMethodsTy::iterator I = methods.begin(), E = methods.end(); I != E; ++I) { if (std::find(TopMethods.begin(), TopMethods.end(), *I) != TopMethods.end()) return true; } return false; } }; } // end anonymous namespace. /// \brief For a macro \arg Loc, returns the file spelling location and sets /// to \arg isMacroArg whether the spelling resides inside a macro definition or /// a macro argument. static SourceLocation getFileSpellingLoc(SourceManager &SM, SourceLocation Loc, bool &isMacroArg) { assert(Loc.isMacroID()); SourceLocation SpellLoc = SM.getImmediateSpellingLoc(Loc); if (SpellLoc.isMacroID()) return getFileSpellingLoc(SM, SpellLoc, isMacroArg); isMacroArg = SM.isMacroArgExpansion(Loc); return SpellLoc; } static enum CXChildVisitResult findFileIdRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursor declCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(declCursor.kind)) return CXChildVisit_Recurse; const Decl *D = cxcursor::getCursorDecl(declCursor); if (!D) return CXChildVisit_Continue; FindFileIdRefVisitData *data = (FindFileIdRefVisitData *)client_data; if (data->isHit(D)) { cursor = cxcursor::getSelectorIdentifierCursor(data->SelectorIdIdx, cursor); // We are looking for identifiers to highlight so for objc methods (and // not a parameter) we can only highlight the selector identifiers. if ((cursor.kind == CXCursor_ObjCClassMethodDecl || cursor.kind == CXCursor_ObjCInstanceMethodDecl) && cxcursor::getSelectorIdentifierIndex(cursor) == -1) return CXChildVisit_Recurse; if (clang_isExpression(cursor.kind)) { if (cursor.kind == CXCursor_DeclRefExpr || cursor.kind == CXCursor_MemberRefExpr) { // continue.. } else if (cursor.kind == CXCursor_ObjCMessageExpr && cxcursor::getSelectorIdentifierIndex(cursor) != -1) { // continue.. } else return CXChildVisit_Recurse; } SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); SourceLocation SelIdLoc = cxcursor::getSelectorIdentifierLoc(cursor); if (SelIdLoc.isValid()) Loc = SelIdLoc; ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (LocInfo.first != data->FID) return CXChildVisit_Recurse; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Recurse; } if (data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)) == CXVisit_Break) return CXChildVisit_Break; } return CXChildVisit_Recurse; } static bool findIdRefsInFile(CXTranslationUnit TU, CXCursor declCursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { assert(clang_isDeclaration(declCursor.kind)); SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); FileID FID = SM.translateFile(File); const Decl *Dcl = cxcursor::getCursorDecl(declCursor); if (!Dcl) return false; FindFileIdRefVisitData data(TU, FID, Dcl, cxcursor::getSelectorIdentifierIndex(declCursor), Visitor); if (const DeclContext *DC = Dcl->getParentFunctionOrMethod()) { return clang_visitChildren(cxcursor::MakeCXCursor(cast<Decl>(DC), TU), findFileIdRefVisit, &data); } SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindIdRefsVisitor(TU, findFileIdRefVisit, &data, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, Range, /*VisitDeclsOnly=*/true); return FindIdRefsVisitor.visitFileRegion(); } namespace { struct FindFileMacroRefVisitData { ASTUnit &Unit; const FileEntry *File; const IdentifierInfo *Macro; CXCursorAndRangeVisitor visitor; FindFileMacroRefVisitData(ASTUnit &Unit, const FileEntry *File, const IdentifierInfo *Macro, CXCursorAndRangeVisitor visitor) : Unit(Unit), File(File), Macro(Macro), visitor(visitor) { } ASTContext &getASTContext() const { return Unit.getASTContext(); } }; } // anonymous namespace static enum CXChildVisitResult findFileMacroRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { const IdentifierInfo *Macro = nullptr; if (cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(cursor)->getName(); else if (cursor.kind == CXCursor_MacroExpansion) Macro = getCursorMacroExpansion(cursor).getName(); if (!Macro) return CXChildVisit_Continue; FindFileMacroRefVisitData *data = (FindFileMacroRefVisitData *)client_data; if (data->Macro != Macro) return CXChildVisit_Continue; SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (SM.getFileEntryForID(LocInfo.first) != data->File) return CXChildVisit_Continue; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Continue; } if (data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)) == CXVisit_Break) return CXChildVisit_Break; return CXChildVisit_Continue; } static bool findMacroRefsInFile(CXTranslationUnit TU, CXCursor Cursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { if (Cursor.kind != CXCursor_MacroDefinition && Cursor.kind != CXCursor_MacroExpansion) return false; ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); FileID FID = SM.translateFile(File); const IdentifierInfo *Macro = nullptr; if (Cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(Cursor)->getName(); else Macro = getCursorMacroExpansion(Cursor).getName(); if (!Macro) return false; FindFileMacroRefVisitData data(*Unit, File, Macro, Visitor); SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindMacroRefsVisitor(TU, findFileMacroRefVisit, &data, /*VisitPreprocessorLast=*/false, /*VisitIncludedEntities=*/false, Range); return FindMacroRefsVisitor.visitPreprocessedEntitiesInRegion(); } namespace { struct FindFileIncludesVisitor { ASTUnit &Unit; const FileEntry *File; CXCursorAndRangeVisitor visitor; FindFileIncludesVisitor(ASTUnit &Unit, const FileEntry *File, CXCursorAndRangeVisitor visitor) : Unit(Unit), File(File), visitor(visitor) { } ASTContext &getASTContext() const { return Unit.getASTContext(); } enum CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { if (cursor.kind != CXCursor_InclusionDirective) return CXChildVisit_Continue; SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); ASTContext &Ctx = getASTContext(); SourceManager &SM = Ctx.getSourceManager(); // We are looking for includes in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (SM.getFileEntryForID(LocInfo.first) != File) return CXChildVisit_Continue; if (visitor.visit(visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)) == CXVisit_Break) return CXChildVisit_Break; return CXChildVisit_Continue; } static enum CXChildVisitResult visit(CXCursor cursor, CXCursor parent, CXClientData client_data) { return static_cast<FindFileIncludesVisitor*>(client_data)-> visit(cursor, parent); } }; } // anonymous namespace static bool findIncludesInFile(CXTranslationUnit TU, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { assert(TU && File && Visitor.visit); ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); FileID FID = SM.translateFile(File); FindFileIncludesVisitor IncludesVisitor(*Unit, File, Visitor); SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor InclusionCursorsVisitor(TU, FindFileIncludesVisitor::visit, &IncludesVisitor, /*VisitPreprocessorLast=*/false, /*VisitIncludedEntities=*/false, Range); return InclusionCursorsVisitor.visitPreprocessedEntitiesInRegion(); } //===----------------------------------------------------------------------===// // libclang public APIs. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXResult clang_findReferencesInFile(CXCursor cursor, CXFile file, CXCursorAndRangeVisitor visitor) { LogRef Log = Logger::make(LLVM_FUNCTION_NAME); if (clang_Cursor_isNull(cursor)) { if (Log) *Log << "Null cursor"; return CXResult_Invalid; } if (cursor.kind == CXCursor_NoDeclFound) { if (Log) *Log << "Got CXCursor_NoDeclFound"; return CXResult_Invalid; } if (!file) { if (Log) *Log << "Null file"; return CXResult_Invalid; } if (!visitor.visit) { if (Log) *Log << "Null visitor"; return CXResult_Invalid; } if (Log) *Log << cursor << " @" << static_cast<const FileEntry *>(file); ASTUnit *CXXUnit = cxcursor::getCursorASTUnit(cursor); if (!CXXUnit) return CXResult_Invalid; ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (cursor.kind == CXCursor_MacroDefinition || cursor.kind == CXCursor_MacroExpansion) { if (findMacroRefsInFile(cxcursor::getCursorTU(cursor), cursor, static_cast<const FileEntry *>(file), visitor)) return CXResult_VisitBreak; return CXResult_Success; } // We are interested in semantics of identifiers so for C++ constructor exprs // prefer type references, e.g.: // // return MyStruct(); // // for 'MyStruct' we'll have a cursor pointing at the constructor decl but // we are actually interested in the type declaration. cursor = cxcursor::getTypeRefCursor(cursor); CXCursor refCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(refCursor.kind)) { if (Log) *Log << "cursor is not referencing a declaration"; return CXResult_Invalid; } if (findIdRefsInFile(cxcursor::getCursorTU(cursor), refCursor, static_cast<const FileEntry *>(file), visitor)) return CXResult_VisitBreak; return CXResult_Success; } CXResult clang_findIncludesInFile(CXTranslationUnit TU, CXFile file, CXCursorAndRangeVisitor visitor) { if (cxtu::isNotUsableTU(TU)) { LOG_BAD_TU(TU); return CXResult_Invalid; } LogRef Log = Logger::make(LLVM_FUNCTION_NAME); if (!file) { if (Log) *Log << "Null file"; return CXResult_Invalid; } if (!visitor.visit) { if (Log) *Log << "Null visitor"; return CXResult_Invalid; } if (Log) *Log << TU << " @" << static_cast<const FileEntry *>(file); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit) return CXResult_Invalid; ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (findIncludesInFile(TU, static_cast<const FileEntry *>(file), visitor)) return CXResult_VisitBreak; return CXResult_Success; } static enum CXVisitorResult _visitCursorAndRange(void *context, CXCursor cursor, CXSourceRange range) { CXCursorAndRangeVisitorBlock block = (CXCursorAndRangeVisitorBlock)context; return INVOKE_BLOCK2(block, cursor, range); } CXResult clang_findReferencesInFileWithBlock(CXCursor cursor, CXFile file, CXCursorAndRangeVisitorBlock block) { CXCursorAndRangeVisitor visitor = { block, block ? _visitCursorAndRange : nullptr }; return clang_findReferencesInFile(cursor, file, visitor); } CXResult clang_findIncludesInFileWithBlock(CXTranslationUnit TU, CXFile file, CXCursorAndRangeVisitorBlock block) { CXCursorAndRangeVisitor visitor = { block, block ? _visitCursorAndRange : nullptr }; return clang_findIncludesInFile(TU, file, visitor); } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/IndexingContext.h
//===- IndexingContext.h - Higher level API functions -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_INDEXINGCONTEXT_H #define LLVM_CLANG_TOOLS_LIBCLANG_INDEXINGCONTEXT_H #include "CXCursor.h" #include "Index_Internal.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/DeclObjC.h" #include "llvm/ADT/DenseSet.h" #include <deque> namespace clang { class FileEntry; class MSPropertyDecl; class ObjCPropertyDecl; class ClassTemplateDecl; class FunctionTemplateDecl; class TypeAliasTemplateDecl; class ClassTemplateSpecializationDecl; namespace cxindex { class IndexingContext; class AttrListInfo; class ScratchAlloc { IndexingContext &IdxCtx; public: explicit ScratchAlloc(IndexingContext &indexCtx); ScratchAlloc(const ScratchAlloc &SA); ~ScratchAlloc(); const char *toCStr(StringRef Str); const char *copyCStr(StringRef Str); template <typename T> T *allocate(); }; struct EntityInfo : public CXIdxEntityInfo { const NamedDecl *Dcl; IndexingContext *IndexCtx; IntrusiveRefCntPtr<AttrListInfo> AttrList; EntityInfo() { name = USR = nullptr; attributes = nullptr; numAttributes = 0; } }; struct ContainerInfo : public CXIdxContainerInfo { const DeclContext *DC; IndexingContext *IndexCtx; }; struct DeclInfo : public CXIdxDeclInfo { enum DInfoKind { Info_Decl, Info_ObjCContainer, Info_ObjCInterface, Info_ObjCProtocol, Info_ObjCCategory, Info_ObjCProperty, Info_CXXClass }; DInfoKind Kind; EntityInfo EntInfo; ContainerInfo SemanticContainer; ContainerInfo LexicalContainer; ContainerInfo DeclAsContainer; DeclInfo(bool isRedeclaration, bool isDefinition, bool isContainer) : Kind(Info_Decl) { this->isRedeclaration = isRedeclaration; this->isDefinition = isDefinition; this->isContainer = isContainer; attributes = nullptr; numAttributes = 0; declAsContainer = semanticContainer = lexicalContainer = nullptr; flags = 0; } DeclInfo(DInfoKind K, bool isRedeclaration, bool isDefinition, bool isContainer) : Kind(K) { this->isRedeclaration = isRedeclaration; this->isDefinition = isDefinition; this->isContainer = isContainer; attributes = nullptr; numAttributes = 0; declAsContainer = semanticContainer = lexicalContainer = nullptr; flags = 0; } }; struct ObjCContainerDeclInfo : public DeclInfo { CXIdxObjCContainerDeclInfo ObjCContDeclInfo; ObjCContainerDeclInfo(bool isForwardRef, bool isRedeclaration, bool isImplementation) : DeclInfo(Info_ObjCContainer, isRedeclaration, /*isDefinition=*/!isForwardRef, /*isContainer=*/!isForwardRef) { init(isForwardRef, isImplementation); } ObjCContainerDeclInfo(DInfoKind K, bool isForwardRef, bool isRedeclaration, bool isImplementation) : DeclInfo(K, isRedeclaration, /*isDefinition=*/!isForwardRef, /*isContainer=*/!isForwardRef) { init(isForwardRef, isImplementation); } static bool classof(const DeclInfo *D) { return Info_ObjCContainer <= D->Kind && D->Kind <= Info_ObjCCategory; } private: void init(bool isForwardRef, bool isImplementation) { if (isForwardRef) ObjCContDeclInfo.kind = CXIdxObjCContainer_ForwardRef; else if (isImplementation) ObjCContDeclInfo.kind = CXIdxObjCContainer_Implementation; else ObjCContDeclInfo.kind = CXIdxObjCContainer_Interface; } }; struct ObjCInterfaceDeclInfo : public ObjCContainerDeclInfo { CXIdxObjCInterfaceDeclInfo ObjCInterDeclInfo; CXIdxObjCProtocolRefListInfo ObjCProtoListInfo; ObjCInterfaceDeclInfo(const ObjCInterfaceDecl *D) : ObjCContainerDeclInfo(Info_ObjCInterface, /*isForwardRef=*/false, /*isRedeclaration=*/D->getPreviousDecl() != nullptr, /*isImplementation=*/false) { } static bool classof(const DeclInfo *D) { return D->Kind == Info_ObjCInterface; } }; struct ObjCProtocolDeclInfo : public ObjCContainerDeclInfo { CXIdxObjCProtocolRefListInfo ObjCProtoRefListInfo; ObjCProtocolDeclInfo(const ObjCProtocolDecl *D) : ObjCContainerDeclInfo(Info_ObjCProtocol, /*isForwardRef=*/false, /*isRedeclaration=*/D->getPreviousDecl(), /*isImplementation=*/false) { } static bool classof(const DeclInfo *D) { return D->Kind == Info_ObjCProtocol; } }; struct ObjCCategoryDeclInfo : public ObjCContainerDeclInfo { CXIdxObjCCategoryDeclInfo ObjCCatDeclInfo; CXIdxObjCProtocolRefListInfo ObjCProtoListInfo; explicit ObjCCategoryDeclInfo(bool isImplementation) : ObjCContainerDeclInfo(Info_ObjCCategory, /*isForwardRef=*/false, /*isRedeclaration=*/isImplementation, /*isImplementation=*/isImplementation) { } static bool classof(const DeclInfo *D) { return D->Kind == Info_ObjCCategory; } }; struct ObjCPropertyDeclInfo : public DeclInfo { CXIdxObjCPropertyDeclInfo ObjCPropDeclInfo; ObjCPropertyDeclInfo() : DeclInfo(Info_ObjCProperty, /*isRedeclaration=*/false, /*isDefinition=*/false, /*isContainer=*/false) { } static bool classof(const DeclInfo *D) { return D->Kind == Info_ObjCProperty; } }; struct CXXClassDeclInfo : public DeclInfo { CXIdxCXXClassDeclInfo CXXClassInfo; CXXClassDeclInfo(bool isRedeclaration, bool isDefinition) : DeclInfo(Info_CXXClass, isRedeclaration, isDefinition, isDefinition) { } static bool classof(const DeclInfo *D) { return D->Kind == Info_CXXClass; } }; struct AttrInfo : public CXIdxAttrInfo { const Attr *A; AttrInfo(CXIdxAttrKind Kind, CXCursor C, CXIdxLoc Loc, const Attr *A) { kind = Kind; cursor = C; loc = Loc; this->A = A; } }; struct IBOutletCollectionInfo : public AttrInfo { EntityInfo ClassInfo; CXIdxIBOutletCollectionAttrInfo IBCollInfo; IBOutletCollectionInfo(CXCursor C, CXIdxLoc Loc, const Attr *A) : AttrInfo(CXIdxAttr_IBOutletCollection, C, Loc, A) { assert(C.kind == CXCursor_IBOutletCollectionAttr); IBCollInfo.objcClass = nullptr; } IBOutletCollectionInfo(const IBOutletCollectionInfo &other); static bool classof(const AttrInfo *A) { return A->kind == CXIdxAttr_IBOutletCollection; } }; class AttrListInfo { ScratchAlloc SA; SmallVector<AttrInfo, 2> Attrs; SmallVector<IBOutletCollectionInfo, 2> IBCollAttrs; SmallVector<CXIdxAttrInfo *, 2> CXAttrs; unsigned ref_cnt; AttrListInfo(const AttrListInfo &) = delete; void operator=(const AttrListInfo &) = delete; public: AttrListInfo(const Decl *D, IndexingContext &IdxCtx); static IntrusiveRefCntPtr<AttrListInfo> create(const Decl *D, IndexingContext &IdxCtx); const CXIdxAttrInfo *const *getAttrs() const { if (CXAttrs.empty()) return nullptr; return CXAttrs.data(); } unsigned getNumAttrs() const { return (unsigned)CXAttrs.size(); } /// \brief Retain/Release only useful when we allocate a AttrListInfo from the /// BumpPtrAllocator, and not from the stack; so that we keep a pointer // in the EntityInfo void Retain() { ++ref_cnt; } void Release() { assert (ref_cnt > 0 && "Reference count is already zero."); if (--ref_cnt == 0) { // Memory is allocated from a BumpPtrAllocator, no need to delete it. this->~AttrListInfo(); } } }; class IndexingContext { ASTContext *Ctx; CXClientData ClientData; IndexerCallbacks &CB; unsigned IndexOptions; CXTranslationUnit CXTU; typedef llvm::DenseMap<const FileEntry *, CXIdxClientFile> FileMapTy; typedef llvm::DenseMap<const DeclContext *, CXIdxClientContainer> ContainerMapTy; typedef llvm::DenseMap<const Decl *, CXIdxClientEntity> EntityMapTy; FileMapTy FileMap; ContainerMapTy ContainerMap; EntityMapTy EntityMap; typedef std::pair<const FileEntry *, const Decl *> RefFileOccurrence; llvm::DenseSet<RefFileOccurrence> RefFileOccurrences; std::deque<DeclGroupRef> TUDeclsInObjCContainer; llvm::BumpPtrAllocator StrScratch; unsigned StrAdapterCount; friend class ScratchAlloc; struct ObjCProtocolListInfo { SmallVector<CXIdxObjCProtocolRefInfo, 4> ProtInfos; SmallVector<EntityInfo, 4> ProtEntities; SmallVector<CXIdxObjCProtocolRefInfo *, 4> Prots; CXIdxObjCProtocolRefListInfo getListInfo() const { CXIdxObjCProtocolRefListInfo Info = { Prots.data(), (unsigned)Prots.size() }; return Info; } ObjCProtocolListInfo(const ObjCProtocolList &ProtList, IndexingContext &IdxCtx, ScratchAlloc &SA); }; struct CXXBasesListInfo { SmallVector<CXIdxBaseClassInfo, 4> BaseInfos; SmallVector<EntityInfo, 4> BaseEntities; SmallVector<CXIdxBaseClassInfo *, 4> CXBases; const CXIdxBaseClassInfo *const *getBases() const { return CXBases.data(); } unsigned getNumBases() const { return (unsigned)CXBases.size(); } CXXBasesListInfo(const CXXRecordDecl *D, IndexingContext &IdxCtx, ScratchAlloc &SA); private: SourceLocation getBaseLoc(const CXXBaseSpecifier &Base) const; }; friend class AttrListInfo; public: IndexingContext(CXClientData clientData, IndexerCallbacks &indexCallbacks, unsigned indexOptions, CXTranslationUnit cxTU) : Ctx(nullptr), ClientData(clientData), CB(indexCallbacks), IndexOptions(indexOptions), CXTU(cxTU), StrScratch(), StrAdapterCount(0) { } ASTContext &getASTContext() const { return *Ctx; } void setASTContext(ASTContext &ctx); void setPreprocessor(Preprocessor &PP); bool shouldSuppressRefs() const { return IndexOptions & CXIndexOpt_SuppressRedundantRefs; } bool shouldIndexFunctionLocalSymbols() const { return IndexOptions & CXIndexOpt_IndexFunctionLocalSymbols; } bool shouldIndexImplicitTemplateInsts() const { return IndexOptions & CXIndexOpt_IndexImplicitTemplateInstantiations; } static bool isFunctionLocalDecl(const Decl *D); bool shouldAbort(); bool hasDiagnosticCallback() const { return CB.diagnostic; } void enteredMainFile(const FileEntry *File); void ppIncludedFile(SourceLocation hashLoc, StringRef filename, const FileEntry *File, bool isImport, bool isAngled, bool isModuleImport); void importedModule(const ImportDecl *ImportD); void importedPCH(const FileEntry *File); void startedTranslationUnit(); void indexDecl(const Decl *D); void indexTagDecl(const TagDecl *D); void indexTypeSourceInfo(TypeSourceInfo *TInfo, const NamedDecl *Parent, const DeclContext *DC = nullptr); void indexTypeLoc(TypeLoc TL, const NamedDecl *Parent, const DeclContext *DC = nullptr); void indexNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const NamedDecl *Parent, const DeclContext *DC = nullptr); void indexDeclContext(const DeclContext *DC); void indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC = nullptr); void handleDiagnosticSet(CXDiagnosticSet CXDiagSet); bool handleFunction(const FunctionDecl *FD); bool handleVar(const VarDecl *D); bool handleField(const FieldDecl *D); bool handleMSProperty(const MSPropertyDecl *D); bool handleEnumerator(const EnumConstantDecl *D); bool handleTagDecl(const TagDecl *D); bool handleTypedefName(const TypedefNameDecl *D); bool handleObjCInterface(const ObjCInterfaceDecl *D); bool handleObjCImplementation(const ObjCImplementationDecl *D); bool handleObjCProtocol(const ObjCProtocolDecl *D); bool handleObjCCategory(const ObjCCategoryDecl *D); bool handleObjCCategoryImpl(const ObjCCategoryImplDecl *D); bool handleObjCMethod(const ObjCMethodDecl *D); bool handleSynthesizedObjCProperty(const ObjCPropertyImplDecl *D); bool handleSynthesizedObjCMethod(const ObjCMethodDecl *D, SourceLocation Loc, const DeclContext *LexicalDC); bool handleObjCProperty(const ObjCPropertyDecl *D); bool handleNamespace(const NamespaceDecl *D); bool handleClassTemplate(const ClassTemplateDecl *D); bool handleFunctionTemplate(const FunctionTemplateDecl *D); bool handleTypeAliasTemplate(const TypeAliasTemplateDecl *D); bool handleReference(const NamedDecl *D, SourceLocation Loc, CXCursor Cursor, const NamedDecl *Parent, const DeclContext *DC, const Expr *E = nullptr, CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct); bool handleReference(const NamedDecl *D, SourceLocation Loc, const NamedDecl *Parent, const DeclContext *DC, const Expr *E = nullptr, CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct); bool isNotFromSourceFile(SourceLocation Loc) const; void indexTopLevelDecl(const Decl *D); void indexTUDeclsInObjCContainer(); void indexDeclGroupRef(DeclGroupRef DG); void addTUDeclInObjCContainer(DeclGroupRef DG) { TUDeclsInObjCContainer.push_back(DG); } void translateLoc(SourceLocation Loc, CXIdxClientFile *indexFile, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); CXIdxClientContainer getClientContainerForDC(const DeclContext *DC) const; void addContainerInMap(const DeclContext *DC, CXIdxClientContainer container); CXIdxClientEntity getClientEntity(const Decl *D) const; void setClientEntity(const Decl *D, CXIdxClientEntity client); static bool isTemplateImplicitInstantiation(const Decl *D); private: bool handleDecl(const NamedDecl *D, SourceLocation Loc, CXCursor Cursor, DeclInfo &DInfo, const DeclContext *LexicalDC = nullptr); bool handleObjCContainer(const ObjCContainerDecl *D, SourceLocation Loc, CXCursor Cursor, ObjCContainerDeclInfo &ContDInfo); bool handleCXXRecordDecl(const CXXRecordDecl *RD, const NamedDecl *OrigD); bool markEntityOccurrenceInFile(const NamedDecl *D, SourceLocation Loc); const NamedDecl *getEntityDecl(const NamedDecl *D) const; const DeclContext *getEntityContainer(const Decl *D) const; CXIdxClientFile getIndexFile(const FileEntry *File); CXIdxLoc getIndexLoc(SourceLocation Loc) const; void getEntityInfo(const NamedDecl *D, EntityInfo &EntityInfo, ScratchAlloc &SA); void getContainerInfo(const DeclContext *DC, ContainerInfo &ContInfo); CXCursor getCursor(const Decl *D) { return cxcursor::MakeCXCursor(D, CXTU); } CXCursor getRefCursor(const NamedDecl *D, SourceLocation Loc); static bool shouldIgnoreIfImplicit(const Decl *D); }; inline ScratchAlloc::ScratchAlloc(IndexingContext &idxCtx) : IdxCtx(idxCtx) { ++IdxCtx.StrAdapterCount; } inline ScratchAlloc::ScratchAlloc(const ScratchAlloc &SA) : IdxCtx(SA.IdxCtx) { ++IdxCtx.StrAdapterCount; } inline ScratchAlloc::~ScratchAlloc() { --IdxCtx.StrAdapterCount; if (IdxCtx.StrAdapterCount == 0) IdxCtx.StrScratch.Reset(); } template <typename T> inline T *ScratchAlloc::allocate() { return IdxCtx.StrScratch.Allocate<T>(); } }} // end clang::cxindex #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/dxcrewriteunused.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcrewriteunused.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Compiler rewriter for unused data and functions. // // // /////////////////////////////////////////////////////////////////////////////// #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/HLSLMacroExpander.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/ParseAST.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Sema/SemaConsumer.h" #include "clang/Sema/SemaHLSL.h" #include "llvm/Support/Host.h" #include "dxc/Support/FileIOHelper.h" #include "dxc/Support/Global.h" #include "dxc/Support/Unicode.h" #include "dxc/Support/WinIncludes.h" #include "dxc/Support/microcom.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MSFileSystem.h" #include "dxc/Support/DxcLangExtensionsHelper.h" #include "dxc/Support/HLSLOptions.h" #include "dxc/Support/dxcapi.impl.h" #include "dxc/Support/dxcfilesystem.h" #include "dxc/dxcapi.internal.h" #include "dxc/dxctools.h" // From dxcutil.h namespace dxcutil { bool IsAbsoluteOrCurDirRelative(const llvm::Twine &T); } // namespace dxcutil #define CP_UTF16 1200 using namespace llvm; using namespace clang; using namespace hlsl; struct RewriteHelper { SmallPtrSet<VarDecl *, 128> unusedGlobals; SmallPtrSet<FunctionDecl *, 128> unusedFunctions; SmallPtrSet<TypeDecl *, 32> unusedTypes; DenseMap<RecordDecl *, unsigned> anonymousRecordRefCounts; }; struct ASTHelper { CompilerInstance compiler; TranslationUnitDecl *tu; ParsedSemanticDefineList semanticMacros; ParsedSemanticDefineList userMacros; bool bHasErrors; }; static FunctionDecl *getFunctionWithBody(FunctionDecl *F) { if (!F) return nullptr; if (F->doesThisDeclarationHaveABody()) return F; F = F->getFirstDecl(); for (auto &&Candidate : F->redecls()) { if (Candidate->doesThisDeclarationHaveABody()) { return Candidate; } } return nullptr; } static void SaveTypeDecl(TagDecl *tagDecl, SmallPtrSetImpl<TypeDecl *> &visitedTypes) { if (visitedTypes.count(tagDecl)) return; visitedTypes.insert(tagDecl); if (CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(tagDecl)) { // If template, save template args if (const ClassTemplateSpecializationDecl *templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(recordDecl)) { const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs(); for (unsigned i = 0; i < args.size(); ++i) { const clang::TemplateArgument &arg = args[i]; switch (arg.getKind()) { case clang::TemplateArgument::ArgKind::Type: if (TagDecl *tagDecl = arg.getAsType()->getAsTagDecl()) { SaveTypeDecl(tagDecl, visitedTypes); }; break; default: break; } } } // Add field types. for (FieldDecl *fieldDecl : recordDecl->fields()) { if (TagDecl *tagDecl = fieldDecl->getType()->getAsTagDecl()) { SaveTypeDecl(tagDecl, visitedTypes); } } // Add base types. if (recordDecl->getNumBases()) { for (auto &I : recordDecl->bases()) { CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); SaveTypeDecl(BaseDecl, visitedTypes); } } } } class VarReferenceVisitor : public RecursiveASTVisitor<VarReferenceVisitor> { private: SmallPtrSetImpl<VarDecl *> &m_unusedGlobals; SmallPtrSetImpl<FunctionDecl *> &m_visitedFunctions; SmallVectorImpl<FunctionDecl *> &m_pendingFunctions; SmallPtrSetImpl<TypeDecl *> &m_visitedTypes; void AddRecordType(TagDecl *tagDecl) { SaveTypeDecl(tagDecl, m_visitedTypes); } public: VarReferenceVisitor(SmallPtrSetImpl<VarDecl *> &unusedGlobals, SmallPtrSetImpl<FunctionDecl *> &visitedFunctions, SmallVectorImpl<FunctionDecl *> &pendingFunctions, SmallPtrSetImpl<TypeDecl *> &types) : m_unusedGlobals(unusedGlobals), m_visitedFunctions(visitedFunctions), m_pendingFunctions(pendingFunctions), m_visitedTypes(types) {} bool VisitDeclRefExpr(DeclRefExpr *ref) { ValueDecl *valueDecl = ref->getDecl(); if (FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(valueDecl)) { FunctionDecl *fnDeclWithbody = getFunctionWithBody(fnDecl); if (fnDeclWithbody) { if (!m_visitedFunctions.count(fnDeclWithbody)) { m_pendingFunctions.push_back(fnDeclWithbody); } } if (fnDeclWithbody && fnDeclWithbody != fnDecl) { // In case fnDecl is only a decl, setDecl to fnDeclWithbody. ref->setDecl(fnDeclWithbody); // Keep the fnDecl for now, since it might be predecl. m_visitedFunctions.insert(fnDecl); } } else if (VarDecl *varDecl = dyn_cast_or_null<VarDecl>(valueDecl)) { m_unusedGlobals.erase(varDecl); if (TagDecl *tagDecl = varDecl->getType()->getAsTagDecl()) { AddRecordType(tagDecl); } if (Expr *initExp = varDecl->getInit()) { if (InitListExpr *initList = dyn_cast<InitListExpr>(initExp)) { TraverseInitListExpr(initList); } else if (ImplicitCastExpr *initCast = dyn_cast<ImplicitCastExpr>(initExp)) { TraverseImplicitCastExpr(initCast); } else if (DeclRefExpr *initRef = dyn_cast<DeclRefExpr>(initExp)) { TraverseDeclRefExpr(initRef); } } } return true; } bool VisitMemberExpr(MemberExpr *expr) { // Save nested struct type. if (TagDecl *tagDecl = expr->getType()->getAsTagDecl()) { m_visitedTypes.insert(tagDecl); } return true; } bool VisitCXXMemberCallExpr(CXXMemberCallExpr *expr) { if (FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(expr->getCalleeDecl())) { if (!m_visitedFunctions.count(fnDecl)) { m_pendingFunctions.push_back(fnDecl); } } if (CXXRecordDecl *recordDecl = expr->getRecordDecl()) { AddRecordType(recordDecl); } return true; } bool VisitHLSLBufferDecl(HLSLBufferDecl *bufDecl) { if (!bufDecl->isCBuffer()) return false; for (Decl *decl : bufDecl->decls()) { if (VarDecl *constDecl = dyn_cast<VarDecl>(decl)) { if (TagDecl *tagDecl = constDecl->getType()->getAsTagDecl()) { AddRecordType(tagDecl); } } else if (isa<EmptyDecl>(decl)) { // Nothing to do for this declaration. } else if (CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(decl)) { m_visitedTypes.insert(recordDecl); } else if (isa<FunctionDecl>(decl)) { // A function within an cbuffer is effectively a top-level function, // as it only refers to globally scoped declarations. // Nothing to do for this declaration. } else { HLSLBufferDecl *inner = cast<HLSLBufferDecl>(decl); VisitHLSLBufferDecl(inner); } } return true; } }; // Collect all global constants. class GlobalCBVisitor : public RecursiveASTVisitor<GlobalCBVisitor> { private: SmallVectorImpl<VarDecl *> &globalConstants; public: GlobalCBVisitor(SmallVectorImpl<VarDecl *> &globals) : globalConstants(globals) {} bool VisitVarDecl(VarDecl *vd) { // Skip local var. if (!vd->getDeclContext()->isTranslationUnit()) { auto *DclContext = vd->getDeclContext(); while (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DclContext)) DclContext = ND->getDeclContext(); if (!DclContext->isTranslationUnit()) return true; } // Skip group shared. if (vd->hasAttr<HLSLGroupSharedAttr>()) return true; // Skip static global. if (!vd->hasExternalFormalLinkage()) return true; // Skip resource. if (DXIL::ResourceClass::Invalid != hlsl::GetResourceClassForType(vd->getASTContext(), vd->getType())) return true; globalConstants.emplace_back(vd); return true; } }; // Collect types used by a record decl. // TODO: template support. class TypeVisitor : public RecursiveASTVisitor<TypeVisitor> { private: MapVector<const TypeDecl *, DenseSet<const TypeDecl *>> &m_typeDepMap; public: TypeVisitor( MapVector<const TypeDecl *, DenseSet<const TypeDecl *>> &typeDepMap) : m_typeDepMap(typeDepMap) {} bool VisitRecordType(const RecordType *RT) { RecordDecl *RD = RT->getDecl(); if (m_typeDepMap.count(RD)) return true; // Create empty dep set. m_typeDepMap[RD]; if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { for (const auto &I : CXXRD->bases()) { const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); if (BaseDecl->field_empty()) continue; QualType baseTy = QualType(BaseDecl->getTypeForDecl(), 0); TraverseType(baseTy); m_typeDepMap[RD].insert(BaseDecl); } } for (auto *field : RD->fields()) { QualType Ty = field->getType(); if (hlsl::IsHLSLResourceType(Ty) || hlsl::IsHLSLNodeType(Ty) || hlsl::IsHLSLVecMatType(Ty)) continue; TraverseType(Ty); const clang::Type *TyPtr = Ty.getTypePtr(); m_typeDepMap[RD].insert(TyPtr->getAsTagDecl()); } return true; } }; // Macro related. namespace { bool MacroPairCompareIsLessThan( const std::pair<const IdentifierInfo *, const MacroInfo *> &left, const std::pair<const IdentifierInfo *, const MacroInfo *> &right) { return left.first->getName().compare(right.first->getName()) < 0; } bool ParsedSemanticDefineCompareIsLessThan(const ParsedSemanticDefine &left, const ParsedSemanticDefine &right) { return left.Name < right.Name; } ParsedSemanticDefineList CollectUserMacrosParsedByCompiler(CompilerInstance &compiler) { ParsedSemanticDefineList parsedDefines; // This is very inefficient in general, but in practice we either have // no semantic defines, or we have a star define for a some reserved prefix. // These will be sorted so rewrites are stable. std::vector<std::pair<const IdentifierInfo *, MacroInfo *>> macros; Preprocessor &pp = compiler.getPreprocessor(); Preprocessor::macro_iterator end = pp.macro_end(); SourceManager &SM = compiler.getSourceManager(); FileID PredefineFileID = pp.getPredefinesFileID(); for (Preprocessor::macro_iterator i = pp.macro_begin(); i != end; ++i) { if (!i->second.getLatest()->isDefined()) { continue; } MacroInfo *mi = i->second.getLatest()->getMacroInfo(); if (mi->getDefinitionLoc().isInvalid()) { continue; } FileID FID = SM.getFileID(mi->getDefinitionEndLoc()); if (FID == PredefineFileID) continue; const IdentifierInfo *ii = i->first; macros.push_back(std::pair<const IdentifierInfo *, MacroInfo *>(ii, mi)); } if (!macros.empty()) { std::sort(macros.begin(), macros.end(), MacroPairCompareIsLessThan); MacroExpander expander(pp); for (std::pair<const IdentifierInfo *, MacroInfo *> m : macros) { std::string expandedValue; MacroInfo *mi = m.second; if (!mi->isFunctionLike()) { expander.ExpandMacro(m.second, &expandedValue); parsedDefines.emplace_back(ParsedSemanticDefine{ m.first->getName(), expandedValue, m.second->getDefinitionLoc().getRawEncoding()}); } else { std::string macroStr; raw_string_ostream macro(macroStr); macro << m.first->getName(); auto args = mi->args(); macro << "("; for (unsigned I = 0; I != mi->getNumArgs(); ++I) { if (I) macro << ", "; macro << args[I]->getName(); } macro << ")"; macro.flush(); std::string macroValStr; raw_string_ostream macroVal(macroValStr); for (const Token &Tok : mi->tokens()) { macroVal << " "; if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind())) macroVal << Punc; else if (const char *Kwd = tok::getKeywordSpelling(Tok.getKind())) macroVal << Kwd; else if (Tok.is(tok::identifier)) macroVal << Tok.getIdentifierInfo()->getName(); else if (Tok.isLiteral() && Tok.getLiteralData()) macroVal << StringRef(Tok.getLiteralData(), Tok.getLength()); else macroVal << Tok.getName(); } macroVal.flush(); parsedDefines.emplace_back(ParsedSemanticDefine{ macroStr, macroValStr, m.second->getDefinitionLoc().getRawEncoding()}); } } } return parsedDefines; } void WriteMacroDefines(ParsedSemanticDefineList &macros, raw_string_ostream &o) { if (!macros.empty()) { o << "\n// Macros:\n"; for (auto &&m : macros) { o << "#define " << m.Name << " " << m.Value << "\n"; } } } } // namespace ParsedSemanticDefineList hlsl::CollectSemanticDefinesParsedByCompiler(CompilerInstance &compiler, DxcLangExtensionsHelper *helper) { ParsedSemanticDefineList parsedDefines; const llvm::SmallVector<std::string, 2> &defines = helper->GetSemanticDefines(); if (defines.size() == 0) { return parsedDefines; } const llvm::SmallVector<std::string, 2> &defineExclusions = helper->GetSemanticDefineExclusions(); const llvm::SetVector<std::string> &nonOptDefines = helper->GetNonOptSemanticDefines(); std::set<std::string> overridenMacroSemDef; // This is very inefficient in general, but in practice we either have // no semantic defines, or we have a star define for a some reserved prefix. // These will be sorted so rewrites are stable. std::vector<std::pair<const IdentifierInfo *, MacroInfo *>> macros; Preprocessor &pp = compiler.getPreprocessor(); Preprocessor::macro_iterator end = pp.macro_end(); for (Preprocessor::macro_iterator i = pp.macro_begin(); i != end; ++i) { if (!i->second.getLatest()->isDefined()) { continue; } MacroInfo *mi = i->second.getLatest()->getMacroInfo(); if (mi->isFunctionLike()) { continue; } const IdentifierInfo *ii = i->first; // Exclusions take precedence over inclusions. bool excluded = false; for (const auto &exclusion : defineExclusions) { if (IsMacroMatch(ii->getName(), exclusion)) { excluded = true; break; } } if (excluded) { continue; } for (const auto &define : defines) { if (!IsMacroMatch(ii->getName(), define)) { continue; } // overriding a semantic define takes the first precedence if (compiler.getCodeGenOpts().HLSLOverrideSemDefs.size() > 0 && compiler.getCodeGenOpts().HLSLOverrideSemDefs.find( ii->getName().str()) != compiler.getCodeGenOpts().HLSLOverrideSemDefs.end()) { std::string defName = ii->getName().str(); std::string defValue = compiler.getCodeGenOpts().HLSLOverrideSemDefs[defName]; overridenMacroSemDef.insert(defName); parsedDefines.emplace_back(ParsedSemanticDefine{defName, defValue, 0}); continue; } // ignoring a specific semantic define takes second precedence if (compiler.getCodeGenOpts().HLSLIgnoreSemDefs.size() > 0 && compiler.getCodeGenOpts().HLSLIgnoreSemDefs.find( ii->getName().str()) != compiler.getCodeGenOpts().HLSLIgnoreSemDefs.end()) { continue; } // ignoring all non-correctness semantic defines takes third precendence if (compiler.getCodeGenOpts().HLSLIgnoreOptSemDefs && !nonOptDefines.count(ii->getName().str())) { continue; } macros.push_back(std::pair<const IdentifierInfo *, MacroInfo *>(ii, mi)); } } // If there are semantic defines which are passed using -override-semdef flag, // but we don't have that semantic define present in source or arglist, then // we just add the semantic define. for (auto &kv : compiler.getCodeGenOpts().HLSLOverrideSemDefs) { std::string overrideDefName = kv.first; std::string overrideDefVal = kv.second; if (overridenMacroSemDef.find(overrideDefName) == overridenMacroSemDef.end()) { parsedDefines.emplace_back( ParsedSemanticDefine{overrideDefName, overrideDefVal, 0}); } } if (!macros.empty()) { MacroExpander expander(pp); for (std::pair<const IdentifierInfo *, MacroInfo *> m : macros) { std::string expandedValue; expander.ExpandMacro(m.second, &expandedValue); parsedDefines.emplace_back( ParsedSemanticDefine{m.first->getName(), expandedValue, m.second->getDefinitionLoc().getRawEncoding()}); } } std::stable_sort(parsedDefines.begin(), parsedDefines.end(), ParsedSemanticDefineCompareIsLessThan); return parsedDefines; } namespace { void SetupCompilerCommon(CompilerInstance &compiler, DxcLangExtensionsHelper *helper, LPCSTR pMainFile, TextDiagnosticPrinter *diagPrinter, ASTUnit::RemappedFile *rewrite, hlsl::options::DxcOpts &opts) { // Setup a compiler instance. std::shared_ptr<TargetOptions> targetOptions(new TargetOptions); targetOptions->Triple = llvm::sys::getDefaultTargetTriple(); compiler.HlslLangExtensions = helper; compiler.createDiagnostics(diagPrinter, false); compiler.createFileManager(); compiler.createSourceManager(compiler.getFileManager()); compiler.setTarget( TargetInfo::CreateTargetInfo(compiler.getDiagnostics(), targetOptions)); // Not use builtin includes. compiler.getHeaderSearchOpts().UseBuiltinIncludes = false; // apply compiler options applicable for rewrite if (opts.WarningAsError) compiler.getDiagnostics().setWarningsAsErrors(true); compiler.getDiagnostics().setIgnoreAllWarnings(!opts.OutputWarnings); compiler.getLangOpts().HLSLVersion = opts.HLSLVersion; compiler.getLangOpts().UseMinPrecision = !opts.Enable16BitTypes; compiler.getLangOpts().EnableDX9CompatMode = opts.EnableDX9CompatMode; compiler.getLangOpts().EnableFXCCompatMode = opts.EnableFXCCompatMode; compiler.getDiagnostics().setIgnoreAllWarnings(!opts.OutputWarnings); compiler.getCodeGenOpts().MainFileName = pMainFile; PreprocessorOptions &PPOpts = compiler.getPreprocessorOpts(); if (rewrite != nullptr) { if (llvm::MemoryBuffer *pMemBuf = rewrite->second) { compiler.getPreprocessorOpts().addRemappedFile(StringRef(pMainFile), pMemBuf); } PPOpts.RemappedFilesKeepOriginalName = true; } PPOpts.ExpandTokPastingArg = opts.LegacyMacroExpansion; // Pick additional arguments. clang::HeaderSearchOptions &HSOpts = compiler.getHeaderSearchOpts(); HSOpts.UseBuiltinIncludes = 0; // Consider: should we force-include '.' if the source file is relative? for (const llvm::opt::Arg *A : opts.Args.filtered(options::OPT_I)) { const bool IsFrameworkFalse = false; const bool IgnoreSysRoot = true; if (dxcutil::IsAbsoluteOrCurDirRelative(A->getValue())) { HSOpts.AddPath(A->getValue(), frontend::Angled, IsFrameworkFalse, IgnoreSysRoot); } else { std::string s("./"); s += A->getValue(); HSOpts.AddPath(s, frontend::Angled, IsFrameworkFalse, IgnoreSysRoot); } } } void SetupCompilerForRewrite(CompilerInstance &compiler, DxcLangExtensionsHelper *helper, LPCSTR pMainFile, TextDiagnosticPrinter *diagPrinter, ASTUnit::RemappedFile *rewrite, hlsl::options::DxcOpts &opts, LPCSTR pDefines, dxcutil::DxcArgsFileSystem *msfPtr) { SetupCompilerCommon(compiler, helper, pMainFile, diagPrinter, rewrite, opts); if (msfPtr) { msfPtr->SetupForCompilerInstance(compiler); } compiler.createPreprocessor(TU_Complete); if (pDefines) { std::string newDefines = compiler.getPreprocessor().getPredefines(); newDefines += pDefines; compiler.getPreprocessor().setPredefines(newDefines); } compiler.createASTContext(); compiler.setASTConsumer(std::unique_ptr<ASTConsumer>(new SemaConsumer())); compiler.createSema(TU_Complete, nullptr); const FileEntry *mainFileEntry = compiler.getFileManager().getFile(StringRef(pMainFile)); if (mainFileEntry == nullptr) { throw ::hlsl::Exception(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); } compiler.getSourceManager().setMainFileID( compiler.getSourceManager().createFileID(mainFileEntry, SourceLocation(), SrcMgr::C_User)); } void SetupCompilerForPreprocess(CompilerInstance &compiler, DxcLangExtensionsHelper *helper, LPCSTR pMainFile, TextDiagnosticPrinter *diagPrinter, ASTUnit::RemappedFile *rewrite, hlsl::options::DxcOpts &opts, DxcDefine *pDefines, UINT32 defineCount, dxcutil::DxcArgsFileSystem *msfPtr) { SetupCompilerCommon(compiler, helper, pMainFile, diagPrinter, rewrite, opts); if (pDefines) { PreprocessorOptions &PPOpts = compiler.getPreprocessorOpts(); for (size_t i = 0; i < defineCount; ++i) { CW2A utf8Name(pDefines[i].Name); CW2A utf8Value(pDefines[i].Value); std::string val(utf8Name.m_psz); val += "="; val += (pDefines[i].Value) ? utf8Value.m_psz : "1"; PPOpts.addMacroDef(val); } } } std::string DefinesToString(DxcDefine *pDefines, UINT32 defineCount) { std::string defineStr; for (UINT32 i = 0; i < defineCount; i++) { CW2A utf8Name(pDefines[i].Name); CW2A utf8Value(pDefines[i].Value); defineStr += "#define "; defineStr += utf8Name; defineStr += " "; defineStr += utf8Value ? utf8Value.m_psz : "1"; defineStr += "\n"; } return defineStr; } HRESULT GenerateAST(DxcLangExtensionsHelper *pExtHelper, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, DxcDefine *pDefines, UINT32 defineCount, ASTHelper &astHelper, hlsl::options::DxcOpts &opts, dxcutil::DxcArgsFileSystem *msfPtr, raw_ostream &w) { // Setup a compiler instance. CompilerInstance &compiler = astHelper.compiler; std::unique_ptr<TextDiagnosticPrinter> diagPrinter = llvm::make_unique<TextDiagnosticPrinter>(w, &compiler.getDiagnosticOpts()); std::string definesStr = DefinesToString(pDefines, defineCount); SetupCompilerForRewrite( compiler, pExtHelper, pFileName, diagPrinter.get(), pRemap, opts, defineCount > 0 ? definesStr.c_str() : nullptr, msfPtr); // Parse the source file. compiler.getDiagnosticClient().BeginSourceFile(compiler.getLangOpts(), &compiler.getPreprocessor()); ParseAST(compiler.getSema(), false, opts.RWOpt.SkipFunctionBody); ASTContext &C = compiler.getASTContext(); TranslationUnitDecl *tu = C.getTranslationUnitDecl(); astHelper.tu = tu; if (compiler.getDiagnosticClient().getNumErrors() > 0) { astHelper.bHasErrors = true; w.flush(); return E_FAIL; } astHelper.bHasErrors = false; astHelper.semanticMacros = CollectSemanticDefinesParsedByCompiler(compiler, pExtHelper); if (opts.RWOpt.KeepUserMacro) astHelper.userMacros = CollectUserMacrosParsedByCompiler(compiler); return S_OK; } HRESULT CollectRewriteHelper(TranslationUnitDecl *tu, LPCSTR pEntryPoint, RewriteHelper &helper, bool bRemoveGlobals, bool bRemoveFunctions, raw_ostream &w) { ASTContext &C = tu->getASTContext(); // Gather all global variables that are not in cbuffers and all functions. SmallPtrSet<VarDecl *, 128> &unusedGlobals = helper.unusedGlobals; DenseMap<RecordDecl *, unsigned> &anonymousRecordRefCounts = helper.anonymousRecordRefCounts; SmallPtrSet<FunctionDecl *, 128> &unusedFunctions = helper.unusedFunctions; SmallPtrSet<TypeDecl *, 32> &unusedTypes = helper.unusedTypes; SmallVector<VarDecl *, 32> nonStaticGlobals; SmallVector<HLSLBufferDecl *, 16> cbufferDecls; for (Decl *tuDecl : tu->decls()) { if (tuDecl->isImplicit()) continue; VarDecl *varDecl = dyn_cast_or_null<VarDecl>(tuDecl); if (varDecl != nullptr) { if (!bRemoveGlobals) { // Only remove static global when not remove global. if (!(varDecl->getStorageClass() == SC_Static || varDecl->isInAnonymousNamespace())) { nonStaticGlobals.emplace_back(varDecl); continue; } } unusedGlobals.insert(varDecl); if (const RecordType *recordType = varDecl->getType()->getAs<RecordType>()) { RecordDecl *recordDecl = recordType->getDecl(); if (recordDecl && recordDecl->getName().empty()) { anonymousRecordRefCounts[recordDecl]++; // Zero initialized if // non-existing } } continue; } if (HLSLBufferDecl *CB = dyn_cast<HLSLBufferDecl>(tuDecl)) { if (!CB->isCBuffer()) continue; cbufferDecls.emplace_back(CB); continue; } FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(tuDecl); if (fnDecl != nullptr) { FunctionDecl *fnDeclWithbody = getFunctionWithBody(fnDecl); // Add fnDecl without body which has a define somewhere. if (fnDecl->doesThisDeclarationHaveABody() || fnDeclWithbody) { unusedFunctions.insert(fnDecl); } } if (TagDecl *tagDecl = dyn_cast<TagDecl>(tuDecl)) { unusedTypes.insert(tagDecl); if (CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(tagDecl)) { for (CXXMethodDecl *methodDecl : recordDecl->methods()) { unusedFunctions.insert(methodDecl); } } } } w << "//found " << unusedGlobals.size() << " globals as candidates for removal\n"; w << "//found " << unusedFunctions.size() << " functions as candidates for removal\n"; DeclContext::lookup_result l = tu->lookup(DeclarationName(&C.Idents.get(StringRef(pEntryPoint)))); if (l.empty()) { w << "//entry point not found\n"; return E_FAIL; } w << "//entry point found\n"; NamedDecl *entryDecl = l.front(); FunctionDecl *entryFnDecl = dyn_cast_or_null<FunctionDecl>(entryDecl); if (entryFnDecl == nullptr) { w << "//entry point found but is not a function declaration\n"; return E_FAIL; } // Traverse reachable functions and variables. SmallPtrSet<FunctionDecl *, 128> visitedFunctions; SmallVector<FunctionDecl *, 32> pendingFunctions; SmallPtrSet<TypeDecl *, 32> visitedTypes; VarReferenceVisitor visitor(unusedGlobals, visitedFunctions, pendingFunctions, visitedTypes); pendingFunctions.push_back(entryFnDecl); while (!pendingFunctions.empty()) { FunctionDecl *pendingDecl = pendingFunctions.pop_back_val(); visitedFunctions.insert(pendingDecl); visitor.TraverseDecl(pendingDecl); } // Traverse cbuffers to save types for cbuffer constant. for (auto *CBDecl : cbufferDecls) { visitor.TraverseDecl(CBDecl); } // Don't bother doing work if there are no globals to remove. if (unusedGlobals.empty() && unusedFunctions.empty() && unusedTypes.empty()) { return S_FALSE; } w << "//found " << unusedGlobals.size() << " globals to remove\n"; // Don't remove visited functions. for (FunctionDecl *visitedFn : visitedFunctions) { unusedFunctions.erase(visitedFn); } w << "//found " << unusedFunctions.size() << " functions to remove\n"; for (VarDecl *varDecl : nonStaticGlobals) { if (TagDecl *tagDecl = varDecl->getType()->getAsTagDecl()) { SaveTypeDecl(tagDecl, visitedTypes); } } for (TypeDecl *typeDecl : visitedTypes) { unusedTypes.erase(typeDecl); } w << "//found " << unusedTypes.size() << " types to remove\n"; return S_OK; } } // namespace static HRESULT ReadOptsAndValidate(hlsl::options::MainArgs &mainArgs, hlsl::options::DxcOpts &opts, IDxcOperationResult **ppResult) { const llvm::opt::OptTable *table = ::options::getHlslOptTable(); CComPtr<AbstractMemoryStream> pOutputStream; IFT(CreateMemoryStream(GetGlobalHeapMalloc(), &pOutputStream)); raw_stream_ostream outStream(pOutputStream); if (0 != hlsl::options::ReadDxcOpts(table, hlsl::options::HlslFlags::RewriteOption, mainArgs, opts, outStream)) { CComPtr<IDxcBlob> pErrorBlob; IFT(pOutputStream->QueryInterface(&pErrorBlob)); outStream.flush(); IFT(DxcResult::Create( E_INVALIDARG, DXC_OUT_NONE, {DxcOutputObject::ErrorOutput(opts.DefaultTextCodePage, (LPCSTR)pErrorBlob->GetBufferPointer(), pErrorBlob->GetBufferSize())}, ppResult)); return S_OK; } return S_OK; } static bool HasUniformParams(FunctionDecl *FD) { for (auto PD : FD->params()) { if (PD->hasAttr<HLSLUniformAttr>()) return true; } return false; } static void WriteUniformParamsAsGlobals(FunctionDecl *FD, raw_ostream &o, PrintingPolicy &p) { // Extract resources first, to avoid placing in cbuffer _Params for (auto PD : FD->params()) { if (PD->hasAttr<HLSLUniformAttr>() && hlsl::IsHLSLResourceType(PD->getType())) { PD->print(o, p); o << ";\n"; } } // Extract any non-resource uniforms into cbuffer _Params bool startedParams = false; for (auto PD : FD->params()) { if (PD->hasAttr<HLSLUniformAttr>() && !hlsl::IsHLSLResourceType(PD->getType())) { if (!startedParams) { o << "cbuffer _Params {\n"; startedParams = true; } PD->print(o, p); o << ";\n"; } } if (startedParams) { o << "}\n"; } } static void PrintTranslationUnitWithTranslatedUniformParams( TranslationUnitDecl *tu, FunctionDecl *entryFnDecl, raw_ostream &o, PrintingPolicy &p) { // Print without the entry function entryFnDecl->setImplicit(true); // Prevent printing of this decl tu->print(o, p); entryFnDecl->setImplicit(false); WriteUniformParamsAsGlobals(entryFnDecl, o, p); PrintingPolicy SubPolicy(p); SubPolicy.HLSLSuppressUniformParameters = true; entryFnDecl->print(o, SubPolicy); } static HRESULT DoRewriteUnused(TranslationUnitDecl *tu, LPCSTR pEntryPoint, bool bRemoveGlobals, bool bRemoveFunctions, raw_ostream &w) { RewriteHelper helper; HRESULT hr = CollectRewriteHelper(tu, pEntryPoint, helper, bRemoveGlobals, bRemoveFunctions, w); if (hr != S_OK) return hr; // Remove all unused variables and functions. for (VarDecl *unusedGlobal : helper.unusedGlobals) { if (const RecordType *recordTy = unusedGlobal->getType()->getAs<RecordType>()) { RecordDecl *recordDecl = recordTy->getDecl(); if (recordDecl && recordDecl->getName().empty()) { // Anonymous structs can only be referenced by the variable they // declare. If we've removed all declared variables of such a struct, // remove it too, because anonymous structs without variable // declarations in global scope are illegal. auto recordRefCountIter = helper.anonymousRecordRefCounts.find(recordDecl); DXASSERT_NOMSG(recordRefCountIter != helper.anonymousRecordRefCounts.end() && recordRefCountIter->second > 0); recordRefCountIter->second--; if (recordRefCountIter->second == 0) { tu->removeDecl(recordDecl); helper.anonymousRecordRefCounts.erase(recordRefCountIter); } } } if (HLSLBufferDecl *CBV = dyn_cast<HLSLBufferDecl>(unusedGlobal->getLexicalDeclContext())) { if (CBV->isConstantBufferView()) { // For constant buffer view, we create a variable for the constant. // The variable use tu as the DeclContext to access as global variable, // CBV as LexicalDeclContext so it is still part of CBV. // setLexicalDeclContext to tu to avoid assert when remove. unusedGlobal->setLexicalDeclContext(tu); } } tu->removeDecl(unusedGlobal); } for (FunctionDecl *unusedFn : helper.unusedFunctions) { // remove name of function to workaround assert when update lookup table. unusedFn->setDeclName(DeclarationName()); if (CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(unusedFn)) { methodDecl->getParent()->removeDecl(unusedFn); } else { tu->removeDecl(unusedFn); } } for (TypeDecl *unusedTy : helper.unusedTypes) { tu->removeDecl(unusedTy); } // Flush and return results. w.flush(); return S_OK; } static HRESULT DoRewriteUnused(DxcLangExtensionsHelper *pHelper, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, LPCSTR pEntryPoint, DxcDefine *pDefines, UINT32 defineCount, bool bRemoveGlobals, bool bRemoveFunctions, std::string &warnings, std::string &result, dxcutil::DxcArgsFileSystem *msfPtr) { raw_string_ostream o(result); raw_string_ostream w(warnings); ASTHelper astHelper; hlsl::options::DxcOpts opts; opts.HLSLVersion = hlsl::LangStd::v2015; GenerateAST(pHelper, pFileName, pRemap, pDefines, defineCount, astHelper, opts, msfPtr, w); if (astHelper.bHasErrors) return E_FAIL; TranslationUnitDecl *tu = astHelper.tu; HRESULT hr = DoRewriteUnused(tu, pEntryPoint, bRemoveGlobals, bRemoveFunctions, w); if (FAILED(hr)) return hr; ASTContext &C = tu->getASTContext(); if (hr == S_FALSE) { w << "//no unused globals found - no work to be done\n"; StringRef contents = C.getSourceManager().getBufferData( C.getSourceManager().getMainFileID()); o << contents; } else { PrintingPolicy p = PrintingPolicy(C.getPrintingPolicy()); p.Indentation = 1; tu->print(o, p); } WriteMacroDefines(astHelper.semanticMacros, o); // Flush and return results. o.flush(); w.flush(); return S_OK; } static void RemoveStaticDecls(DeclContext &Ctx) { for (auto it = Ctx.decls_begin(); it != Ctx.decls_end();) { auto cur = it++; if (VarDecl *VD = dyn_cast<VarDecl>(*cur)) { if (VD->getStorageClass() == SC_Static || VD->isInAnonymousNamespace()) { Ctx.removeDecl(VD); } } if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*cur)) { if (isa<CXXMethodDecl>(FD)) continue; if (FD->getStorageClass() == SC_Static || FD->isInAnonymousNamespace()) { Ctx.removeDecl(FD); } } if (DeclContext *DC = dyn_cast<DeclContext>(*cur)) { RemoveStaticDecls(*DC); } } } static void GlobalVariableAsExternByDefault(DeclContext &Ctx) { for (auto it = Ctx.decls_begin(); it != Ctx.decls_end();) { auto cur = it++; if (VarDecl *VD = dyn_cast<VarDecl>(*cur)) { bool isInternal = VD->getStorageClass() == SC_Static || VD->isInAnonymousNamespace(); if (!isInternal) { VD->setStorageClass(StorageClass::SC_Extern); } } // Only iterate on namespaces. if (NamespaceDecl *DC = dyn_cast<NamespaceDecl>(*cur)) { GlobalVariableAsExternByDefault(*DC); } } } static HRESULT DoSimpleReWrite(DxcLangExtensionsHelper *pHelper, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, hlsl::options::DxcOpts &opts, DxcDefine *pDefines, UINT32 defineCount, std::string &warnings, std::string &result, dxcutil::DxcArgsFileSystem *msfPtr) { raw_string_ostream o(result); raw_string_ostream w(warnings); ASTHelper astHelper; GenerateAST(pHelper, pFileName, pRemap, pDefines, defineCount, astHelper, opts, msfPtr, w); TranslationUnitDecl *tu = astHelper.tu; if (opts.RWOpt.SkipStatic && opts.RWOpt.SkipFunctionBody) { // Remove static functions and globals. RemoveStaticDecls(*tu); } if (opts.RWOpt.GlobalExternByDefault) { GlobalVariableAsExternByDefault(*tu); } if (opts.EntryPoint.empty()) opts.EntryPoint = "main"; if (opts.RWOpt.RemoveUnusedGlobals || opts.RWOpt.RemoveUnusedFunctions) { HRESULT hr = DoRewriteUnused(tu, opts.EntryPoint.data(), opts.RWOpt.RemoveUnusedGlobals, opts.RWOpt.RemoveUnusedFunctions, w); if (FAILED(hr)) return hr; } else { o << "// Rewrite unchanged result:\n"; } ASTContext &C = tu->getASTContext(); FunctionDecl *entryFnDecl = nullptr; if (opts.RWOpt.ExtractEntryUniforms) { DeclContext::lookup_result l = tu->lookup(DeclarationName(&C.Idents.get(opts.EntryPoint))); if (l.empty()) { w << "//entry point not found\n"; return E_FAIL; } entryFnDecl = dyn_cast_or_null<FunctionDecl>(l.front()); if (!HasUniformParams(entryFnDecl)) entryFnDecl = nullptr; } PrintingPolicy p = PrintingPolicy(C.getPrintingPolicy()); p.HLSLOmitDefaultTemplateParams = 1; p.Indentation = 1; if (entryFnDecl) { PrintTranslationUnitWithTranslatedUniformParams(tu, entryFnDecl, o, p); } else { tu->print(o, p); } WriteMacroDefines(astHelper.semanticMacros, o); if (opts.RWOpt.KeepUserMacro) WriteMacroDefines(astHelper.userMacros, o); // Flush and return results. o.flush(); w.flush(); if (astHelper.bHasErrors) return E_FAIL; return S_OK; } namespace { void PreprocessResult(CompilerInstance &compiler, LPCSTR pFileName) { // These settings are back-compatible with fxc. clang::PreprocessorOutputOptions &PPOutOpts = compiler.getPreprocessorOutputOpts(); PPOutOpts.ShowCPP = 1; // Print normal preprocessed output. PPOutOpts.ShowComments = 0; // Show comments. PPOutOpts.ShowLineMarkers = 1; // Show \#line markers. PPOutOpts.UseLineDirectives = 1; // Use \#line instead of GCC-style \# N. PPOutOpts.ShowMacroComments = 0; // Show comments, even in macros. PPOutOpts.ShowMacros = 0; // Print macro definitions. PPOutOpts.RewriteIncludes = 0; // Preprocess include directives only. FrontendInputFile file(pFileName, IK_HLSL); clang::PrintPreprocessedAction action; if (action.BeginSourceFile(compiler, file)) { action.Execute(); action.EndSourceFile(); } } class RewriteVisitor : public RecursiveASTVisitor<RewriteVisitor> { public: RewriteVisitor(Rewriter &R, TranslationUnitDecl *tu, RewriteHelper &helper) : TheRewriter(R), SourceMgr(R.getSourceMgr()), tu(tu), helper(helper), bNeedLineInfo(false) {} bool VisitFunctionDecl(FunctionDecl *f) { if (helper.unusedFunctions.count(f)) { bNeedLineInfo = true; TheRewriter.RemoveText(f->getSourceRange()); return true; } AddLineInfoIfNeed(f->getLocStart()); return true; } bool VisitTypeDecl(TypeDecl *t) { if (helper.unusedTypes.count(t)) { bNeedLineInfo = true; TheRewriter.RemoveText(t->getSourceRange()); return true; } AddLineInfoIfNeed(t->getLocStart()); return true; } bool VisitVarDecl(VarDecl *vd) { if (vd->getDeclContext() == tu) { if (helper.unusedGlobals.count(vd)) { bNeedLineInfo = true; TheRewriter.RemoveText(vd->getSourceRange()); return true; } AddLineInfoIfNeed(vd->getLocStart()); } return true; } private: void AddLineInfoIfNeed(SourceLocation Loc) { if (bNeedLineInfo) { bNeedLineInfo = false; auto lineStr = MakeLineInfo(Loc); TheRewriter.InsertTextBefore(Loc, lineStr); } } std::string MakeLineInfo(SourceLocation Loc) { if (Loc.isInvalid()) return ""; if (!Loc.isFileID()) return ""; PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); const char *Filename = PLoc.getFilename(); int Line = PLoc.getLine(); std::string lineStr; raw_string_ostream o(lineStr); o << "#line" << ' ' << Line << ' ' << '"'; o.write_escaped(Filename); o << '"' << '\n'; o.flush(); return lineStr; } private: Rewriter &TheRewriter; SourceManager &SourceMgr; TranslationUnitDecl *tu; RewriteHelper &helper; bool bNeedLineInfo; }; // Preprocess rewritten files. HRESULT preprocessRewrittenFiles(DxcLangExtensionsHelper *pExtHelper, Rewriter &R, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, hlsl::options::DxcOpts &opts, DxcDefine *pDefines, UINT32 defineCount, raw_string_ostream &w, raw_string_ostream &o, dxcutil::DxcArgsFileSystem *msfPtr, IMalloc *pMalloc) { CComPtr<AbstractMemoryStream> pOutputStream; IFT(CreateMemoryStream(pMalloc, &pOutputStream)); raw_stream_ostream outStream(pOutputStream.p); // TODO: how to reuse msfPtr when ReigsterOutputStream. IFT(msfPtr->RegisterOutputStream(L"output.bc", pOutputStream)); llvm::MemoryBuffer *pMemBuf = pRemap->second; std::unique_ptr<llvm::MemoryBuffer> pBuffer( llvm::MemoryBuffer::getMemBufferCopy(pMemBuf->getBuffer(), pFileName)); std::unique_ptr<ASTUnit::RemappedFile> pPreprocessRemap( new ASTUnit::RemappedFile(pFileName, pBuffer.release())); // Need another compiler instance for preprocess because // PrintPreprocessedAction will createPreprocessor. CompilerInstance compiler; std::unique_ptr<TextDiagnosticPrinter> diagPrinter = llvm::make_unique<TextDiagnosticPrinter>(w, &compiler.getDiagnosticOpts()); SetupCompilerForPreprocess(compiler, pExtHelper, pFileName, diagPrinter.get(), pPreprocessRemap.get(), opts, pDefines, defineCount, msfPtr); auto &sourceManager = R.getSourceMgr(); auto &preprocessorOpts = compiler.getPreprocessorOpts(); // Map rewrite buf to source manager of preprocessor compiler. for (auto it = R.buffer_begin(); it != R.buffer_end(); it++) { RewriteBuffer &buf = it->second; const FileEntry *Entry = sourceManager.getFileEntryForID(it->first); std::string lineStr; raw_string_ostream o(lineStr); buf.write(o); o.flush(); StringRef fileName = Entry->getName(); std::unique_ptr<llvm::MemoryBuffer> rewriteBuf = MemoryBuffer::getMemBufferCopy(lineStr, fileName); preprocessorOpts.addRemappedFile(fileName, rewriteBuf.release()); } compiler.getFrontendOpts().OutputFile = "output.bc"; compiler.WriteDefaultOutputDirectly = true; compiler.setOutStream(&outStream); try { PreprocessResult(compiler, pFileName); StringRef out((char *)pOutputStream.p->GetPtr(), pOutputStream.p->GetPtrSize()); o << out; compiler.setSourceManager(nullptr); msfPtr->UnRegisterOutputStream(); } catch (Exception &exp) { w << exp.msg; return E_FAIL; } catch (...) { return E_FAIL; } return S_OK; } HRESULT DoReWriteWithLineDirective( DxcLangExtensionsHelper *pExtHelper, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, hlsl::options::DxcOpts &opts, DxcDefine *pDefines, UINT32 defineCount, std::string &warnings, std::string &result, dxcutil::DxcArgsFileSystem *msfPtr, IMalloc *pMalloc) { raw_string_ostream o(result); raw_string_ostream w(warnings); Rewriter rewriter; RewriteHelper rwHelper; ASTHelper astHelper; // Generate AST and rewrite the file. { GenerateAST(pExtHelper, pFileName, pRemap, pDefines, defineCount, astHelper, opts, msfPtr, w); TranslationUnitDecl *tu = astHelper.tu; if (opts.EntryPoint.empty()) opts.EntryPoint = "main"; ASTContext &C = tu->getASTContext(); rewriter.setSourceMgr(C.getSourceManager(), C.getLangOpts()); if (opts.RWOpt.RemoveUnusedGlobals || opts.RWOpt.RemoveUnusedFunctions) { HRESULT hr = CollectRewriteHelper(tu, opts.EntryPoint.data(), rwHelper, opts.RWOpt.RemoveUnusedGlobals, opts.RWOpt.RemoveUnusedFunctions, w); if (hr == E_FAIL) return hr; RewriteVisitor visitor(rewriter, tu, rwHelper); visitor.TraverseDecl(tu); } // TODO: support ExtractEntryUniforms, GlobalExternByDefault, SkipStatic, // SkipFunctionBody. if (opts.RWOpt.ExtractEntryUniforms || opts.RWOpt.GlobalExternByDefault || opts.RWOpt.SkipStatic || opts.RWOpt.SkipFunctionBody) { w << "-extract-entry-uniforms, -global-extern-by-default,-skip-static, " "-skip-fn-body are not supported yet when -line-directive is " "enabled"; w.flush(); return E_FAIL; } if (astHelper.bHasErrors) { o.flush(); w.flush(); return E_FAIL; } } // Preprocess rewritten files. preprocessRewrittenFiles(pExtHelper, rewriter, pFileName, pRemap, opts, pDefines, defineCount, w, o, msfPtr, pMalloc); WriteMacroDefines(astHelper.semanticMacros, o); if (opts.RWOpt.KeepUserMacro) WriteMacroDefines(astHelper.userMacros, o); // Flush and return results. o.flush(); w.flush(); return S_OK; } template <typename DT> void printWithNamespace(DT *VD, raw_string_ostream &OS, PrintingPolicy &p) { SmallVector<StringRef, 2> namespaceList; auto const *Context = VD->getDeclContext(); while (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Context)) { namespaceList.emplace_back(ND->getName()); Context = ND->getDeclContext(); } for (auto it = namespaceList.rbegin(); it != namespaceList.rend(); ++it) { OS << "namespace " << *it << " {\n"; } VD->print(OS, p); OS << ";\n"; for (unsigned i = 0; i < namespaceList.size(); ++i) { OS << "}\n"; } } void printTypeWithoutMethodBody(const TypeDecl *TD, raw_string_ostream &OS, PrintingPolicy &p) { PrintingPolicy declP(p); declP.HLSLOnlyDecl = true; printWithNamespace(TD, OS, declP); } class MethodsVisitor : public DeclVisitor<MethodsVisitor> { public: MethodsVisitor(raw_string_ostream &o, PrintingPolicy &p) : OS(o), declP(p) { declP.HLSLNoinlineMethod = true; } void VisitFunctionDecl(FunctionDecl *f) { // Don't need to do namespace, the location is not change. f->print(OS, declP); return; } void VisitDeclContext(DeclContext *DC) { SmallVector<Decl *, 2> Decls; for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); D != DEnd; ++D) { // Don't print ObjCIvarDecls, as they are printed when visiting the // containing ObjCInterfaceDecl. if (isa<ObjCIvarDecl>(*D)) continue; // Skip over implicit declarations in pretty-printing mode. if (D->isImplicit()) continue; Visit(*D); } } void VisitCXXRecordDecl(CXXRecordDecl *D) { if (D->isCompleteDefinition()) { VisitDeclContext(D); } } private: raw_string_ostream &OS; PrintingPolicy declP; }; HRESULT DoRewriteGlobalCB(DxcLangExtensionsHelper *pExtHelper, LPCSTR pFileName, ASTUnit::RemappedFile *pRemap, hlsl::options::DxcOpts &opts, DxcDefine *pDefines, UINT32 defineCount, std::string &warnings, std::string &result, dxcutil::DxcArgsFileSystem *msfPtr, IMalloc *pMalloc) { raw_string_ostream o(result); raw_string_ostream w(warnings); ASTHelper astHelper; GenerateAST(pExtHelper, pFileName, pRemap, pDefines, defineCount, astHelper, opts, msfPtr, w); if (astHelper.bHasErrors) return E_FAIL; TranslationUnitDecl *tu = astHelper.tu; // Collect global constants. SmallVector<VarDecl *, 128> globalConstants; GlobalCBVisitor visitor(globalConstants); visitor.TraverseDecl(tu); // Collect types for global constants. MapVector<const TypeDecl *, DenseSet<const TypeDecl *>> typeDepMap; TypeVisitor tyVisitor(typeDepMap); for (VarDecl *VD : globalConstants) { QualType Type = VD->getType(); tyVisitor.TraverseType(Type); } ASTContext &C = tu->getASTContext(); Rewriter R(C.getSourceManager(), C.getLangOpts()); std::string globalCBStr; raw_string_ostream OS(globalCBStr); PrintingPolicy p = PrintingPolicy(C.getPrintingPolicy()); // Sort types with typeDepMap. SmallVector<const TypeDecl *, 32> sortedGlobalConstantTypes; while (!typeDepMap.empty()) { SmallSet<const TypeDecl *, 4> noDepTypes; for (auto it : typeDepMap) { const TypeDecl *TD = it.first; auto &dep = it.second; if (dep.empty()) { sortedGlobalConstantTypes.emplace_back(TD); noDepTypes.insert(TD); } else { for (auto *depDecl : dep) { if (typeDepMap.count(depDecl) == 0) { noDepTypes.insert(depDecl); } } for (auto *noDepDecl : noDepTypes) { if (dep.count(noDepDecl)) dep.erase(noDepDecl); } if (dep.empty()) { sortedGlobalConstantTypes.emplace_back(TD); noDepTypes.insert(TD); } } } for (auto *noDepDecl : noDepTypes) typeDepMap.erase(noDepDecl); } // Move all type decl to top of tu. for (const TypeDecl *TD : sortedGlobalConstantTypes) { printTypeWithoutMethodBody(TD, OS, p); std::string methodsStr; raw_string_ostream methodsOS(methodsStr); MethodsVisitor Visitor(methodsOS, p); Visitor.Visit(const_cast<TypeDecl *>(TD)); methodsOS.flush(); R.ReplaceText(TD->getSourceRange(), methodsStr); // TODO: remove ; for type decl. } OS << "cbuffer GlobalCB {\n"; // Create HLSLBufferDecl after the types. for (VarDecl *VD : globalConstants) { printWithNamespace(VD, OS, p); R.RemoveText(VD->getSourceRange()); // TODO: remove ; for var decl. } OS << "}\n"; OS.flush(); // Cannot find begin of tu, just write first when output. // R.InsertTextBefore(tu->decls_begin()->getLocation(), globalCBStr); o << globalCBStr; // Preprocess rewritten files. preprocessRewrittenFiles(pExtHelper, R, pFileName, pRemap, opts, pDefines, defineCount, w, o, msfPtr, pMalloc); WriteMacroDefines(astHelper.semanticMacros, o); if (opts.RWOpt.KeepUserMacro) WriteMacroDefines(astHelper.userMacros, o); // Flush and return results. o.flush(); w.flush(); return S_OK; } } // namespace class DxcRewriter : public IDxcRewriter2, public IDxcLangExtensions3 { private: DXC_MICROCOM_TM_REF_FIELDS() DxcLangExtensionsHelper m_langExtensionsHelper; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_CTOR(DxcRewriter) DXC_LANGEXTENSIONS_HELPER_IMPL(m_langExtensionsHelper) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcRewriter2, IDxcRewriter, IDxcLangExtensions, IDxcLangExtensions2, IDxcLangExtensions3>(this, iid, ppvObject); } HRESULT STDMETHODCALLTYPE RemoveUnusedGlobals( IDxcBlobEncoding *pSource, LPCWSTR pEntryPoint, DxcDefine *pDefines, UINT32 defineCount, IDxcOperationResult **ppResult) override { if (pSource == nullptr || ppResult == nullptr || (defineCount > 0 && pDefines == nullptr)) return E_INVALIDARG; *ppResult = nullptr; DxcThreadMalloc TM(m_pMalloc); CComPtr<IDxcBlobUtf8> utf8Source; IFR(hlsl::DxcGetBlobAsUtf8(pSource, m_pMalloc, &utf8Source)); LPCSTR fakeName = "input.hlsl"; try { ::llvm::sys::fs::MSFileSystem *msfPtr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); StringRef Data(utf8Source->GetStringPointer(), utf8Source->GetStringLength()); std::unique_ptr<llvm::MemoryBuffer> pBuffer( llvm::MemoryBuffer::getMemBufferCopy(Data, fakeName)); std::unique_ptr<ASTUnit::RemappedFile> pRemap( new ASTUnit::RemappedFile(fakeName, pBuffer.release())); CW2A utf8EntryPoint(pEntryPoint); std::string errors; std::string rewrite; LPCWSTR pOutputName = nullptr; // TODO: Fill this in HRESULT status = DoRewriteUnused( &m_langExtensionsHelper, fakeName, pRemap.get(), utf8EntryPoint, pDefines, defineCount, true /*removeGlobals*/, false /*removeFunctions*/, errors, rewrite, nullptr); return DxcResult::Create( status, DXC_OUT_HLSL, {DxcOutputObject::StringOutput( DXC_OUT_HLSL, CP_UTF8, // TODO: Support DefaultTextCodePage rewrite.c_str(), pOutputName), DxcOutputObject::ErrorOutput( CP_UTF8, // TODO Support DefaultTextCodePage errors.c_str())}, ppResult); } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE RewriteUnchanged( IDxcBlobEncoding *pSource, DxcDefine *pDefines, UINT32 defineCount, IDxcOperationResult **ppResult) override { if (pSource == nullptr || ppResult == nullptr || (defineCount > 0 && pDefines == nullptr)) return E_POINTER; *ppResult = nullptr; DxcThreadMalloc TM(m_pMalloc); CComPtr<IDxcBlobUtf8> utf8Source; IFR(hlsl::DxcGetBlobAsUtf8(pSource, m_pMalloc, &utf8Source)); LPCSTR fakeName = "input.hlsl"; try { ::llvm::sys::fs::MSFileSystem *msfPtr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); StringRef Data(utf8Source->GetStringPointer(), utf8Source->GetStringLength()); std::unique_ptr<llvm::MemoryBuffer> pBuffer( llvm::MemoryBuffer::getMemBufferCopy(Data, fakeName)); std::unique_ptr<ASTUnit::RemappedFile> pRemap( new ASTUnit::RemappedFile(fakeName, pBuffer.release())); hlsl::options::DxcOpts opts; opts.HLSLVersion = hlsl::LangStd::v2015; std::string errors; std::string rewrite; HRESULT status = DoSimpleReWrite(&m_langExtensionsHelper, fakeName, pRemap.get(), opts, pDefines, defineCount, errors, rewrite, nullptr); return DxcResult::Create( status, DXC_OUT_HLSL, {DxcOutputObject::StringOutput(DXC_OUT_HLSL, opts.DefaultTextCodePage, rewrite.c_str(), DxcOutNoName), DxcOutputObject::ErrorOutput(opts.DefaultTextCodePage, errors.c_str())}, ppResult); } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE RewriteUnchangedWithInclude( IDxcBlobEncoding *pSource, // Optional file name for pSource. Used in errors and include handlers. LPCWSTR pSourceName, DxcDefine *pDefines, UINT32 defineCount, // user-provided interface to handle #include directives (optional) IDxcIncludeHandler *pIncludeHandler, UINT32 rewriteOption, IDxcOperationResult **ppResult) override { if (pSource == nullptr || ppResult == nullptr || (defineCount > 0 && pDefines == nullptr)) return E_POINTER; *ppResult = nullptr; DxcThreadMalloc TM(m_pMalloc); CComPtr<IDxcBlobUtf8> utf8Source; IFR(hlsl::DxcGetBlobAsUtf8(pSource, m_pMalloc, &utf8Source)); CW2A utf8SourceName(pSourceName); LPCSTR fName = utf8SourceName.m_psz; try { dxcutil::DxcArgsFileSystem *msfPtr = dxcutil::CreateDxcArgsFileSystem( utf8Source, pSourceName, pIncludeHandler); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); StringRef Data(utf8Source->GetStringPointer(), utf8Source->GetStringLength()); std::unique_ptr<llvm::MemoryBuffer> pBuffer( llvm::MemoryBuffer::getMemBufferCopy(Data, fName)); std::unique_ptr<ASTUnit::RemappedFile> pRemap( new ASTUnit::RemappedFile(fName, pBuffer.release())); hlsl::options::DxcOpts opts; opts.HLSLVersion = hlsl::LangStd::v2015; opts.RWOpt.SkipFunctionBody |= rewriteOption & RewriterOptionMask::SkipFunctionBody; opts.RWOpt.SkipStatic |= rewriteOption & RewriterOptionMask::SkipStatic; opts.RWOpt.GlobalExternByDefault |= rewriteOption & RewriterOptionMask::GlobalExternByDefault; opts.RWOpt.KeepUserMacro |= rewriteOption & RewriterOptionMask::KeepUserMacro; std::string errors; std::string rewrite; HRESULT status = DoSimpleReWrite(&m_langExtensionsHelper, fName, pRemap.get(), opts, pDefines, defineCount, errors, rewrite, msfPtr); return DxcResult::Create( status, DXC_OUT_HLSL, {DxcOutputObject::StringOutput(DXC_OUT_HLSL, opts.DefaultTextCodePage, rewrite.c_str(), DxcOutNoName), DxcOutputObject::ErrorOutput(opts.DefaultTextCodePage, errors.c_str())}, ppResult); } CATCH_CPP_RETURN_HRESULT(); } HRESULT STDMETHODCALLTYPE RewriteWithOptions( IDxcBlobEncoding *pSource, // Optional file name for pSource. Used in errors and include handlers. LPCWSTR pSourceName, // Compiler arguments LPCWSTR *pArguments, UINT32 argCount, // Defines DxcDefine *pDefines, UINT32 defineCount, // user-provided interface to handle #include directives (optional) IDxcIncludeHandler *pIncludeHandler, IDxcOperationResult **ppResult) override { if (pSource == nullptr || ppResult == nullptr || (argCount > 0 && pArguments == nullptr) || (defineCount > 0 && pDefines == nullptr)) return E_POINTER; *ppResult = nullptr; DxcThreadMalloc TM(m_pMalloc); CComPtr<IDxcBlobUtf8> utf8Source; IFR(hlsl::DxcGetBlobAsUtf8(pSource, m_pMalloc, &utf8Source)); CW2A utf8SourceName(pSourceName); LPCSTR fName = utf8SourceName.m_psz; try { dxcutil::DxcArgsFileSystem *msfPtr = dxcutil::CreateDxcArgsFileSystem( utf8Source, pSourceName, pIncludeHandler); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); hlsl::options::MainArgs mainArgs(argCount, pArguments, 0); hlsl::options::DxcOpts opts; IFR(ReadOptsAndValidate(mainArgs, opts, ppResult)); HRESULT hr; if (*ppResult && SUCCEEDED((*ppResult)->GetStatus(&hr)) && FAILED(hr)) { // Looks odd, but this call succeeded enough to allocate a result return S_OK; } StringRef Data(utf8Source->GetStringPointer(), utf8Source->GetStringLength()); std::unique_ptr<llvm::MemoryBuffer> pBuffer( llvm::MemoryBuffer::getMemBufferCopy(Data, fName)); std::unique_ptr<ASTUnit::RemappedFile> pRemap( new ASTUnit::RemappedFile(fName, pBuffer.release())); if (opts.RWOpt.DeclGlobalCB) { std::string errors; std::string rewrite; HRESULT status = S_OK; status = DoRewriteGlobalCB(&m_langExtensionsHelper, fName, pRemap.get(), opts, pDefines, defineCount, errors, rewrite, msfPtr, m_pMalloc); if (status != S_OK) { return S_OK; } pBuffer = llvm::MemoryBuffer::getMemBufferCopy(rewrite, fName); pRemap.reset(new ASTUnit::RemappedFile(fName, pBuffer.release())); } std::string errors; std::string rewrite; HRESULT status = S_OK; if (opts.RWOpt.WithLineDirective) { status = DoReWriteWithLineDirective( &m_langExtensionsHelper, fName, pRemap.get(), opts, pDefines, defineCount, errors, rewrite, msfPtr, m_pMalloc); } else { status = DoSimpleReWrite(&m_langExtensionsHelper, fName, pRemap.get(), opts, pDefines, defineCount, errors, rewrite, msfPtr); } return DxcResult::Create( status, DXC_OUT_HLSL, {DxcOutputObject::StringOutput(DXC_OUT_HLSL, opts.DefaultTextCodePage, rewrite.c_str(), DxcOutNoName), DxcOutputObject::ErrorOutput(opts.DefaultTextCodePage, errors.c_str())}, ppResult); } CATCH_CPP_RETURN_HRESULT(); } }; HRESULT CreateDxcRewriter(REFIID riid, LPVOID *ppv) { CComPtr<DxcRewriter> isense = DxcRewriter::Alloc(DxcGetThreadMallocNoRef()); IFROOM(isense.p); return isense.p->QueryInterface(riid, ppv); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXStoredDiagnostic.cpp
/*===-- CXStoreDiagnostic.cpp - Diagnostics C Interface ----------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Implements part of the diagnostic functions of the Clang C interface. *| |* *| \*===----------------------------------------------------------------------===*/ #include "CIndexDiagnostic.h" #include "CIndexer.h" #include "CXTranslationUnit.h" #include "CXSourceLocation.h" #include "CXString.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::cxloc; CXDiagnosticSeverity CXStoredDiagnostic::getSeverity() const { switch (Diag.getLevel()) { case DiagnosticsEngine::Ignored: return CXDiagnostic_Ignored; case DiagnosticsEngine::Note: return CXDiagnostic_Note; case DiagnosticsEngine::Remark: // The 'Remark' level isn't represented in the stable API. case DiagnosticsEngine::Warning: return CXDiagnostic_Warning; case DiagnosticsEngine::Error: return CXDiagnostic_Error; case DiagnosticsEngine::Fatal: return CXDiagnostic_Fatal; } llvm_unreachable("Invalid diagnostic level"); } CXSourceLocation CXStoredDiagnostic::getLocation() const { if (Diag.getLocation().isInvalid()) return clang_getNullLocation(); return translateSourceLocation(Diag.getLocation().getManager(), LangOpts, Diag.getLocation()); } CXString CXStoredDiagnostic::getSpelling() const { return cxstring::createRef(Diag.getMessage()); } CXString CXStoredDiagnostic::getDiagnosticOption(CXString *Disable) const { unsigned ID = Diag.getID(); StringRef Option = DiagnosticIDs::getWarningOptionForDiag(ID); if (!Option.empty()) { if (Disable) *Disable = cxstring::createDup((Twine("-Wno-") + Option).str()); return cxstring::createDup((Twine("-W") + Option).str()); } if (ID == diag::fatal_too_many_errors) { if (Disable) *Disable = cxstring::createRef("-ferror-limit=0"); return cxstring::createRef("-ferror-limit="); } return cxstring::createEmpty(); } unsigned CXStoredDiagnostic::getCategory() const { return DiagnosticIDs::getCategoryNumberForDiag(Diag.getID()); } CXString CXStoredDiagnostic::getCategoryText() const { unsigned catID = DiagnosticIDs::getCategoryNumberForDiag(Diag.getID()); return cxstring::createRef(DiagnosticIDs::getCategoryNameFromID(catID)); } unsigned CXStoredDiagnostic::getNumRanges() const { if (Diag.getLocation().isInvalid()) return 0; return Diag.range_size(); } CXSourceRange CXStoredDiagnostic::getRange(unsigned int Range) const { assert(Diag.getLocation().isValid()); return translateSourceRange(Diag.getLocation().getManager(), LangOpts, Diag.range_begin()[Range]); } unsigned CXStoredDiagnostic::getNumFixIts() const { if (Diag.getLocation().isInvalid()) return 0; return Diag.fixit_size(); } CXString CXStoredDiagnostic::getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const { const FixItHint &Hint = Diag.fixit_begin()[FixIt]; if (ReplacementRange) { // Create a range that covers the entire replacement (or // removal) range, adjusting the end of the range to point to // the end of the token. *ReplacementRange = translateSourceRange(Diag.getLocation().getManager(), LangOpts, Hint.RemoveRange); } return cxstring::createDup(Hint.CodeToInsert); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CLog.h
//===- CLog.h - Logging Interface -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CLOG_H #define LLVM_CLANG_TOOLS_LIBCLANG_CLOG_H #include "clang-c/Index.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include <string> namespace llvm { class format_object_base; } namespace clang { class FileEntry; namespace cxindex { class Logger; typedef IntrusiveRefCntPtr<Logger> LogRef; /// \brief Collects logging output and writes it to stderr when it's destructed. /// Common use case: /// \code /// if (LogRef Log = Logger::make(__func__)) { /// *Log << "stuff"; /// } /// \endcode class Logger : public RefCountedBase<Logger> { std::string Name; bool Trace; SmallString<64> Msg; llvm::raw_svector_ostream LogOS; public: static const char *getEnvVar() { static const char *sCachedVar = ::getenv("LIBCLANG_LOGGING"); return sCachedVar; } static bool isLoggingEnabled() { return getEnvVar() != nullptr; } static bool isStackTracingEnabled() { if (const char *EnvOpt = Logger::getEnvVar()) return llvm::StringRef(EnvOpt) == "2"; return false; } static LogRef make(llvm::StringRef name, bool trace = isStackTracingEnabled()) { if (isLoggingEnabled()) return new Logger(name, trace); return nullptr; } explicit Logger(llvm::StringRef name, bool trace) : Name(name), Trace(trace), LogOS(Msg) { } ~Logger(); Logger &operator<<(CXTranslationUnit); Logger &operator<<(const FileEntry *FE); Logger &operator<<(CXCursor cursor); Logger &operator<<(CXSourceLocation); Logger &operator<<(CXSourceRange); Logger &operator<<(CXString); Logger &operator<<(llvm::StringRef Str) { LogOS << Str; return *this; } Logger &operator<<(const char *Str) { if (Str) LogOS << Str; return *this; } Logger &operator<<(unsigned long N) { LogOS << N; return *this; } Logger &operator<<(long N) { LogOS << N ; return *this; } Logger &operator<<(unsigned int N) { LogOS << N; return *this; } Logger &operator<<(int N) { LogOS << N; return *this; } Logger &operator<<(char C) { LogOS << C; return *this; } Logger &operator<<(unsigned char C) { LogOS << C; return *this; } Logger &operator<<(signed char C) { LogOS << C; return *this; } Logger &operator<<(const llvm::format_object_base &Fmt); }; } } /// \brief Macros to automate common uses of Logger. Like this: /// \code /// LOG_FUNC_SECTION { /// *Log << "blah"; /// } /// \endcode #define LOG_SECTION(NAME) \ if (clang::cxindex::LogRef Log = clang::cxindex::Logger::make(NAME)) #define LOG_FUNC_SECTION LOG_SECTION(LLVM_FUNCTION_NAME) #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXCursor.h
//===- CXCursor.h - Routines for manipulating CXCursors -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXCursors. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXCURSOR_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXCURSOR_H #include "clang-c/Index.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/PointerUnion.h" #include <utility> namespace clang { class ASTContext; class ASTUnit; class Attr; class CXXBaseSpecifier; class Decl; class Expr; class FieldDecl; class InclusionDirective; class LabelStmt; class MacroDefinitionRecord; class MacroExpansion; class NamedDecl; class ObjCInterfaceDecl; class ObjCProtocolDecl; class OverloadedTemplateStorage; class OverloadExpr; class Stmt; class TemplateDecl; class TemplateName; class TypeDecl; class VarDecl; class IdentifierInfo; namespace cxcursor { CXCursor getCursor(CXTranslationUnit, SourceLocation); CXCursor MakeCXCursor(const clang::Attr *A, const clang::Decl *Parent, CXTranslationUnit TU); CXCursor MakeCXCursor(const clang::Decl *D, CXTranslationUnit TU, SourceRange RegionOfInterest = SourceRange(), bool FirstInDeclGroup = true); CXCursor MakeCXCursor(const clang::Stmt *S, const clang::Decl *Parent, CXTranslationUnit TU, SourceRange RegionOfInterest = SourceRange()); CXCursor MakeCXCursorInvalid(CXCursorKind K, CXTranslationUnit TU = nullptr); /// \brief Create an Objective-C superclass reference at the given location. CXCursor MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack an ObjCSuperClassRef cursor into the interface it references /// and optionally the location where the reference occurred. std::pair<const ObjCInterfaceDecl *, SourceLocation> getCursorObjCSuperClassRef(CXCursor C); /// \brief Create an Objective-C protocol reference at the given location. CXCursor MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack an ObjCProtocolRef cursor into the protocol it references /// and optionally the location where the reference occurred. std::pair<const ObjCProtocolDecl *, SourceLocation> getCursorObjCProtocolRef(CXCursor C); /// \brief Create an Objective-C class reference at the given location. CXCursor MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack an ObjCClassRef cursor into the class it references /// and optionally the location where the reference occurred. std::pair<const ObjCInterfaceDecl *, SourceLocation> getCursorObjCClassRef(CXCursor C); /// \brief Create a type reference at the given location. CXCursor MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a TypeRef cursor into the class it references /// and optionally the location where the reference occurred. std::pair<const TypeDecl *, SourceLocation> getCursorTypeRef(CXCursor C); /// \brief Create a reference to a template at the given location. CXCursor MakeCursorTemplateRef(const TemplateDecl *Template, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a TemplateRef cursor into the template it references and /// the location where the reference occurred. std::pair<const TemplateDecl *, SourceLocation> getCursorTemplateRef(CXCursor C); /// \brief Create a reference to a namespace or namespace alias at the given /// location. CXCursor MakeCursorNamespaceRef(const NamedDecl *NS, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a NamespaceRef cursor into the namespace or namespace alias /// it references and the location where the reference occurred. std::pair<const NamedDecl *, SourceLocation> getCursorNamespaceRef(CXCursor C); /// \brief Create a reference to a variable at the given location. CXCursor MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a VariableRef cursor into the variable it references and the /// location where the where the reference occurred. std::pair<const VarDecl *, SourceLocation> getCursorVariableRef(CXCursor C); /// \brief Create a reference to a field at the given location. CXCursor MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a MemberRef cursor into the field it references and the /// location where the reference occurred. std::pair<const FieldDecl *, SourceLocation> getCursorMemberRef(CXCursor C); /// \brief Create a CXX base specifier cursor. CXCursor MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B, CXTranslationUnit TU); /// \brief Unpack a CXXBaseSpecifier cursor into a CXXBaseSpecifier. const CXXBaseSpecifier *getCursorCXXBaseSpecifier(CXCursor C); /// \brief Create a preprocessing directive cursor. CXCursor MakePreprocessingDirectiveCursor(SourceRange Range, CXTranslationUnit TU); /// \brief Unpack a given preprocessing directive to retrieve its source range. SourceRange getCursorPreprocessingDirective(CXCursor C); /// \brief Create a macro definition cursor. CXCursor MakeMacroDefinitionCursor(const MacroDefinitionRecord *, CXTranslationUnit TU); /// \brief Unpack a given macro definition cursor to retrieve its /// source range. const MacroDefinitionRecord *getCursorMacroDefinition(CXCursor C); /// \brief Create a macro expansion cursor. CXCursor MakeMacroExpansionCursor(MacroExpansion *, CXTranslationUnit TU); /// \brief Create a "pseudo" macro expansion cursor, using a macro definition /// and a source location. CXCursor MakeMacroExpansionCursor(MacroDefinitionRecord *, SourceLocation Loc, CXTranslationUnit TU); /// \brief Wraps a macro expansion cursor and provides a common interface /// for a normal macro expansion cursor or a "pseudo" one. /// /// "Pseudo" macro expansion cursors (essentially a macro definition along with /// a source location) are created in special cases, for example they can be /// created for identifiers inside macro definitions, if these identifiers are /// macro names. class MacroExpansionCursor { CXCursor C; bool isPseudo() const { return C.data[1] != nullptr; } const MacroDefinitionRecord *getAsMacroDefinition() const { assert(isPseudo()); return static_cast<const MacroDefinitionRecord *>(C.data[0]); } const MacroExpansion *getAsMacroExpansion() const { assert(!isPseudo()); return static_cast<const MacroExpansion *>(C.data[0]); } SourceLocation getPseudoLoc() const { assert(isPseudo()); return SourceLocation::getFromPtrEncoding(C.data[1]); } public: MacroExpansionCursor(CXCursor C) : C(C) { assert(C.kind == CXCursor_MacroExpansion); } const IdentifierInfo *getName() const; const MacroDefinitionRecord *getDefinition() const; SourceRange getSourceRange() const; }; /// \brief Unpack a given macro expansion cursor to retrieve its info. static inline MacroExpansionCursor getCursorMacroExpansion(CXCursor C) { return C; } /// \brief Create an inclusion directive cursor. CXCursor MakeInclusionDirectiveCursor(InclusionDirective *, CXTranslationUnit TU); /// \brief Unpack a given inclusion directive cursor to retrieve its /// source range. const InclusionDirective *getCursorInclusionDirective(CXCursor C); /// \brief Create a label reference at the given location. CXCursor MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc, CXTranslationUnit TU); /// \brief Unpack a label reference into the label statement it refers to and /// the location of the reference. std::pair<const LabelStmt *, SourceLocation> getCursorLabelRef(CXCursor C); /// \brief Create a overloaded declaration reference cursor for an expression. CXCursor MakeCursorOverloadedDeclRef(const OverloadExpr *E, CXTranslationUnit TU); /// \brief Create a overloaded declaration reference cursor for a declaration. CXCursor MakeCursorOverloadedDeclRef(const Decl *D, SourceLocation Location, CXTranslationUnit TU); /// \brief Create a overloaded declaration reference cursor for a template name. CXCursor MakeCursorOverloadedDeclRef(TemplateName Template, SourceLocation Location, CXTranslationUnit TU); /// \brief Internal storage for an overloaded declaration reference cursor; typedef llvm::PointerUnion3<const OverloadExpr *, const Decl *, OverloadedTemplateStorage *> OverloadedDeclRefStorage; /// \brief Unpack an overloaded declaration reference into an expression, /// declaration, or template name along with the source location. std::pair<OverloadedDeclRefStorage, SourceLocation> getCursorOverloadedDeclRef(CXCursor C); const Decl *getCursorDecl(CXCursor Cursor); const Expr *getCursorExpr(CXCursor Cursor); const Stmt *getCursorStmt(CXCursor Cursor); const Attr *getCursorAttr(CXCursor Cursor); const Decl *getCursorParentDecl(CXCursor Cursor); ASTContext &getCursorContext(CXCursor Cursor); ASTUnit *getCursorASTUnit(CXCursor Cursor); CXTranslationUnit getCursorTU(CXCursor Cursor); void getOverriddenCursors(CXCursor cursor, SmallVectorImpl<CXCursor> &overridden); /// \brief Create an opaque pool used for fast generation of overriden /// CXCursor arrays. void *createOverridenCXCursorsPool(); /// \brief Dispose of the overriden CXCursors pool. void disposeOverridenCXCursorsPool(void *pool); /// \brief Returns a index/location pair for a selector identifier if the cursor /// points to one. std::pair<int, SourceLocation> getSelectorIdentifierIndexAndLoc(CXCursor); static inline int getSelectorIdentifierIndex(CXCursor cursor) { return getSelectorIdentifierIndexAndLoc(cursor).first; } static inline SourceLocation getSelectorIdentifierLoc(CXCursor cursor) { return getSelectorIdentifierIndexAndLoc(cursor).second; } CXCursor getSelectorIdentifierCursor(int SelIdx, CXCursor cursor); static inline CXCursor getTypeRefedCallExprCursor(CXCursor cursor) { CXCursor newCursor = cursor; if (cursor.kind == CXCursor_CallExpr) newCursor.xdata = 1; return newCursor; } CXCursor getTypeRefCursor(CXCursor cursor); /// \brief Generate a USR for \arg D and put it in \arg Buf. /// \returns true if no USR was computed or the result should be ignored, /// false otherwise. bool getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf); bool operator==(CXCursor X, CXCursor Y); inline bool operator!=(CXCursor X, CXCursor Y) { return !(X == Y); } /// \brief Return true if the cursor represents a declaration that is the /// first in a declaration group. bool isFirstInDeclGroup(CXCursor C); }} // end namespace: clang::cxcursor #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXString.cpp
//===- CXString.cpp - Routines for manipulating CXStrings -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXStrings. It should be the // only file that has internal knowledge of the encoding of the data in // CXStrings. // //===----------------------------------------------------------------------===// #include "CXString.h" #include "CXTranslationUnit.h" #include "clang-c/Index.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; /// Describes the kind of underlying data in CXString. enum CXStringFlag { /// CXString contains a 'const char *' that it doesn't own. CXS_Unmanaged, /// CXString contains a 'const char *' that it allocated with malloc(). CXS_Malloc, /// CXString contains a CXStringBuf that needs to be returned to the /// CXStringPool. CXS_StringBuf }; namespace clang { namespace cxstring { //===----------------------------------------------------------------------===// // Basic generation of CXStrings. //===----------------------------------------------------------------------===// CXString createEmpty() { CXString Str; Str.data = ""; Str.private_flags = CXS_Unmanaged; return Str; } CXString createNull() { CXString Str; Str.data = nullptr; Str.private_flags = CXS_Unmanaged; return Str; } CXString createRef(const char *String) { if (String && String[0] == '\0') return createEmpty(); CXString Str; Str.data = String; Str.private_flags = CXS_Unmanaged; return Str; } CXString createDup(const char *String) { if (!String) return createNull(); if (String[0] == '\0') return createEmpty(); CXString Str; Str.data = _strdup(String); // HLSL Change strdup to _strdup Str.private_flags = CXS_Malloc; return Str; } CXString createRef(StringRef String) { // If the string is not nul-terminated, we have to make a copy. // FIXME: This is doing a one past end read, and should be removed! For memory // we don't manage, the API string can become unterminated at any time outside // our control. if (!String.empty() && String.data()[String.size()] != 0) return createDup(String); CXString Result; Result.data = String.data(); Result.private_flags = (unsigned) CXS_Unmanaged; return Result; } CXString createDup(StringRef String) { CXString Result; char *Spelling = static_cast<char *>(malloc(String.size() + 1)); memmove(Spelling, String.data(), String.size()); Spelling[String.size()] = 0; Result.data = Spelling; Result.private_flags = (unsigned) CXS_Malloc; return Result; } CXString createCXString(CXStringBuf *buf) { CXString Str; Str.data = buf; Str.private_flags = (unsigned) CXS_StringBuf; return Str; } //===----------------------------------------------------------------------===// // String pools. //===----------------------------------------------------------------------===// CXStringPool::~CXStringPool() { for (std::vector<CXStringBuf *>::iterator I = Pool.begin(), E = Pool.end(); I != E; ++I) { delete *I; } } CXStringBuf *CXStringPool::getCXStringBuf(CXTranslationUnit TU) { if (Pool.empty()) return new CXStringBuf(TU); CXStringBuf *Buf = Pool.back(); Buf->Data.clear(); Pool.pop_back(); return Buf; } CXStringBuf *getCXStringBuf(CXTranslationUnit TU) { return TU->StringPool->getCXStringBuf(TU); } void CXStringBuf::dispose() { TU->StringPool->Pool.push_back(this); } bool isManagedByPool(CXString str) { return ((CXStringFlag) str.private_flags) == CXS_StringBuf; } } // end namespace cxstring } // end namespace clang //===----------------------------------------------------------------------===// // libClang public APIs. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. const char *clang_getCString(CXString string) { if (string.private_flags == (unsigned) CXS_StringBuf) { return static_cast<const cxstring::CXStringBuf *>(string.data)->Data.data(); } return static_cast<const char *>(string.data); } void clang_disposeString(CXString string) { switch ((CXStringFlag) string.private_flags) { case CXS_Unmanaged: break; case CXS_Malloc: if (string.data) free(const_cast<void *>(string.data)); break; case CXS_StringBuf: static_cast<cxstring::CXStringBuf *>( const_cast<void *>(string.data))->dispose(); break; } } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexUSRs.cpp
//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the generation and use of USRs from CXEntities. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CXCursor.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Index/USRGeneration.h" #include "clang/Lex/PreprocessingRecord.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::index; //===----------------------------------------------------------------------===// // API hooks. //===----------------------------------------------------------------------===// static inline StringRef extractUSRSuffix(StringRef s) { return s.startswith("c:") ? s.substr(2) : ""; } bool cxcursor::getDeclCursorUSR(const Decl *D, SmallVectorImpl<char> &Buf) { return generateUSRForDecl(D, Buf); } // extern "C" { // HLSL Change -Don't use c linkage. CXString clang_getCursorUSR(CXCursor C) { const CXCursorKind &K = clang_getCursorKind(C); if (clang_isDeclaration(K)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return cxstring::createEmpty(); CXTranslationUnit TU = cxcursor::getCursorTU(C); if (!TU) return cxstring::createEmpty(); cxstring::CXStringBuf *buf = cxstring::getCXStringBuf(TU); if (!buf) return cxstring::createEmpty(); bool Ignore = cxcursor::getDeclCursorUSR(D, buf->Data); if (Ignore) { buf->dispose(); return cxstring::createEmpty(); } // Return the C-string, but don't make a copy since it is already in // the string buffer. buf->Data.push_back('\0'); return createCXString(buf); } if (K == CXCursor_MacroDefinition) { CXTranslationUnit TU = cxcursor::getCursorTU(C); if (!TU) return cxstring::createEmpty(); cxstring::CXStringBuf *buf = cxstring::getCXStringBuf(TU); if (!buf) return cxstring::createEmpty(); bool Ignore = generateUSRForMacro(cxcursor::getCursorMacroDefinition(C), cxtu::getASTUnit(TU)->getSourceManager(), buf->Data); if (Ignore) { buf->dispose(); return cxstring::createEmpty(); } // Return the C-string, but don't make a copy since it is already in // the string buffer. buf->Data.push_back('\0'); return createCXString(buf); } return cxstring::createEmpty(); } CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); OS << extractUSRSuffix(clang_getCString(classUSR)); generateUSRForObjCIvar(name, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCMethod(const char *name, unsigned isInstanceMethod, CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); OS << extractUSRSuffix(clang_getCString(classUSR)); generateUSRForObjCMethod(name, isInstanceMethod, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCClass(const char *name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); generateUSRForObjCClass(name, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCProtocol(const char *name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); generateUSRForObjCProtocol(name, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCCategory(const char *class_name, const char *category_name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); generateUSRForObjCCategory(class_name, category_name, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCProperty(const char *property, CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); OS << extractUSRSuffix(clang_getCString(classUSR)); generateUSRForObjCProperty(property, OS); return cxstring::createDup(OS.str()); } // } // end extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/IndexBody.cpp
//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/DataRecursiveASTVisitor.h" using namespace clang; using namespace cxindex; namespace { class BodyIndexer : public DataRecursiveASTVisitor<BodyIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; typedef DataRecursiveASTVisitor<BodyIndexer> base; public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool TraverseTypeLoc(TypeLoc TL) { IndexCtx.indexTypeLoc(TL, Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } bool VisitDeclRefExpr(DeclRefExpr *E) { IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, E); return true; } bool VisitMemberExpr(MemberExpr *E) { IndexCtx.handleReference(E->getMemberDecl(), E->getMemberLoc(), Parent, ParentDC, E); return true; } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::reverse_designators_iterator D = E->designators_rbegin(), DEnd = E->designators_rend(); D != DEnd; ++D) { if (D->isFieldDesignator()) IndexCtx.handleReference(D->getField(), D->getFieldLoc(), Parent, ParentDC, E); } return true; } bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, E); return true; } bool VisitObjCMessageExpr(ObjCMessageExpr *E) { if (ObjCMethodDecl *MD = E->getMethodDecl()) IndexCtx.handleReference(MD, E->getSelectorStartLoc(), Parent, ParentDC, E, E->isImplicit() ? CXIdxEntityRef_Implicit : CXIdxEntityRef_Direct); return true; } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { if (E->isExplicitProperty()) IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(), Parent, ParentDC, E); // No need to do a handleReference for the objc method, because there will // be a message expr as part of PseudoObjectExpr. return true; } bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) { IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(), Parent, ParentDC, E, CXIdxEntityRef_Direct); return true; } bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) { IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(), Parent, ParentDC, E, CXIdxEntityRef_Direct); return true; } bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) { if (ObjCMethodDecl *MD = E->getBoxingMethod()) IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, E, CXIdxEntityRef_Implicit); return true; } bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, E, CXIdxEntityRef_Implicit); return true; } bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) { if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, E, CXIdxEntityRef_Implicit); return true; } bool VisitCXXConstructExpr(CXXConstructExpr *E) { IndexCtx.handleReference(E->getConstructor(), E->getLocation(), Parent, ParentDC, E); return true; } bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E) { if (E->getOperatorLoc().isInvalid()) return true; // implicit. return base::TraverseCXXOperatorCallExpr(E); } bool VisitDeclStmt(DeclStmt *S) { if (IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexDeclGroupRef(S->getDeclGroup()); return true; } DeclGroupRef DG = S->getDeclGroup(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (!D) continue; if (!IndexCtx.isFunctionLocalDecl(D)) IndexCtx.indexTopLevelDecl(D); } return true; } bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) { if (C->capturesThis() || C->capturesVLAType()) return true; if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols()) IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent, ParentDC); // FIXME: Lambda init-captures. return true; } }; } // anonymous namespace void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC) { if (!S) return; if (!DC) DC = Parent->getLexicalDeclContext(); BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S)); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXComment.cpp
//===- CXComment.cpp - libclang APIs for manipulating CXComments ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines all libclang APIs related to walking comment AST. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "CXComment.h" #include "CXCursor.h" #include "CXString.h" #include "clang-c/Documentation.h" #include "clang/AST/Decl.h" #include "clang/Index/CommentToXML.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <climits> using namespace clang; using namespace clang::comments; using namespace clang::cxcomment; // extern "C" { // HLSL Change -Don't use c linkage. CXComment clang_Cursor_getParsedComment(CXCursor C) { using namespace clang::cxcursor; if (!clang_isDeclaration(C.kind)) return createCXComment(nullptr, nullptr); const Decl *D = getCursorDecl(C); const ASTContext &Context = getCursorContext(C); const FullComment *FC = Context.getCommentForDecl(D, /*PP=*/nullptr); return createCXComment(FC, getCursorTU(C)); } enum CXCommentKind clang_Comment_getKind(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return CXComment_Null; switch (C->getCommentKind()) { case Comment::NoCommentKind: return CXComment_Null; case Comment::TextCommentKind: return CXComment_Text; case Comment::InlineCommandCommentKind: return CXComment_InlineCommand; case Comment::HTMLStartTagCommentKind: return CXComment_HTMLStartTag; case Comment::HTMLEndTagCommentKind: return CXComment_HTMLEndTag; case Comment::ParagraphCommentKind: return CXComment_Paragraph; case Comment::BlockCommandCommentKind: return CXComment_BlockCommand; case Comment::ParamCommandCommentKind: return CXComment_ParamCommand; case Comment::TParamCommandCommentKind: return CXComment_TParamCommand; case Comment::VerbatimBlockCommentKind: return CXComment_VerbatimBlockCommand; case Comment::VerbatimBlockLineCommentKind: return CXComment_VerbatimBlockLine; case Comment::VerbatimLineCommentKind: return CXComment_VerbatimLine; case Comment::FullCommentKind: return CXComment_FullComment; } llvm_unreachable("unknown CommentKind"); } unsigned clang_Comment_getNumChildren(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return 0; return C->child_count(); } CXComment clang_Comment_getChild(CXComment CXC, unsigned ChildIdx) { const Comment *C = getASTNode(CXC); if (!C || ChildIdx >= C->child_count()) return createCXComment(nullptr, nullptr); return createCXComment(*(C->child_begin() + ChildIdx), CXC.TranslationUnit); } unsigned clang_Comment_isWhitespace(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return false; if (const TextComment *TC = dyn_cast<TextComment>(C)) return TC->isWhitespace(); if (const ParagraphComment *PC = dyn_cast<ParagraphComment>(C)) return PC->isWhitespace(); return false; } unsigned clang_InlineContentComment_hasTrailingNewline(CXComment CXC) { const InlineContentComment *ICC = getASTNodeAs<InlineContentComment>(CXC); if (!ICC) return false; return ICC->hasTrailingNewline(); } CXString clang_TextComment_getText(CXComment CXC) { const TextComment *TC = getASTNodeAs<TextComment>(CXC); if (!TC) return cxstring::createNull(); return cxstring::createRef(TC->getText()); } CXString clang_InlineCommandComment_getCommandName(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(ICC->getCommandName(Traits)); } enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return CXCommentInlineCommandRenderKind_Normal; switch (ICC->getRenderKind()) { case InlineCommandComment::RenderNormal: return CXCommentInlineCommandRenderKind_Normal; case InlineCommandComment::RenderBold: return CXCommentInlineCommandRenderKind_Bold; case InlineCommandComment::RenderMonospaced: return CXCommentInlineCommandRenderKind_Monospaced; case InlineCommandComment::RenderEmphasized: return CXCommentInlineCommandRenderKind_Emphasized; } llvm_unreachable("unknown InlineCommandComment::RenderKind"); } unsigned clang_InlineCommandComment_getNumArgs(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return 0; return ICC->getNumArgs(); } CXString clang_InlineCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC || ArgIdx >= ICC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(ICC->getArgText(ArgIdx)); } CXString clang_HTMLTagComment_getTagName(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); return cxstring::createRef(HTC->getTagName()); } unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return false; return HST->isSelfClosing(); } unsigned clang_HTMLStartTag_getNumAttrs(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return 0; return HST->getNumAttrs(); } CXString clang_HTMLStartTag_getAttrName(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Name); } CXString clang_HTMLStartTag_getAttrValue(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Value); } CXString clang_BlockCommandComment_getCommandName(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(BCC->getCommandName(Traits)); } unsigned clang_BlockCommandComment_getNumArgs(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return 0; return BCC->getNumArgs(); } CXString clang_BlockCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC || ArgIdx >= BCC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(BCC->getArgText(ArgIdx)); } CXComment clang_BlockCommandComment_getParagraph(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return createCXComment(nullptr, nullptr); return createCXComment(BCC->getParagraph(), CXC.TranslationUnit); } CXString clang_ParamCommandComment_getParamName(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(PCC->getParamNameAsWritten()); } unsigned clang_ParamCommandComment_isParamIndexValid(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isParamIndexValid(); } unsigned clang_ParamCommandComment_getParamIndex(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->isParamIndexValid() || PCC->isVarArgParam()) return ParamCommandComment::InvalidParamIndex; return PCC->getParamIndex(); } unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isDirectionExplicit(); } enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection( CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return CXCommentParamPassDirection_In; switch (PCC->getDirection()) { case ParamCommandComment::In: return CXCommentParamPassDirection_In; case ParamCommandComment::Out: return CXCommentParamPassDirection_Out; case ParamCommandComment::InOut: return CXCommentParamPassDirection_InOut; } llvm_unreachable("unknown ParamCommandComment::PassDirection"); } CXString clang_TParamCommandComment_getParamName(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(TPCC->getParamNameAsWritten()); } unsigned clang_TParamCommandComment_isParamPositionValid(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC) return false; return TPCC->isPositionValid(); } unsigned clang_TParamCommandComment_getDepth(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid()) return 0; return TPCC->getDepth(); } unsigned clang_TParamCommandComment_getIndex(CXComment CXC, unsigned Depth) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid() || Depth >= TPCC->getDepth()) return 0; return TPCC->getIndex(Depth); } CXString clang_VerbatimBlockLineComment_getText(CXComment CXC) { const VerbatimBlockLineComment *VBL = getASTNodeAs<VerbatimBlockLineComment>(CXC); if (!VBL) return cxstring::createNull(); return cxstring::createRef(VBL->getText()); } CXString clang_VerbatimLineComment_getText(CXComment CXC) { const VerbatimLineComment *VLC = getASTNodeAs<VerbatimLineComment>(CXC); if (!VLC) return cxstring::createNull(); return cxstring::createRef(VLC->getText()); } //===----------------------------------------------------------------------===// // Converting comments to XML. //===----------------------------------------------------------------------===// CXString clang_HTMLTagComment_getAsString(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<128> Text; TU->CommentToXML->convertHTMLTagNodeToText( HTC, Text, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(Text.str()); } CXString clang_FullComment_getAsHTML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<1024> HTML; TU->CommentToXML ->convertCommentToHTML(FC, HTML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(HTML.str()); } CXString clang_FullComment_getAsXML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<1024> XML; TU->CommentToXML ->convertCommentToXML(FC, XML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(XML.str()); } // } // end extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/BuildSystem.cpp
//===- BuildSystem.cpp - Utilities for use by build systems ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements various utilities for use by build systems. // //===----------------------------------------------------------------------===// #include "clang-c/BuildSystem.h" #include "CXString.h" #include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Path.h" #include "llvm/Support/TimeValue.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace llvm::sys; unsigned long long clang_getBuildSessionTimestamp(void) { return llvm::sys::TimeValue::now().toEpochTime(); } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(clang::vfs::YAMLVFSWriter, CXVirtualFileOverlay) CXVirtualFileOverlay clang_VirtualFileOverlay_create(unsigned) { return wrap(new clang::vfs::YAMLVFSWriter()); } enum CXErrorCode clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay VFO, const char *virtualPath, const char *realPath) { if (!VFO || !virtualPath || !realPath) return CXError_InvalidArguments; if (!path::is_absolute(virtualPath)) return CXError_InvalidArguments; if (!path::is_absolute(realPath)) return CXError_InvalidArguments; for (path::const_iterator PI = path::begin(virtualPath), PE = path::end(virtualPath); PI != PE; ++PI) { StringRef Comp = *PI; if (Comp == "." || Comp == "..") return CXError_InvalidArguments; } unwrap(VFO)->addFileMapping(virtualPath, realPath); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_setCaseSensitivity(CXVirtualFileOverlay VFO, int caseSensitive) { if (!VFO) return CXError_InvalidArguments; unwrap(VFO)->setCaseSensitivity(caseSensitive); return CXError_Success; } enum CXErrorCode clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay VFO, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!VFO || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); unwrap(VFO)->write(OS); StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_free(void *buffer) { free(buffer); } void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay VFO) { delete unwrap(VFO); } struct CXModuleMapDescriptorImpl { std::string ModuleName; std::string UmbrellaHeader; }; CXModuleMapDescriptor clang_ModuleMapDescriptor_create(unsigned) { return new CXModuleMapDescriptorImpl(); } enum CXErrorCode clang_ModuleMapDescriptor_setFrameworkModuleName(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->ModuleName = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_setUmbrellaHeader(CXModuleMapDescriptor MMD, const char *name) { if (!MMD || !name) return CXError_InvalidArguments; MMD->UmbrellaHeader = name; return CXError_Success; } enum CXErrorCode clang_ModuleMapDescriptor_writeToBuffer(CXModuleMapDescriptor MMD, unsigned, char **out_buffer_ptr, unsigned *out_buffer_size) { if (!MMD || !out_buffer_ptr || !out_buffer_size) return CXError_InvalidArguments; llvm::SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); OS << "framework module " << MMD->ModuleName << " {\n"; OS << " umbrella header \""; OS.write_escaped(MMD->UmbrellaHeader) << "\"\n"; OS << '\n'; OS << " export *\n"; OS << " module * { export * }\n"; OS << "}\n"; StringRef Data = OS.str(); *out_buffer_ptr = (char*)malloc(Data.size()); *out_buffer_size = Data.size(); memcpy(*out_buffer_ptr, Data.data(), Data.size()); return CXError_Success; } void clang_ModuleMapDescriptor_dispose(CXModuleMapDescriptor MMD) { delete MMD; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXLoadedDiagnostic.h
/*===-- CXLoadedDiagnostic.h - Handling of persisent diags ------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Implements handling of persisent diagnostics. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXLOADEDDIAGNOSTIC_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXLOADEDDIAGNOSTIC_H #include "CIndexDiagnostic.h" #include "llvm/ADT/StringRef.h" #include "clang/Basic/LLVM.h" #include <string> #include <vector> namespace clang { class CXLoadedDiagnostic : public CXDiagnosticImpl { public: CXLoadedDiagnostic() : CXDiagnosticImpl(LoadedDiagnosticKind), severity(0), category(0) {} ~CXLoadedDiagnostic() override; /// \brief Return the severity of the diagnostic. CXDiagnosticSeverity getSeverity() const override; /// \brief Return the location of the diagnostic. CXSourceLocation getLocation() const override; /// \brief Return the spelling of the diagnostic. CXString getSpelling() const override; /// \brief Return the text for the diagnostic option. CXString getDiagnosticOption(CXString *Disable) const override; /// \brief Return the category of the diagnostic. unsigned getCategory() const override; /// \brief Return the category string of the diagnostic. CXString getCategoryText() const override; /// \brief Return the number of source ranges for the diagnostic. unsigned getNumRanges() const override; /// \brief Return the source ranges for the diagnostic. CXSourceRange getRange(unsigned Range) const override; /// \brief Return the number of FixIts. unsigned getNumFixIts() const override; /// \brief Return the FixIt information (source range and inserted text). CXString getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const override; static bool classof(const CXDiagnosticImpl *D) { return D->getKind() == LoadedDiagnosticKind; } /// \brief Decode the CXSourceLocation into file, line, column, and offset. static void decodeLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset); struct Location { CXFile file; unsigned line; unsigned column; unsigned offset; Location() : line(0), column(0), offset(0) {} }; Location DiagLoc; std::vector<CXSourceRange> Ranges; std::vector<std::pair<CXSourceRange, const char *> > FixIts; const char *Spelling; llvm::StringRef DiagOption; llvm::StringRef CategoryText; unsigned severity; unsigned category; }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXSourceLocation.cpp
//===- CXSourceLocation.cpp - CXSourceLocations APIs ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXSourceLocations. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "CIndexer.h" #include "CLog.h" #include "CXLoadedDiagnostic.h" #include "CXSourceLocation.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Format.h" using namespace clang; using namespace clang::cxindex; //===----------------------------------------------------------------------===// // Internal predicates on CXSourceLocations. //===----------------------------------------------------------------------===// static bool isASTUnitSourceLocation(const CXSourceLocation &L) { // If the lowest bit is clear then the first ptr_data entry is a SourceManager // pointer, or the CXSourceLocation is a null location. return ((uintptr_t)L.ptr_data[0] & 0x1) == 0; } //===----------------------------------------------------------------------===// // Basic construction and comparison of CXSourceLocations and CXSourceRanges. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXSourceLocation clang_getNullLocation() { CXSourceLocation Result = { { nullptr, nullptr }, 0 }; return Result; } unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { return (loc1.ptr_data[0] == loc2.ptr_data[0] && loc1.ptr_data[1] == loc2.ptr_data[1] && loc1.int_data == loc2.int_data); } CXSourceRange clang_getNullRange() { CXSourceRange Result = { { nullptr, nullptr }, 0, 0 }; return Result; } CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { if (!isASTUnitSourceLocation(begin)) { if (isASTUnitSourceLocation(end)) return clang_getNullRange(); CXSourceRange Result = { { begin.ptr_data[0], end.ptr_data[0] }, 0, 0 }; return Result; } if (begin.ptr_data[0] != end.ptr_data[0] || begin.ptr_data[1] != end.ptr_data[1]) return clang_getNullRange(); CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, begin.int_data, end.int_data }; return Result; } unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2) { return range1.ptr_data[0] == range2.ptr_data[0] && range1.ptr_data[1] == range2.ptr_data[1] && range1.begin_int_data == range2.begin_int_data && range1.end_int_data == range2.end_int_data; } int clang_Range_isNull(CXSourceRange range) { return clang_equalRanges(range, clang_getNullRange()); } CXSourceLocation clang_getRangeStart(CXSourceRange range) { // Special decoding for CXSourceLocations for CXLoadedDiagnostics. if ((uintptr_t)range.ptr_data[0] & 0x1) { CXSourceLocation Result = { { range.ptr_data[0], nullptr }, 0 }; return Result; } CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, range.begin_int_data }; return Result; } CXSourceLocation clang_getRangeEnd(CXSourceRange range) { // Special decoding for CXSourceLocations for CXLoadedDiagnostics. if ((uintptr_t)range.ptr_data[0] & 0x1) { CXSourceLocation Result = { { range.ptr_data[1], nullptr }, 0 }; return Result; } CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, range.end_int_data }; return Result; } // } // end extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Getting CXSourceLocations and CXSourceRanges from a translation unit. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXSourceLocation clang_getLocation(CXTranslationUnit TU, CXFile file, unsigned line, unsigned column) { if (cxtu::isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullLocation(); } if (!file) return clang_getNullLocation(); if (line == 0 || column == 0) return clang_getNullLocation(); LogRef Log = Logger::make(LLVM_FUNCTION_NAME); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); const FileEntry *File = static_cast<const FileEntry *>(file); SourceLocation SLoc = CXXUnit->getLocation(File, line, column); if (SLoc.isInvalid()) { if (Log) *Log << llvm::format("(\"%s\", %d, %d) = invalid", File->getName(), line, column); return clang_getNullLocation(); } CXSourceLocation CXLoc = cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); if (Log) *Log << llvm::format("(\"%s\", %d, %d) = ", File->getName(), line, column) << CXLoc; return CXLoc; } CXSourceLocation clang_getLocationForOffset(CXTranslationUnit TU, CXFile file, unsigned offset) { if (cxtu::isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullLocation(); } if (!file) return clang_getNullLocation(); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); SourceLocation SLoc = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset); if (SLoc.isInvalid()) return clang_getNullLocation(); return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); } // } // end extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Routines for expanding and manipulating CXSourceLocations, regardless // of their origin. //===----------------------------------------------------------------------===// static void createNullLocation(CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (file) *file = nullptr; if (line) *line = 0; if (column) *column = 0; if (offset) *offset = 0; return; } static void createNullLocation(CXString *filename, unsigned *line, unsigned *column, unsigned *offset = nullptr) { if (filename) *filename = cxstring::createEmpty(); if (line) *line = 0; if (column) *column = 0; if (offset) *offset = 0; return; } // extern "C" { // HLSL Change -Don't use c linkage. int clang_Location_isInSystemHeader(CXSourceLocation location) { const SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (Loc.isInvalid()) return 0; const SourceManager &SM = *static_cast<const SourceManager*>(location.ptr_data[0]); return SM.isInSystemHeader(Loc); } int clang_Location_isFromMainFile(CXSourceLocation location) { const SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (Loc.isInvalid()) return 0; const SourceManager &SM = *static_cast<const SourceManager*>(location.ptr_data[0]); return SM.isWrittenInMainFile(Loc); } void clang_getExpansionLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (!isASTUnitSourceLocation(location)) { CXLoadedDiagnostic::decodeLocation(location, file, line, column, offset); return; } SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) { createNullLocation(file, line, column, offset); return; } const SourceManager &SM = *static_cast<const SourceManager*>(location.ptr_data[0]); SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc); // Check that the FileID is invalid on the expansion location. // This can manifest in invalid code. FileID fileID = SM.getFileID(ExpansionLoc); bool Invalid = false; const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid); if (Invalid || !sloc.isFile()) { createNullLocation(file, line, column, offset); return; } if (file) *file = const_cast<FileEntry *>(SM.getFileEntryForSLocEntry(sloc)); if (line) *line = SM.getExpansionLineNumber(ExpansionLoc); if (column) *column = SM.getExpansionColumnNumber(ExpansionLoc); if (offset) *offset = SM.getDecomposedLoc(ExpansionLoc).second; } void clang_getPresumedLocation(CXSourceLocation location, CXString *filename, unsigned *line, unsigned *column) { if (!isASTUnitSourceLocation(location)) { // Other SourceLocation implementations do not support presumed locations // at this time. createNullLocation(filename, line, column); return; } SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) { createNullLocation(filename, line, column); return; } const SourceManager &SM = *static_cast<const SourceManager *>(location.ptr_data[0]); PresumedLoc PreLoc = SM.getPresumedLoc(Loc); if (PreLoc.isInvalid()) { createNullLocation(filename, line, column); return; } if (filename) *filename = cxstring::createRef(PreLoc.getFilename()); if (line) *line = PreLoc.getLine(); if (column) *column = PreLoc.getColumn(); } void clang_getInstantiationLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { // Redirect to new API. clang_getExpansionLocation(location, file, line, column, offset); } void clang_getSpellingLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (!isASTUnitSourceLocation(location)) { CXLoadedDiagnostic::decodeLocation(location, file, line, column, offset); return; } SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) return createNullLocation(file, line, column, offset); const SourceManager &SM = *static_cast<const SourceManager*>(location.ptr_data[0]); // FIXME: This should call SourceManager::getSpellingLoc(). SourceLocation SpellLoc = SM.getFileLoc(Loc); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; if (FID.isInvalid()) return createNullLocation(file, line, column, offset); if (file) *file = const_cast<FileEntry *>(SM.getFileEntryForID(FID)); if (line) *line = SM.getLineNumber(FID, FileOffset); if (column) *column = SM.getColumnNumber(FID, FileOffset); if (offset) *offset = FileOffset; } void clang_getFileLocation(CXSourceLocation location, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (!isASTUnitSourceLocation(location)) { CXLoadedDiagnostic::decodeLocation(location, file, line, column, offset); return; } SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) return createNullLocation(file, line, column, offset); const SourceManager &SM = *static_cast<const SourceManager*>(location.ptr_data[0]); SourceLocation FileLoc = SM.getFileLoc(Loc); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(FileLoc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; if (FID.isInvalid()) return createNullLocation(file, line, column, offset); if (file) *file = const_cast<FileEntry *>(SM.getFileEntryForID(FID)); if (line) *line = SM.getLineNumber(FID, FileOffset); if (column) *column = SM.getColumnNumber(FID, FileOffset); if (offset) *offset = FileOffset; } // } // end extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXSourceLocation.h
//===- CXSourceLocation.h - CXSourceLocations Utilities ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXSourceLocations. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXSOURCELOCATION_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXSOURCELOCATION_H #include "clang-c/Index.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceLocation.h" namespace clang { class SourceManager; namespace cxloc { /// \brief Translate a Clang source location into a CIndex source location. static inline CXSourceLocation translateSourceLocation(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation Loc) { if (Loc.isInvalid()) clang_getNullLocation(); CXSourceLocation Result = { { &SM, &LangOpts, }, Loc.getRawEncoding() }; return Result; } /// \brief Translate a Clang source location into a CIndex source location. static inline CXSourceLocation translateSourceLocation(ASTContext &Context, SourceLocation Loc) { return translateSourceLocation(Context.getSourceManager(), Context.getLangOpts(), Loc); } /// \brief Translate a Clang source range into a CIndex source range. /// /// Clang internally represents ranges where the end location points to the /// start of the token at the end. However, for external clients it is more /// useful to have a CXSourceRange be a proper half-open interval. This routine /// does the appropriate translation. CXSourceRange translateSourceRange(const SourceManager &SM, const LangOptions &LangOpts, const CharSourceRange &R); /// \brief Translate a Clang source range into a CIndex source range. static inline CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) { return translateSourceRange(Context.getSourceManager(), Context.getLangOpts(), CharSourceRange::getTokenRange(R)); } static inline SourceLocation translateSourceLocation(CXSourceLocation L) { return SourceLocation::getFromRawEncoding(L.int_data); } static inline SourceRange translateCXSourceRange(CXSourceRange R) { return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data), SourceLocation::getFromRawEncoding(R.end_int_data)); } }} // end namespace: clang::cxloc #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexDiagnostic.h
/*===-- CIndexDiagnostic.h - Diagnostics C Interface ------------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Implements the diagnostic functions of the Clang C interface. *| |* *| \*===----------------------------------------------------------------------===*/ #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CINDEXDIAGNOSTIC_H #define LLVM_CLANG_TOOLS_LIBCLANG_CINDEXDIAGNOSTIC_H #include "clang-c/Index.h" #include <memory> #include <vector> #include <assert.h> namespace clang { class LangOptions; class StoredDiagnostic; class CXDiagnosticImpl; class CXDiagnosticSetImpl { std::vector<std::unique_ptr<CXDiagnosticImpl>> Diagnostics; const bool IsExternallyManaged; public: CXDiagnosticSetImpl(bool isManaged = false) : IsExternallyManaged(isManaged) {} virtual ~CXDiagnosticSetImpl(); size_t getNumDiagnostics() const { return Diagnostics.size(); } CXDiagnosticImpl *getDiagnostic(unsigned i) const { assert(i < getNumDiagnostics()); return Diagnostics[i].get(); } void appendDiagnostic(std::unique_ptr<CXDiagnosticImpl> D); bool empty() const { return Diagnostics.empty(); } bool isExternallyManaged() const { return IsExternallyManaged; } }; class CXDiagnosticImpl { public: enum Kind { StoredDiagnosticKind, LoadedDiagnosticKind, CustomNoteDiagnosticKind }; virtual ~CXDiagnosticImpl(); /// \brief Return the severity of the diagnostic. virtual CXDiagnosticSeverity getSeverity() const = 0; /// \brief Return the location of the diagnostic. virtual CXSourceLocation getLocation() const = 0; /// \brief Return the spelling of the diagnostic. virtual CXString getSpelling() const = 0; /// \brief Return the text for the diagnostic option. virtual CXString getDiagnosticOption(CXString *Disable) const = 0; /// \brief Return the category of the diagnostic. virtual unsigned getCategory() const = 0; /// \brief Return the category string of the diagnostic. virtual CXString getCategoryText() const = 0; /// \brief Return the number of source ranges for the diagnostic. virtual unsigned getNumRanges() const = 0; /// \brief Return the source ranges for the diagnostic. virtual CXSourceRange getRange(unsigned Range) const = 0; /// \brief Return the number of FixIts. virtual unsigned getNumFixIts() const = 0; /// \brief Return the FixIt information (source range and inserted text). virtual CXString getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const = 0; Kind getKind() const { return K; } CXDiagnosticSetImpl &getChildDiagnostics() { return ChildDiags; } protected: CXDiagnosticImpl(Kind k) : K(k) {} CXDiagnosticSetImpl ChildDiags; void append(std::unique_ptr<CXDiagnosticImpl> D) { ChildDiags.appendDiagnostic(std::move(D)); } private: Kind K; }; /// \brief The storage behind a CXDiagnostic struct CXStoredDiagnostic : public CXDiagnosticImpl { const StoredDiagnostic &Diag; const LangOptions &LangOpts; CXStoredDiagnostic(const StoredDiagnostic &Diag, const LangOptions &LangOpts) : CXDiagnosticImpl(StoredDiagnosticKind), Diag(Diag), LangOpts(LangOpts) { } ~CXStoredDiagnostic() override {} /// \brief Return the severity of the diagnostic. CXDiagnosticSeverity getSeverity() const override; /// \brief Return the location of the diagnostic. CXSourceLocation getLocation() const override; /// \brief Return the spelling of the diagnostic. CXString getSpelling() const override; /// \brief Return the text for the diagnostic option. CXString getDiagnosticOption(CXString *Disable) const override; /// \brief Return the category of the diagnostic. unsigned getCategory() const override; /// \brief Return the category string of the diagnostic. CXString getCategoryText() const override; /// \brief Return the number of source ranges for the diagnostic. unsigned getNumRanges() const override; /// \brief Return the source ranges for the diagnostic. CXSourceRange getRange(unsigned Range) const override; /// \brief Return the number of FixIts. unsigned getNumFixIts() const override; /// \brief Return the FixIt information (source range and inserted text). CXString getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const override; static bool classof(const CXDiagnosticImpl *D) { return D->getKind() == StoredDiagnosticKind; } }; namespace cxdiag { CXDiagnosticSetImpl *lazyCreateDiags(CXTranslationUnit TU, bool checkIfChanged = false); } // end namespace cxdiag } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/IndexTypeSourceInfo.cpp
//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/DataRecursiveASTVisitor.h" using namespace clang; using namespace cxindex; namespace { class TypeIndexer : public DataRecursiveASTVisitor<TypeIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; public: TypeIndexer(IndexingContext &indexCtx, const NamedDecl *parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool VisitTypedefTypeLoc(TypedefTypeLoc TL) { IndexCtx.handleReference(TL.getTypedefNameDecl(), TL.getNameLoc(), Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } bool VisitTagTypeLoc(TagTypeLoc TL) { TagDecl *D = TL.getDecl(); if (D->getParentFunctionOrMethod()) return true; if (TL.isDefinition()) { IndexCtx.indexTagDecl(D); return true; } if (D->getLocation() == TL.getNameLoc()) IndexCtx.handleTagDecl(D); else IndexCtx.handleReference(D, TL.getNameLoc(), Parent, ParentDC); return true; } bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { IndexCtx.handleReference(TL.getIFaceDecl(), TL.getNameLoc(), Parent, ParentDC); return true; } bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) { IndexCtx.handleReference(TL.getProtocol(i), TL.getProtocolLoc(i), Parent, ParentDC); } return true; } bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { if (const TemplateSpecializationType *T = TL.getTypePtr()) { if (IndexCtx.shouldIndexImplicitTemplateInsts()) { if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) IndexCtx.handleReference(RD, TL.getTemplateNameLoc(), Parent, ParentDC); } else { if (const TemplateDecl *D = T->getTemplateName().getAsTemplateDecl()) IndexCtx.handleReference(D, TL.getTemplateNameLoc(), Parent, ParentDC); } } return true; } bool TraverseStmt(Stmt *S) { IndexCtx.indexBody(S, Parent, ParentDC); return true; } }; } // anonymous namespace void IndexingContext::indexTypeSourceInfo(TypeSourceInfo *TInfo, const NamedDecl *Parent, const DeclContext *DC) { if (!TInfo || TInfo->getTypeLoc().isNull()) return; indexTypeLoc(TInfo->getTypeLoc(), Parent, DC); } void IndexingContext::indexTypeLoc(TypeLoc TL, const NamedDecl *Parent, const DeclContext *DC) { if (TL.isNull()) return; if (!DC) DC = Parent->getLexicalDeclContext(); TypeIndexer(*this, Parent, DC).TraverseTypeLoc(TL); } void IndexingContext::indexNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const NamedDecl *Parent, const DeclContext *DC) { if (!NNS) return; if (NestedNameSpecifierLoc Prefix = NNS.getPrefix()) indexNestedNameSpecifierLoc(Prefix, Parent, DC); if (!DC) DC = Parent->getLexicalDeclContext(); SourceLocation Loc = NNS.getSourceRange().getBegin(); switch (NNS.getNestedNameSpecifier()->getKind()) { case NestedNameSpecifier::Identifier: case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: break; case NestedNameSpecifier::Namespace: handleReference(NNS.getNestedNameSpecifier()->getAsNamespace(), Loc, Parent, DC); break; case NestedNameSpecifier::NamespaceAlias: handleReference(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Loc, Parent, DC); break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: indexTypeLoc(NNS.getTypeLoc(), Parent, DC); break; } } void IndexingContext::indexTagDecl(const TagDecl *D) { if (handleTagDecl(D)) { if (D->isThisDeclarationADefinition()) indexDeclContext(D); } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/IndexDecl.cpp
//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/DeclVisitor.h" using namespace clang; using namespace cxindex; namespace { class IndexingDeclVisitor : public ConstDeclVisitor<IndexingDeclVisitor, bool> { IndexingContext &IndexCtx; public: explicit IndexingDeclVisitor(IndexingContext &indexCtx) : IndexCtx(indexCtx) { } /// \brief Returns true if the given method has been defined explicitly by the /// user. static bool hasUserDefined(const ObjCMethodDecl *D, const ObjCImplDecl *Container) { const ObjCMethodDecl *MD = Container->getMethod(D->getSelector(), D->isInstanceMethod()); return MD && !MD->isImplicit() && MD->isThisDeclarationADefinition(); } void handleDeclarator(const DeclaratorDecl *D, const NamedDecl *Parent = nullptr) { if (!Parent) Parent = D; if (!IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), Parent); IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent); } else { if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D)) { IndexCtx.handleVar(Parm); } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { for (auto PI : FD->params()) { IndexCtx.handleVar(PI); } } } } void handleObjCMethod(const ObjCMethodDecl *D) { IndexCtx.handleObjCMethod(D); if (D->isImplicit()) return; IndexCtx.indexTypeSourceInfo(D->getReturnTypeSourceInfo(), D); for (const auto *I : D->params()) handleDeclarator(I, D); if (D->isThisDeclarationADefinition()) { const Stmt *Body = D->getBody(); if (Body) { IndexCtx.indexBody(Body, D, D); } } } bool VisitFunctionDecl(const FunctionDecl *D) { IndexCtx.handleFunction(D); handleDeclarator(D); if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) { // Constructor initializers. for (const auto *Init : Ctor->inits()) { if (Init->isWritten()) { IndexCtx.indexTypeSourceInfo(Init->getTypeSourceInfo(), D); if (const FieldDecl *Member = Init->getAnyMember()) IndexCtx.handleReference(Member, Init->getMemberLocation(), D, D); IndexCtx.indexBody(Init->getInit(), D, D); } } } if (D->isThisDeclarationADefinition()) { const Stmt *Body = D->getBody(); if (Body) { IndexCtx.indexBody(Body, D, D); } } return true; } bool VisitVarDecl(const VarDecl *D) { IndexCtx.handleVar(D); handleDeclarator(D); IndexCtx.indexBody(D->getInit(), D); return true; } bool VisitFieldDecl(const FieldDecl *D) { IndexCtx.handleField(D); handleDeclarator(D); if (D->isBitField()) IndexCtx.indexBody(D->getBitWidth(), D); else if (D->hasInClassInitializer()) IndexCtx.indexBody(D->getInClassInitializer(), D); return true; } bool VisitMSPropertyDecl(const MSPropertyDecl *D) { handleDeclarator(D); return true; } bool VisitEnumConstantDecl(const EnumConstantDecl *D) { IndexCtx.handleEnumerator(D); IndexCtx.indexBody(D->getInitExpr(), D); return true; } bool VisitTypedefNameDecl(const TypedefNameDecl *D) { IndexCtx.handleTypedefName(D); IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D); return true; } bool VisitTagDecl(const TagDecl *D) { // Non-free standing tags are handled in indexTypeSourceInfo. if (D->isFreeStanding()) IndexCtx.indexTagDecl(D); return true; } bool VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) { IndexCtx.handleObjCInterface(D); if (D->isThisDeclarationADefinition()) { IndexCtx.indexTUDeclsInObjCContainer(); IndexCtx.indexDeclContext(D); } return true; } bool VisitObjCProtocolDecl(const ObjCProtocolDecl *D) { IndexCtx.handleObjCProtocol(D); if (D->isThisDeclarationADefinition()) { IndexCtx.indexTUDeclsInObjCContainer(); IndexCtx.indexDeclContext(D); } return true; } bool VisitObjCImplementationDecl(const ObjCImplementationDecl *D) { const ObjCInterfaceDecl *Class = D->getClassInterface(); if (!Class) return true; if (Class->isImplicitInterfaceDecl()) IndexCtx.handleObjCInterface(Class); IndexCtx.handleObjCImplementation(D); IndexCtx.indexTUDeclsInObjCContainer(); // Index the ivars first to make sure the synthesized ivars are indexed // before indexing the methods that can reference them. for (const auto *IvarI : D->ivars()) IndexCtx.indexDecl(IvarI); for (const auto *I : D->decls()) { if (!isa<ObjCIvarDecl>(I)) IndexCtx.indexDecl(I); } return true; } bool VisitObjCCategoryDecl(const ObjCCategoryDecl *D) { IndexCtx.handleObjCCategory(D); IndexCtx.indexTUDeclsInObjCContainer(); IndexCtx.indexDeclContext(D); return true; } bool VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) { const ObjCCategoryDecl *Cat = D->getCategoryDecl(); if (!Cat) return true; IndexCtx.handleObjCCategoryImpl(D); IndexCtx.indexTUDeclsInObjCContainer(); IndexCtx.indexDeclContext(D); return true; } bool VisitObjCMethodDecl(const ObjCMethodDecl *D) { // Methods associated with a property, even user-declared ones, are // handled when we handle the property. if (D->isPropertyAccessor()) return true; handleObjCMethod(D); return true; } bool VisitObjCPropertyDecl(const ObjCPropertyDecl *D) { if (ObjCMethodDecl *MD = D->getGetterMethodDecl()) if (MD->getLexicalDeclContext() == D->getLexicalDeclContext()) handleObjCMethod(MD); if (ObjCMethodDecl *MD = D->getSetterMethodDecl()) if (MD->getLexicalDeclContext() == D->getLexicalDeclContext()) handleObjCMethod(MD); IndexCtx.handleObjCProperty(D); IndexCtx.indexTypeSourceInfo(D->getTypeSourceInfo(), D); return true; } bool VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) { ObjCPropertyDecl *PD = D->getPropertyDecl(); IndexCtx.handleSynthesizedObjCProperty(D); if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) return true; assert(D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize); if (ObjCIvarDecl *IvarD = D->getPropertyIvarDecl()) { if (!IvarD->getSynthesize()) IndexCtx.handleReference(IvarD, D->getPropertyIvarDeclLoc(), nullptr, D->getDeclContext()); } if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) { if (MD->isPropertyAccessor() && !hasUserDefined(MD, cast<ObjCImplDecl>(D->getDeclContext()))) IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(), D->getLexicalDeclContext()); } if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) { if (MD->isPropertyAccessor() && !hasUserDefined(MD, cast<ObjCImplDecl>(D->getDeclContext()))) IndexCtx.handleSynthesizedObjCMethod(MD, D->getLocation(), D->getLexicalDeclContext()); } return true; } bool VisitNamespaceDecl(const NamespaceDecl *D) { IndexCtx.handleNamespace(D); IndexCtx.indexDeclContext(D); return true; } bool VisitUsingDecl(const UsingDecl *D) { // FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR, // we should do better. IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D); for (const auto *I : D->shadows()) IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), D, D->getLexicalDeclContext()); return true; } bool VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) { // FIXME: Parent for the following is CXIdxEntity_Unexposed with no USR, // we should do better. IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D); IndexCtx.handleReference(D->getNominatedNamespaceAsWritten(), D->getLocation(), D, D->getLexicalDeclContext()); return true; } bool VisitClassTemplateDecl(const ClassTemplateDecl *D) { IndexCtx.handleClassTemplate(D); if (D->isThisDeclarationADefinition()) IndexCtx.indexDeclContext(D->getTemplatedDecl()); return true; } bool VisitClassTemplateSpecializationDecl(const ClassTemplateSpecializationDecl *D) { // FIXME: Notify subsequent callbacks if info comes from implicit // instantiation. if (D->isThisDeclarationADefinition() && (IndexCtx.shouldIndexImplicitTemplateInsts() || !IndexCtx.isTemplateImplicitInstantiation(D))) IndexCtx.indexTagDecl(D); return true; } bool VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) { IndexCtx.handleFunctionTemplate(D); FunctionDecl *FD = D->getTemplatedDecl(); handleDeclarator(FD, D); if (FD->isThisDeclarationADefinition()) { const Stmt *Body = FD->getBody(); if (Body) { IndexCtx.indexBody(Body, D, FD); } } return true; } bool VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) { IndexCtx.handleTypeAliasTemplate(D); IndexCtx.indexTypeSourceInfo(D->getTemplatedDecl()->getTypeSourceInfo(), D); return true; } bool VisitImportDecl(const ImportDecl *D) { IndexCtx.importedModule(D); return true; } }; } // anonymous namespace void IndexingContext::indexDecl(const Decl *D) { if (D->isImplicit() && shouldIgnoreIfImplicit(D)) return; bool Handled = IndexingDeclVisitor(*this).Visit(D); if (!Handled && isa<DeclContext>(D)) indexDeclContext(cast<DeclContext>(D)); } void IndexingContext::indexDeclContext(const DeclContext *DC) { for (const auto *I : DC->decls()) indexDecl(I); } void IndexingContext::indexTopLevelDecl(const Decl *D) { if (isNotFromSourceFile(D->getLocation())) return; if (isa<ObjCMethodDecl>(D)) return; // Wait for the objc container. indexDecl(D); } void IndexingContext::indexDeclGroupRef(DeclGroupRef DG) { for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) indexTopLevelDecl(*I); } void IndexingContext::indexTUDeclsInObjCContainer() { while (!TUDeclsInObjCContainer.empty()) { DeclGroupRef DG = TUDeclsInObjCContainer.front(); TUDeclsInObjCContainer.pop_front(); indexDeclGroupRef(DG); } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXCompilationDatabase.cpp
#include "clang-c/CXCompilationDatabase.h" #include "CXString.h" #include "clang/Tooling/CompilationDatabase.h" #include <cstdio> using namespace clang; using namespace clang::tooling; // extern "C" { // HLSL Change -Don't use c linkage. // FIXME: do something more useful with the error message CXCompilationDatabase clang_CompilationDatabase_fromDirectory(const char *BuildDir, CXCompilationDatabase_Error *ErrorCode) { std::string ErrorMsg; CXCompilationDatabase_Error Err = CXCompilationDatabase_NoError; std::unique_ptr<CompilationDatabase> db = CompilationDatabase::loadFromDirectory(BuildDir, ErrorMsg); if (!db) { fprintf(stderr, "LIBCLANG TOOLING ERROR: %s\n", ErrorMsg.c_str()); Err = CXCompilationDatabase_CanNotLoadDatabase; } if (ErrorCode) *ErrorCode = Err; return db.release(); } void clang_CompilationDatabase_dispose(CXCompilationDatabase CDb) { delete static_cast<CompilationDatabase *>(CDb); } struct AllocatedCXCompileCommands { std::vector<CompileCommand> CCmd; AllocatedCXCompileCommands(std::vector<CompileCommand> Cmd) : CCmd(std::move(Cmd)) {} }; CXCompileCommands clang_CompilationDatabase_getCompileCommands(CXCompilationDatabase CDb, const char *CompleteFileName) { if (CompilationDatabase *db = static_cast<CompilationDatabase *>(CDb)) { std::vector<CompileCommand> CCmd(db->getCompileCommands(CompleteFileName)); if (!CCmd.empty()) return new AllocatedCXCompileCommands(std::move(CCmd)); } return nullptr; } CXCompileCommands clang_CompilationDatabase_getAllCompileCommands(CXCompilationDatabase CDb) { if (CompilationDatabase *db = static_cast<CompilationDatabase *>(CDb)) { std::vector<CompileCommand> CCmd(db->getAllCompileCommands()); if (!CCmd.empty()) return new AllocatedCXCompileCommands(std::move(CCmd)); } return nullptr; } void clang_CompileCommands_dispose(CXCompileCommands Cmds) { delete static_cast<AllocatedCXCompileCommands *>(Cmds); } unsigned clang_CompileCommands_getSize(CXCompileCommands Cmds) { if (!Cmds) return 0; AllocatedCXCompileCommands *ACC = static_cast<AllocatedCXCompileCommands *>(Cmds); return ACC->CCmd.size(); } CXCompileCommand clang_CompileCommands_getCommand(CXCompileCommands Cmds, unsigned I) { if (!Cmds) return nullptr; AllocatedCXCompileCommands *ACC = static_cast<AllocatedCXCompileCommands *>(Cmds); if (I >= ACC->CCmd.size()) return nullptr; return &ACC->CCmd[I]; } CXString clang_CompileCommand_getDirectory(CXCompileCommand CCmd) { if (!CCmd) return cxstring::createNull(); CompileCommand *cmd = static_cast<CompileCommand *>(CCmd); return cxstring::createRef(cmd->Directory.c_str()); } unsigned clang_CompileCommand_getNumArgs(CXCompileCommand CCmd) { if (!CCmd) return 0; return static_cast<CompileCommand *>(CCmd)->CommandLine.size(); } CXString clang_CompileCommand_getArg(CXCompileCommand CCmd, unsigned Arg) { if (!CCmd) return cxstring::createNull(); CompileCommand *Cmd = static_cast<CompileCommand *>(CCmd); if (Arg >= Cmd->CommandLine.size()) return cxstring::createNull(); return cxstring::createRef(Cmd->CommandLine[Arg].c_str()); } unsigned clang_CompileCommand_getNumMappedSources(CXCompileCommand CCmd) { if (!CCmd) return 0; return static_cast<CompileCommand *>(CCmd)->MappedSources.size(); } CXString clang_CompileCommand_getMappedSourcePath(CXCompileCommand CCmd, unsigned I) { if (!CCmd) return cxstring::createNull(); CompileCommand *Cmd = static_cast<CompileCommand *>(CCmd); if (I >= Cmd->MappedSources.size()) return cxstring::createNull(); return cxstring::createRef(Cmd->MappedSources[I].first.c_str()); } CXString clang_CompileCommand_getMappedSourceContent(CXCompileCommand CCmd, unsigned I) { if (!CCmd) return cxstring::createNull(); CompileCommand *Cmd = static_cast<CompileCommand *>(CCmd); if (I >= Cmd->MappedSources.size()) return cxstring::createNull(); return cxstring::createRef(Cmd->MappedSources[I].second.c_str()); } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/Indexing.cpp
//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "CIndexDiagnostic.h" #include "CIndexer.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/DeclVisitor.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/PPConditionalDirectiveRecord.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/SemaConsumer.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include <cstdio> using namespace clang; using namespace cxtu; using namespace cxindex; static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx); namespace { //===----------------------------------------------------------------------===// // Skip Parsed Bodies //===----------------------------------------------------------------------===// #ifdef LLVM_ON_WIN32 // FIXME: On windows it is disabled since current implementation depends on // file inodes. class SessionSkipBodyData { }; class TUSkipBodyControl { public: TUSkipBodyControl(SessionSkipBodyData &sessionData, PPConditionalDirectiveRecord &ppRec, Preprocessor &pp) { } bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) { return false; } void finished() { } }; #else /// \brief A "region" in source code identified by the file/offset of the /// preprocessor conditional directive that it belongs to. /// Multiple, non-consecutive ranges can be parts of the same region. /// /// As an example of different regions separated by preprocessor directives: /// /// \code /// #1 /// #ifdef BLAH /// #2 /// #ifdef CAKE /// #3 /// #endif /// #2 /// #endif /// #1 /// \endcode /// /// There are 3 regions, with non-consecutive parts: /// #1 is identified as the beginning of the file /// #2 is identified as the location of "#ifdef BLAH" /// #3 is identified as the location of "#ifdef CAKE" /// class PPRegion { llvm::sys::fs::UniqueID UniqueID; time_t ModTime; unsigned Offset; public: PPRegion() : UniqueID(0, 0), ModTime(), Offset() {} PPRegion(llvm::sys::fs::UniqueID UniqueID, unsigned offset, time_t modTime) : UniqueID(UniqueID), ModTime(modTime), Offset(offset) {} const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; } unsigned getOffset() const { return Offset; } time_t getModTime() const { return ModTime; } bool isInvalid() const { return *this == PPRegion(); } friend bool operator==(const PPRegion &lhs, const PPRegion &rhs) { return lhs.UniqueID == rhs.UniqueID && lhs.Offset == rhs.Offset && lhs.ModTime == rhs.ModTime; } }; typedef llvm::DenseSet<PPRegion> PPRegionSetTy; } // end anonymous namespace namespace llvm { template <> struct isPodLike<PPRegion> { static const bool value = true; }; template <> struct DenseMapInfo<PPRegion> { static inline PPRegion getEmptyKey() { return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-1), 0); } static inline PPRegion getTombstoneKey() { return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-2), 0); } static unsigned getHashValue(const PPRegion &S) { llvm::FoldingSetNodeID ID; const llvm::sys::fs::UniqueID &UniqueID = S.getUniqueID(); ID.AddInteger(UniqueID.getFile()); ID.AddInteger(UniqueID.getDevice()); ID.AddInteger(S.getOffset()); ID.AddInteger(S.getModTime()); return ID.ComputeHash(); } static bool isEqual(const PPRegion &LHS, const PPRegion &RHS) { return LHS == RHS; } }; } namespace { class SessionSkipBodyData { llvm::sys::Mutex Mux; PPRegionSetTy ParsedRegions; public: SessionSkipBodyData() : Mux(/*recursive=*/false) {} ~SessionSkipBodyData() { //llvm::errs() << "RegionData: " << Skipped.size() << " - " << Skipped.getMemorySize() << "\n"; } void copyTo(PPRegionSetTy &Set) { llvm::MutexGuard MG(Mux); Set = ParsedRegions; } void update(ArrayRef<PPRegion> Regions) { llvm::MutexGuard MG(Mux); ParsedRegions.insert(Regions.begin(), Regions.end()); } }; class TUSkipBodyControl { SessionSkipBodyData &SessionData; PPConditionalDirectiveRecord &PPRec; Preprocessor &PP; PPRegionSetTy ParsedRegions; SmallVector<PPRegion, 32> NewParsedRegions; PPRegion LastRegion; bool LastIsParsed; public: TUSkipBodyControl(SessionSkipBodyData &sessionData, PPConditionalDirectiveRecord &ppRec, Preprocessor &pp) : SessionData(sessionData), PPRec(ppRec), PP(pp) { SessionData.copyTo(ParsedRegions); } bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) { PPRegion region = getRegion(Loc, FID, FE); if (region.isInvalid()) return false; // Check common case, consecutive functions in the same region. if (LastRegion == region) return LastIsParsed; LastRegion = region; LastIsParsed = ParsedRegions.count(region); if (!LastIsParsed) NewParsedRegions.push_back(region); return LastIsParsed; } void finished() { SessionData.update(NewParsedRegions); } private: PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) { SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc); if (RegionLoc.isInvalid()) { if (isParsedOnceInclude(FE)) { const llvm::sys::fs::UniqueID &ID = FE->getUniqueID(); return PPRegion(ID, 0, FE->getModificationTime()); } return PPRegion(); } const SourceManager &SM = PPRec.getSourceManager(); assert(RegionLoc.isFileID()); FileID RegionFID; unsigned RegionOffset; std::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc); if (RegionFID != FID) { if (isParsedOnceInclude(FE)) { const llvm::sys::fs::UniqueID &ID = FE->getUniqueID(); return PPRegion(ID, 0, FE->getModificationTime()); } return PPRegion(); } const llvm::sys::fs::UniqueID &ID = FE->getUniqueID(); return PPRegion(ID, RegionOffset, FE->getModificationTime()); } bool isParsedOnceInclude(const FileEntry *FE) { return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE); } }; #endif //===----------------------------------------------------------------------===// // IndexPPCallbacks //===----------------------------------------------------------------------===// class IndexPPCallbacks : public PPCallbacks { Preprocessor &PP; IndexingContext &IndexCtx; bool IsMainFileEntered; public: IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx) : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { } void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override { if (IsMainFileEntered) return; SourceManager &SM = PP.getSourceManager(); SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID()); if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) { IsMainFileEntered = true; IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID())); } } void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) override { bool isImport = (IncludeTok.is(tok::identifier) && IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import); IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled, Imported); } /// MacroDefined - This hook is called whenever a macro definition is seen. void MacroDefined(const Token &Id, const MacroDirective *MD) override {} /// MacroUndefined - This hook is called whenever a macro #undef is seen. /// MI is released immediately following this callback. void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD) override {} /// MacroExpands - This is called by when a macro invocation is found. void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override {} /// SourceRangeSkipped - This hook is called when a source range is skipped. /// \param Range The SourceRange that was skipped. The range begins at the /// #if/#else directive and ends after the #endif/#else directive. void SourceRangeSkipped(SourceRange Range) override {} }; //===----------------------------------------------------------------------===// // IndexingConsumer //===----------------------------------------------------------------------===// class IndexingConsumer : public ASTConsumer { IndexingContext &IndexCtx; TUSkipBodyControl *SKCtrl; public: IndexingConsumer(IndexingContext &indexCtx, TUSkipBodyControl *skCtrl) : IndexCtx(indexCtx), SKCtrl(skCtrl) { } // ASTConsumer Implementation void Initialize(ASTContext &Context) override { IndexCtx.setASTContext(Context); IndexCtx.startedTranslationUnit(); } void HandleTranslationUnit(ASTContext &Ctx) override { if (SKCtrl) SKCtrl->finished(); } bool HandleTopLevelDecl(DeclGroupRef DG) override { IndexCtx.indexDeclGroupRef(DG); return !IndexCtx.shouldAbort(); } /// \brief Handle the specified top-level declaration that occurred inside /// and ObjC container. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { // They will be handled after the interface is seen first. IndexCtx.addTUDeclInObjCContainer(D); } /// \brief This is called by the AST reader when deserializing things. /// The default implementation forwards to HandleTopLevelDecl but we don't /// care about them when indexing, so have an empty definition. void HandleInterestingDecl(DeclGroupRef D) override {} void HandleTagDeclDefinition(TagDecl *D) override { if (!IndexCtx.shouldIndexImplicitTemplateInsts()) return; if (IndexCtx.isTemplateImplicitInstantiation(D)) IndexCtx.indexDecl(D); } void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) override { if (!IndexCtx.shouldIndexImplicitTemplateInsts()) return; IndexCtx.indexDecl(D); } bool shouldSkipFunctionBody(Decl *D) override { if (!SKCtrl) { // Always skip bodies. return true; } const SourceManager &SM = IndexCtx.getASTContext().getSourceManager(); SourceLocation Loc = D->getLocation(); if (Loc.isMacroID()) return false; if (SM.isInSystemHeader(Loc)) return true; // always skip bodies from system headers. FileID FID; unsigned Offset; std::tie(FID, Offset) = SM.getDecomposedLoc(Loc); // Don't skip bodies from main files; this may be revisited. if (SM.getMainFileID() == FID) return false; const FileEntry *FE = SM.getFileEntryForID(FID); if (!FE) return false; return SKCtrl->isParsed(Loc, FID, FE); } }; //===----------------------------------------------------------------------===// // CaptureDiagnosticConsumer //===----------------------------------------------------------------------===// class CaptureDiagnosticConsumer : public DiagnosticConsumer { SmallVector<StoredDiagnostic, 4> Errors; public: void HandleDiagnostic(DiagnosticsEngine::Level level, const Diagnostic &Info) override { if (level >= DiagnosticsEngine::Error) Errors.push_back(StoredDiagnostic(level, Info)); } }; //===----------------------------------------------------------------------===// // IndexingFrontendAction //===----------------------------------------------------------------------===// class IndexingFrontendAction : public ASTFrontendAction { IndexingContext IndexCtx; CXTranslationUnit CXTU; SessionSkipBodyData *SKData; std::unique_ptr<TUSkipBodyControl> SKCtrl; public: IndexingFrontendAction(CXClientData clientData, IndexerCallbacks &indexCallbacks, unsigned indexOptions, CXTranslationUnit cxTU, SessionSkipBodyData *skData) : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU), CXTU(cxTU), SKData(skData) { } std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); if (!PPOpts.ImplicitPCHInclude.empty()) { IndexCtx.importedPCH( CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude)); } IndexCtx.setASTContext(CI.getASTContext()); Preprocessor &PP = CI.getPreprocessor(); PP.addPPCallbacks(llvm::make_unique<IndexPPCallbacks>(PP, IndexCtx)); IndexCtx.setPreprocessor(PP); if (SKData) { auto *PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager()); PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec)); SKCtrl = llvm::make_unique<TUSkipBodyControl>(*SKData, *PPRec, PP); } return llvm::make_unique<IndexingConsumer>(IndexCtx, SKCtrl.get()); } void EndSourceFileAction() override { indexDiagnostics(CXTU, IndexCtx); } TranslationUnitKind getTranslationUnitKind() override { if (IndexCtx.shouldIndexImplicitTemplateInsts()) return TU_Complete; else return TU_Prefix; } bool hasCodeCompletionSupport() const override { return false; } }; //===----------------------------------------------------------------------===// // clang_indexSourceFileUnit Implementation //===----------------------------------------------------------------------===// struct IndexSessionData { CXIndex CIdx; std::unique_ptr<SessionSkipBodyData> SkipBodyData; explicit IndexSessionData(CXIndex cIdx) : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {} }; struct IndexSourceFileInfo { CXIndexAction idxAction; CXClientData client_data; IndexerCallbacks *index_callbacks; unsigned index_callbacks_size; unsigned index_options; const char *source_filename; const char *const *command_line_args; int num_command_line_args; ArrayRef<CXUnsavedFile> unsaved_files; CXTranslationUnit *out_TU; unsigned TU_options; CXErrorCode &result; }; } // anonymous namespace static void clang_indexSourceFile_Impl(void *UserData) { const IndexSourceFileInfo *ITUI = static_cast<IndexSourceFileInfo *>(UserData); CXIndexAction cxIdxAction = ITUI->idxAction; CXClientData client_data = ITUI->client_data; IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; unsigned index_callbacks_size = ITUI->index_callbacks_size; unsigned index_options = ITUI->index_options; const char *source_filename = ITUI->source_filename; const char * const *command_line_args = ITUI->command_line_args; int num_command_line_args = ITUI->num_command_line_args; CXTranslationUnit *out_TU = ITUI->out_TU; unsigned TU_options = ITUI->TU_options; if (out_TU) *out_TU = nullptr; bool requestedToGetTU = (out_TU != nullptr); if (!cxIdxAction) { ITUI->result = CXError_InvalidArguments; return; } if (!client_index_callbacks || index_callbacks_size == 0) { ITUI->result = CXError_InvalidArguments; return; } IndexerCallbacks CB; memset(&CB, 0, sizeof(CB)); unsigned ClientCBSize = index_callbacks_size < sizeof(CB) ? index_callbacks_size : sizeof(CB); memcpy(&CB, client_index_callbacks, ClientCBSize); IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction); CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx); if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); bool CaptureDiagnostics = !Logger::isLoggingEnabled(); CaptureDiagnosticConsumer *CaptureDiag = nullptr; if (CaptureDiagnostics) CaptureDiag = new CaptureDiagnosticConsumer(); // Configure the diagnostics. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions, CaptureDiag, /*ShouldOwnClient=*/true)); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > DiagCleanup(Diags.get()); std::unique_ptr<std::vector<const char *>> Args( new std::vector<const char *>()); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > ArgsCleanup(Args.get()); Args->insert(Args->end(), command_line_args, command_line_args + num_command_line_args); // The 'source_filename' argument is optional. If the caller does not // specify it then it is assumed that the source file is specified // in the actual argument list. // Put the source file after command_line_args otherwise if '-x' flag is // present it will be unused. if (source_filename) Args->push_back(source_filename); IntrusiveRefCntPtr<CompilerInvocation> CInvok(createInvocationFromCommandLine(*Args, Diags)); if (!CInvok) return; // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation, llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> > CInvokCleanup(CInvok.get()); if (CInvok->getFrontendOpts().Inputs.empty()) return; typedef SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 8> MemBufferOwner; std::unique_ptr<MemBufferOwner> BufOwner(new MemBufferOwner); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> BufOwnerCleanup( BufOwner.get()); for (auto &UF : ITUI->unsaved_files) { std::unique_ptr<llvm::MemoryBuffer> MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); CInvok->getPreprocessorOpts().addRemappedFile(UF.Filename, MB.get()); BufOwner->push_back(std::move(MB)); } // Since libclang is primarily used by batch tools dealing with // (often very broken) source code, where spell-checking can have a // significant negative impact on performance (particularly when // precompiled headers are involved), we disable it. #ifdef MS_SUPPORT_VARIABLE_LANGOPTS CInvok->getLangOpts()->SpellChecking = false; #endif if (index_options & CXIndexOpt_SuppressWarnings) CInvok->getDiagnosticOpts().IgnoreWarnings = true; ASTUnit *Unit = ASTUnit::create(CInvok.get(), Diags, CaptureDiagnostics, /*UserFilesAreVolatile=*/true); if (!Unit) { ITUI->result = CXError_InvalidArguments; return; } std::unique_ptr<CXTUOwner> CXTU( new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit))); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner> CXTUCleanup(CXTU.get()); // Enable the skip-parsed-bodies optimization only for C++; this may be // revisited. bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) && CInvok->getLangOpts()->CPlusPlus; if (SkipBodies) CInvok->getFrontendOpts().SkipFunctionBodies = true; std::unique_ptr<IndexingFrontendAction> IndexAction; IndexAction.reset(new IndexingFrontendAction(client_data, CB, index_options, CXTU->getTU(), SkipBodies ? IdxSession->SkipBodyData.get() : nullptr)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction> IndexActionCleanup(IndexAction.get()); bool Persistent = requestedToGetTU; bool OnlyLocalDecls = false; bool PrecompilePreamble = false; bool CacheCodeCompletionResults = false; PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts(); PPOpts.AllowPCHWithCompilerErrors = true; if (requestedToGetTU) { OnlyLocalDecls = CXXIdx->getOnlyLocalDecls(); PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble; // FIXME: Add a flag for modules. CacheCodeCompletionResults = TU_options & CXTranslationUnit_CacheCompletionResults; } if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) { PPOpts.DetailedRecord = true; } if (!requestedToGetTU && !CInvok->getLangOpts()->Modules) PPOpts.DetailedRecord = false; DiagnosticErrorTrap DiagTrap(*Diags); bool Success = ASTUnit::LoadFromCompilerInvocationAction( CInvok.get(), CXXIdx->getPCHContainerOperations(), Diags, IndexAction.get(), Unit, Persistent, CXXIdx->getClangResourcesPath(), OnlyLocalDecls, CaptureDiagnostics, PrecompilePreamble, CacheCodeCompletionResults, /*IncludeBriefCommentsInCodeCompletion=*/false, /*UserFilesAreVolatile=*/true); if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics()) printDiagsToStderr(Unit); if (isASTReadError(Unit)) { ITUI->result = CXError_ASTReadError; return; } if (!Success) return; if (out_TU) *out_TU = CXTU->takeTU(); ITUI->result = CXError_Success; } //===----------------------------------------------------------------------===// // clang_indexTranslationUnit Implementation //===----------------------------------------------------------------------===// namespace { struct IndexTranslationUnitInfo { CXIndexAction idxAction; CXClientData client_data; IndexerCallbacks *index_callbacks; unsigned index_callbacks_size; unsigned index_options; CXTranslationUnit TU; int result; }; } // anonymous namespace static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) { Preprocessor &PP = Unit.getPreprocessor(); if (!PP.getPreprocessingRecord()) return; // FIXME: Only deserialize inclusion directives. bool isModuleFile = Unit.isModuleFile(); for (PreprocessedEntity *PPE : Unit.getLocalPreprocessingEntities()) { if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { SourceLocation Loc = ID->getSourceRange().getBegin(); // Modules have synthetic main files as input, give an invalid location // if the location points to such a file. if (isModuleFile && Unit.isInMainFileID(Loc)) Loc = SourceLocation(); IdxCtx.ppIncludedFile(Loc, ID->getFileName(), ID->getFile(), ID->getKind() == InclusionDirective::Import, !ID->wasInQuotes(), ID->importedModule()); } } } static bool topLevelDeclVisitor(void *context, const Decl *D) { IndexingContext &IdxCtx = *static_cast<IndexingContext*>(context); IdxCtx.indexTopLevelDecl(D); if (IdxCtx.shouldAbort()) return false; return true; } static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) { Unit.visitLocalTopLevelDecls(&IdxCtx, topLevelDeclVisitor); } static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) { if (!IdxCtx.hasDiagnosticCallback()) return; CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU); IdxCtx.handleDiagnosticSet(DiagSet); } static void clang_indexTranslationUnit_Impl(void *UserData) { IndexTranslationUnitInfo *ITUI = static_cast<IndexTranslationUnitInfo*>(UserData); CXTranslationUnit TU = ITUI->TU; CXClientData client_data = ITUI->client_data; IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; unsigned index_callbacks_size = ITUI->index_callbacks_size; unsigned index_options = ITUI->index_options; // Set up the initial return value. ITUI->result = CXError_Failure; // Check arguments. if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); ITUI->result = CXError_InvalidArguments; return; } if (!client_index_callbacks || index_callbacks_size == 0) { ITUI->result = CXError_InvalidArguments; return; } CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); IndexerCallbacks CB; memset(&CB, 0, sizeof(CB)); unsigned ClientCBSize = index_callbacks_size < sizeof(CB) ? index_callbacks_size : sizeof(CB); memcpy(&CB, client_index_callbacks, ClientCBSize); std::unique_ptr<IndexingContext> IndexCtx; IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext> IndexCtxCleanup(IndexCtx.get()); std::unique_ptr<IndexingConsumer> IndexConsumer; IndexConsumer.reset(new IndexingConsumer(*IndexCtx, nullptr)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer> IndexConsumerCleanup(IndexConsumer.get()); ASTUnit *Unit = cxtu::getASTUnit(TU); if (!Unit) return; ASTUnit::ConcurrencyCheck Check(*Unit); if (const FileEntry *PCHFile = Unit->getPCHFile()) IndexCtx->importedPCH(PCHFile); FileManager &FileMgr = Unit->getFileManager(); if (Unit->getOriginalSourceFileName().empty()) IndexCtx->enteredMainFile(nullptr); else IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName())); IndexConsumer->Initialize(Unit->getASTContext()); indexPreprocessingRecord(*Unit, *IndexCtx); indexTranslationUnit(*Unit, *IndexCtx); indexDiagnostics(TU, *IndexCtx); ITUI->result = CXError_Success; } //===----------------------------------------------------------------------===// // libclang public APIs. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) { return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory; } const CXIdxObjCContainerDeclInfo * clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) { if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const ObjCContainerDeclInfo * ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI)) return &ContInfo->ObjCContDeclInfo; return nullptr; } const CXIdxObjCInterfaceDeclInfo * clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) { if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const ObjCInterfaceDeclInfo * InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) return &InterInfo->ObjCInterDeclInfo; return nullptr; } const CXIdxObjCCategoryDeclInfo * clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){ if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const ObjCCategoryDeclInfo * CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) return &CatInfo->ObjCCatDeclInfo; return nullptr; } const CXIdxObjCProtocolRefListInfo * clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) { if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const ObjCInterfaceDeclInfo * InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) return InterInfo->ObjCInterDeclInfo.protocols; if (const ObjCProtocolDeclInfo * ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI)) return &ProtInfo->ObjCProtoRefListInfo; if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) return CatInfo->ObjCCatDeclInfo.protocols; return nullptr; } const CXIdxObjCPropertyDeclInfo * clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) { if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI)) return &PropInfo->ObjCPropDeclInfo; return nullptr; } const CXIdxIBOutletCollectionAttrInfo * clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) { if (!AInfo) return nullptr; const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo); if (const IBOutletCollectionInfo * IBInfo = dyn_cast<IBOutletCollectionInfo>(DI)) return &IBInfo->IBCollInfo; return nullptr; } const CXIdxCXXClassDeclInfo * clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) { if (!DInfo) return nullptr; const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI)) return &ClassInfo->CXXClassInfo; return nullptr; } CXIdxClientContainer clang_index_getClientContainer(const CXIdxContainerInfo *info) { if (!info) return nullptr; const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); return Container->IndexCtx->getClientContainerForDC(Container->DC); } void clang_index_setClientContainer(const CXIdxContainerInfo *info, CXIdxClientContainer client) { if (!info) return; const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); Container->IndexCtx->addContainerInMap(Container->DC, client); } CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) { if (!info) return nullptr; const EntityInfo *Entity = static_cast<const EntityInfo *>(info); return Entity->IndexCtx->getClientEntity(Entity->Dcl); } void clang_index_setClientEntity(const CXIdxEntityInfo *info, CXIdxClientEntity client) { if (!info) return; const EntityInfo *Entity = static_cast<const EntityInfo *>(info); Entity->IndexCtx->setClientEntity(Entity->Dcl, client); } CXIndexAction clang_IndexAction_create(CXIndex CIdx) { return new IndexSessionData(CIdx); } void clang_IndexAction_dispose(CXIndexAction idxAction) { if (idxAction) delete static_cast<IndexSessionData *>(idxAction); } int clang_indexSourceFile(CXIndexAction idxAction, CXClientData client_data, IndexerCallbacks *index_callbacks, unsigned index_callbacks_size, unsigned index_options, const char *source_filename, const char * const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, CXTranslationUnit *out_TU, unsigned TU_options) { LOG_FUNC_SECTION { *Log << source_filename << ": "; for (int i = 0; i != num_command_line_args; ++i) *Log << command_line_args[i] << " "; } if (num_unsaved_files && !unsaved_files) return CXError_InvalidArguments; CXErrorCode result = CXError_Failure; IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks, index_callbacks_size, index_options, source_filename, command_line_args, num_command_line_args, llvm::makeArrayRef(unsaved_files, num_unsaved_files), out_TU, TU_options, result}; if (getenv("LIBCLANG_NOTHREADS")) { clang_indexSourceFile_Impl(&ITUI); return result; } llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) { fprintf(stderr, "libclang: crash detected during indexing source file: {\n"); fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); fprintf(stderr, " 'command_line_args' : ["); for (int i = 0; i != num_command_line_args; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "'%s'", command_line_args[i]); } fprintf(stderr, "],\n"); fprintf(stderr, " 'unsaved_files' : ["); for (unsigned i = 0; i != num_unsaved_files; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, unsaved_files[i].Length); } fprintf(stderr, "],\n"); fprintf(stderr, " 'options' : %d,\n", TU_options); fprintf(stderr, "}\n"); return 1; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { if (out_TU) PrintLibclangResourceUsage(*out_TU); } return result; } int clang_indexTranslationUnit(CXIndexAction idxAction, CXClientData client_data, IndexerCallbacks *index_callbacks, unsigned index_callbacks_size, unsigned index_options, CXTranslationUnit TU) { LOG_FUNC_SECTION { *Log << TU; } IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks, index_callbacks_size, index_options, TU, 0 }; if (getenv("LIBCLANG_NOTHREADS")) { clang_indexTranslationUnit_Impl(&ITUI); return ITUI.result; } llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) { fprintf(stderr, "libclang: crash detected during indexing TU\n"); return 1; } return ITUI.result; } void clang_indexLoc_getFileLocation(CXIdxLoc location, CXIdxClientFile *indexFile, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (indexFile) *indexFile = nullptr; if (file) *file = nullptr; if (line) *line = 0; if (column) *column = 0; if (offset) *offset = 0; SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) return; IndexingContext &IndexCtx = *static_cast<IndexingContext*>(location.ptr_data[0]); IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset); } CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) { SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); if (!location.ptr_data[0] || Loc.isInvalid()) return clang_getNullLocation(); IndexingContext &IndexCtx = *static_cast<IndexingContext*>(location.ptr_data[0]); return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc); } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CMakeLists.txt
set(LLVM_OPTIONAL_SOURCES ARCMigrate.cpp) # HLSL Change - ignore file if (WIN32) set (HLSL_IGNORE_SOURCES BuildSystem.cpp ) set(SOURCES # ARCMigrate.cpp # HLSL Change - remove ARCMigrate CIndex.cpp CIndexCXX.cpp CIndexCodeCompletion.cpp CIndexDiagnostic.cpp CIndexHigh.cpp CIndexInclusionStack.cpp CIndexUSRs.cpp CIndexer.cpp CXComment.cpp CXCursor.cpp CXCompilationDatabase.cpp CXLoadedDiagnostic.cpp CXSourceLocation.cpp CXStoredDiagnostic.cpp CXString.cpp CXType.cpp IndexBody.cpp IndexDecl.cpp IndexTypeSourceInfo.cpp Indexing.cpp IndexingContext.cpp dxcisenseimpl.cpp # HLSL Change dxcrewriteunused.cpp # HLSL Change ADDITIONAL_HEADERS CIndexDiagnostic.h CIndexer.h CXCursor.h CXLoadedDiagnostic.h CXSourceLocation.h CXString.h CXTranslationUnit.h CXType.h Index_Internal.h IndexingContext.h ../../include/clang-c/Index.h ) else () set(SOURCES # ARCMigrate.cpp # HLSL Change - remove ARCMigrate CIndex.cpp CIndexCXX.cpp CIndexCodeCompletion.cpp CIndexDiagnostic.cpp CIndexHigh.cpp CIndexInclusionStack.cpp CIndexUSRs.cpp CIndexer.cpp CXComment.cpp CXCursor.cpp CXCompilationDatabase.cpp CXLoadedDiagnostic.cpp CXSourceLocation.cpp CXStoredDiagnostic.cpp CXString.cpp CXType.cpp IndexBody.cpp IndexDecl.cpp IndexTypeSourceInfo.cpp Indexing.cpp IndexingContext.cpp dxcisenseimpl.cpp # HLSL Change dxcrewriteunused.cpp # HLSL Change ADDITIONAL_HEADERS CIndexDiagnostic.h CIndexer.h CXCursor.h CXLoadedDiagnostic.h CXSourceLocation.h CXString.h CXTranslationUnit.h CXType.h Index_Internal.h IndexingContext.h ../../include/clang-c/Index.h ) set (HLSL_IGNORE_SOURCES BuildSystem.cpp ) endif(WIN32) set(LIBS clangAST clangBasic clangFrontend clangIndex clangLex clangSema clangTooling ) if (0 AND CLANG_ENABLE_ARCMT) # HLSL Change - remove ARC support list(APPEND LIBS clangARCMigrate) endif () find_library(DL_LIBRARY_PATH dl) if (DL_LIBRARY_PATH) list(APPEND LIBS dl) endif() option(LIBCLANG_BUILD_STATIC "Build libclang as a static library (in addition to a shared one)" OFF) set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/libclang.exports) if(MSVC) # Avoid LNK4197 not to spceify libclang.def here. # Each functions is exported as "dllexport" in include/clang-c. # KB835326 set(LLVM_EXPORTED_SYMBOL_FILE) endif() # HLSL Change Starts # Add a definition for the link type. add_definitions(-DCINDEX_LINKAGE=) add_definitions(-DLIBCLANG_CC=) set(ENABLE_STATIC STATIC) # HLSL Change Ends if( 0 AND LLVM_ENABLE_PIC ) # HLSL Change - disable DLL, we only use the static lib set(ENABLE_SHARED SHARED) endif() if((NOT LLVM_ENABLE_PIC OR LIBCLANG_BUILD_STATIC) AND NOT WIN32) set(ENABLE_STATIC STATIC) endif() if(WIN32) set(output_name "libclang") else() set(output_name "clang") endif() if(1) # HLSL Change don't build the static target like this add_clang_library(libclang ${ENABLE_SHARED} ${ENABLE_STATIC} OUTPUT_NAME ${output_name} ${SOURCES} # DEPENDS clang-headers - HLSL Change LINK_LIBS ${LIBS} LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Core Support MSSupport ) if(ENABLE_SHARED) if(WIN32) set_target_properties(libclang PROPERTIES VERSION ${LIBCLANG_LIBRARY_VERSION} DEFINE_SYMBOL _CINDEX_LIB_) else() set_target_properties(libclang PROPERTIES VERSION ${LIBCLANG_LIBRARY_VERSION} DEFINE_SYMBOL _CINDEX_LIB_) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(LIBCLANG_LINK_FLAGS " -Wl,-compatibility_version -Wl,1") if (DEFINED ${LLVM_SUBMIT_VERSION}) set(LIBCLANG_LINK_FLAGS "${LIBCLANG_LINK_FLAGS} -Wl,-current_version -Wl,${LLVM_SUBMIT_VERSION}.${LLVM_SUBMIT_SUBVERSION}") endif() set_property(TARGET libclang APPEND_STRING PROPERTY LINK_FLAGS ${LIBCLANG_LINK_FLAGS}) endif() endif() endif() # HLSL Change add_dependencies(libclang TablegenHLSLOptions) # HLSL Change # HLSL Change Starts # add_clang_library(${LIBCLANG_STATIC_TARGET_NAME} STATIC ${SOURCES}) # target_link_libraries(${LIBCLANG_STATIC_TARGET_NAME} ${LIBS}) # add_dependencies(${LIBCLANG_STATIC_TARGET_NAME} ${GENERATED_HEADERS} clang-headers) # HLSL Change Ends
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/Index_Internal.h
//===- CXString.h - Routines for manipulating CXStrings -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXStrings. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_INDEX_INTERNAL_H #define LLVM_CLANG_TOOLS_LIBCLANG_INDEX_INTERNAL_H #include "clang-c/Index.h" #ifndef __has_feature #define __has_feature(x) 0 #endif #if __has_feature(blocks) #define INVOKE_BLOCK2(block, arg1, arg2) block(arg1, arg2) #else // If we are compiled with a compiler that doesn't have native blocks support, // define and call the block manually. #define INVOKE_BLOCK2(block, arg1, arg2) block->invoke(block, arg1, arg2) typedef struct _CXCursorAndRangeVisitorBlock { void *isa; int flags; int reserved; enum CXVisitorResult (*invoke)(_CXCursorAndRangeVisitorBlock *, CXCursor, CXSourceRange); } *CXCursorAndRangeVisitorBlock; #endif // !__has_feature(blocks) /// \brief The result of comparing two source ranges. enum RangeComparisonResult { /// \brief Either the ranges overlap or one of the ranges is invalid. RangeOverlap, /// \brief The first range ends before the second range starts. RangeBefore, /// \brief The first range starts after the second range ends. RangeAfter }; #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexCodeCompletion.cpp
//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Clang-C Source Indexing library hooks for // code completion. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CIndexDiagnostic.h" #include "CLog.h" #include "CXCursor.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Type.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Program.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include <atomic> #include <cstdio> #include <cstdlib> #include <string> #ifdef UDP_CODE_COMPLETION_LOGGER #include "clang/Basic/Version.h" #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #endif using namespace clang; using namespace clang::cxindex; // extern "C" { // HLSL Change -Don't use c linkage. enum CXCompletionChunkKind clang_getCompletionChunkKind(CXCompletionString completion_string, unsigned chunk_number) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; if (!CCStr || chunk_number >= CCStr->size()) return CXCompletionChunk_Text; switch ((*CCStr)[chunk_number].Kind) { case CodeCompletionString::CK_TypedText: return CXCompletionChunk_TypedText; case CodeCompletionString::CK_Text: return CXCompletionChunk_Text; case CodeCompletionString::CK_Optional: return CXCompletionChunk_Optional; case CodeCompletionString::CK_Placeholder: return CXCompletionChunk_Placeholder; case CodeCompletionString::CK_Informative: return CXCompletionChunk_Informative; case CodeCompletionString::CK_ResultType: return CXCompletionChunk_ResultType; case CodeCompletionString::CK_CurrentParameter: return CXCompletionChunk_CurrentParameter; case CodeCompletionString::CK_LeftParen: return CXCompletionChunk_LeftParen; case CodeCompletionString::CK_RightParen: return CXCompletionChunk_RightParen; case CodeCompletionString::CK_LeftBracket: return CXCompletionChunk_LeftBracket; case CodeCompletionString::CK_RightBracket: return CXCompletionChunk_RightBracket; case CodeCompletionString::CK_LeftBrace: return CXCompletionChunk_LeftBrace; case CodeCompletionString::CK_RightBrace: return CXCompletionChunk_RightBrace; case CodeCompletionString::CK_LeftAngle: return CXCompletionChunk_LeftAngle; case CodeCompletionString::CK_RightAngle: return CXCompletionChunk_RightAngle; case CodeCompletionString::CK_Comma: return CXCompletionChunk_Comma; case CodeCompletionString::CK_Colon: return CXCompletionChunk_Colon; case CodeCompletionString::CK_SemiColon: return CXCompletionChunk_SemiColon; case CodeCompletionString::CK_Equal: return CXCompletionChunk_Equal; case CodeCompletionString::CK_HorizontalSpace: return CXCompletionChunk_HorizontalSpace; case CodeCompletionString::CK_VerticalSpace: return CXCompletionChunk_VerticalSpace; } llvm_unreachable("Invalid CompletionKind!"); } CXString clang_getCompletionChunkText(CXCompletionString completion_string, unsigned chunk_number) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; if (!CCStr || chunk_number >= CCStr->size()) return cxstring::createNull(); switch ((*CCStr)[chunk_number].Kind) { case CodeCompletionString::CK_TypedText: case CodeCompletionString::CK_Text: case CodeCompletionString::CK_Placeholder: case CodeCompletionString::CK_CurrentParameter: case CodeCompletionString::CK_Informative: case CodeCompletionString::CK_LeftParen: case CodeCompletionString::CK_RightParen: case CodeCompletionString::CK_LeftBracket: case CodeCompletionString::CK_RightBracket: case CodeCompletionString::CK_LeftBrace: case CodeCompletionString::CK_RightBrace: case CodeCompletionString::CK_LeftAngle: case CodeCompletionString::CK_RightAngle: case CodeCompletionString::CK_Comma: case CodeCompletionString::CK_ResultType: case CodeCompletionString::CK_Colon: case CodeCompletionString::CK_SemiColon: case CodeCompletionString::CK_Equal: case CodeCompletionString::CK_HorizontalSpace: case CodeCompletionString::CK_VerticalSpace: return cxstring::createRef((*CCStr)[chunk_number].Text); case CodeCompletionString::CK_Optional: // Note: treated as an empty text block. return cxstring::createEmpty(); } llvm_unreachable("Invalid CodeCompletionString Kind!"); } CXCompletionString clang_getCompletionChunkCompletionString(CXCompletionString completion_string, unsigned chunk_number) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; if (!CCStr || chunk_number >= CCStr->size()) return nullptr; switch ((*CCStr)[chunk_number].Kind) { case CodeCompletionString::CK_TypedText: case CodeCompletionString::CK_Text: case CodeCompletionString::CK_Placeholder: case CodeCompletionString::CK_CurrentParameter: case CodeCompletionString::CK_Informative: case CodeCompletionString::CK_LeftParen: case CodeCompletionString::CK_RightParen: case CodeCompletionString::CK_LeftBracket: case CodeCompletionString::CK_RightBracket: case CodeCompletionString::CK_LeftBrace: case CodeCompletionString::CK_RightBrace: case CodeCompletionString::CK_LeftAngle: case CodeCompletionString::CK_RightAngle: case CodeCompletionString::CK_Comma: case CodeCompletionString::CK_ResultType: case CodeCompletionString::CK_Colon: case CodeCompletionString::CK_SemiColon: case CodeCompletionString::CK_Equal: case CodeCompletionString::CK_HorizontalSpace: case CodeCompletionString::CK_VerticalSpace: return nullptr; case CodeCompletionString::CK_Optional: // Note: treated as an empty text block. return (*CCStr)[chunk_number].Optional; } llvm_unreachable("Invalid CompletionKind!"); } unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; return CCStr? CCStr->size() : 0; } unsigned clang_getCompletionPriority(CXCompletionString completion_string) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely); } enum CXAvailabilityKind clang_getCompletionAvailability(CXCompletionString completion_string) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability()) : CXAvailability_Available; } unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; return CCStr ? CCStr->getAnnotationCount() : 0; } CXString clang_getCompletionAnnotation(CXCompletionString completion_string, unsigned annotation_number) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number)) : cxstring::createNull(); } CXString clang_getCompletionParent(CXCompletionString completion_string, CXCursorKind *kind) { if (kind) *kind = CXCursor_NotImplemented; CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; if (!CCStr) return cxstring::createNull(); return cxstring::createRef(CCStr->getParentContextName()); } CXString clang_getCompletionBriefComment(CXCompletionString completion_string) { CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; if (!CCStr) return cxstring::createNull(); return cxstring::createRef(CCStr->getBriefComment()); } namespace { /// \brief The CXCodeCompleteResults structure we allocate internally; /// the client only sees the initial CXCodeCompleteResults structure. /// /// Normally, clients of CXString shouldn't care whether or not a CXString is /// managed by a pool or by explicitly malloc'ed memory. But /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can /// not rely on the StringPool in the TU. struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults { AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr); ~AllocatedCXCodeCompleteResults(); /// \brief Diagnostics produced while performing code completion. SmallVector<StoredDiagnostic, 8> Diagnostics; /// \brief Allocated API-exposed wrappters for Diagnostics. SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; /// \brief Diag object IntrusiveRefCntPtr<DiagnosticsEngine> Diag; /// \brief Language options used to adjust source locations. LangOptions LangOpts; /// \brief File manager, used for diagnostics. IntrusiveRefCntPtr<FileManager> FileMgr; /// \brief Source manager, used for diagnostics. IntrusiveRefCntPtr<SourceManager> SourceMgr; /// \brief Temporary files that should be removed once we have finished /// with the code-completion results. std::vector<std::string> TemporaryFiles; /// \brief Temporary buffers that will be deleted once we have finished with /// the code-completion results. SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers; /// \brief Allocator used to store globally cached code-completion results. IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator> CachedCompletionAllocator; /// \brief Allocator used to store code completion results. IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator> CodeCompletionAllocator; /// \brief Context under which completion occurred. enum clang::CodeCompletionContext::Kind ContextKind; /// \brief A bitfield representing the acceptable completions for the /// current context. unsigned long long Contexts; /// \brief The kind of the container for the current context for completions. enum CXCursorKind ContainerKind; /// \brief The USR of the container for the current context for completions. std::string ContainerUSR; /// \brief a boolean value indicating whether there is complete information /// about the container unsigned ContainerIsIncomplete; /// \brief A string containing the Objective-C selector entered thus far for a /// message send. std::string Selector; }; } // end anonymous namespace /// \brief Tracks the number of code-completion result objects that are /// currently active. /// /// Used for debugging purposes only. static std::atomic<unsigned> CodeCompletionResultObjects; AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults( IntrusiveRefCntPtr<FileManager> FileMgr) : CXCodeCompleteResults(), DiagOpts(new DiagnosticOptions), Diag(new DiagnosticsEngine( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)), FileMgr(FileMgr), SourceMgr(new SourceManager(*Diag, *FileMgr)), CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator), Contexts(CXCompletionContext_Unknown), ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) { if (getenv("LIBCLANG_OBJTRACKING")) fprintf(stderr, "+++ %u completion results\n", ++CodeCompletionResultObjects); } AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() { llvm::DeleteContainerPointers(DiagnosticsWrappers); delete [] Results; for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) llvm::sys::fs::remove(TemporaryFiles[I]); for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I) delete TemporaryBuffers[I]; if (getenv("LIBCLANG_OBJTRACKING")) fprintf(stderr, "--- %u completion results\n", --CodeCompletionResultObjects); } // } // end extern "C" // HLSL Change -Don't use c linkage. static unsigned long long getContextsForContextKind( enum CodeCompletionContext::Kind kind, Sema &S) { unsigned long long contexts = 0; switch (kind) { case CodeCompletionContext::CCC_OtherWithMacros: { //We can allow macros here, but we don't know what else is permissible //So we'll say the only thing permissible are macros contexts = CXCompletionContext_MacroName; break; } case CodeCompletionContext::CCC_TopLevel: case CodeCompletionContext::CCC_ObjCIvarList: case CodeCompletionContext::CCC_ClassStructUnion: case CodeCompletionContext::CCC_Type: { contexts = CXCompletionContext_AnyType | CXCompletionContext_ObjCInterface; if (S.getLangOpts().CPlusPlus) { contexts |= CXCompletionContext_EnumTag | CXCompletionContext_UnionTag | CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; } break; } case CodeCompletionContext::CCC_Statement: { contexts = CXCompletionContext_AnyType | CXCompletionContext_ObjCInterface | CXCompletionContext_AnyValue; if (S.getLangOpts().CPlusPlus) { contexts |= CXCompletionContext_EnumTag | CXCompletionContext_UnionTag | CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; } break; } case CodeCompletionContext::CCC_Expression: { contexts = CXCompletionContext_AnyValue; if (S.getLangOpts().CPlusPlus) { contexts |= CXCompletionContext_AnyType | CXCompletionContext_ObjCInterface | CXCompletionContext_EnumTag | CXCompletionContext_UnionTag | CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; } break; } case CodeCompletionContext::CCC_ObjCMessageReceiver: { contexts = CXCompletionContext_ObjCObjectValue | CXCompletionContext_ObjCSelectorValue | CXCompletionContext_ObjCInterface; if (S.getLangOpts().CPlusPlus) { contexts |= CXCompletionContext_CXXClassTypeValue | CXCompletionContext_AnyType | CXCompletionContext_EnumTag | CXCompletionContext_UnionTag | CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; } break; } case CodeCompletionContext::CCC_DotMemberAccess: { contexts = CXCompletionContext_DotMemberAccess; break; } case CodeCompletionContext::CCC_ArrowMemberAccess: { contexts = CXCompletionContext_ArrowMemberAccess; break; } case CodeCompletionContext::CCC_ObjCPropertyAccess: { contexts = CXCompletionContext_ObjCPropertyAccess; break; } case CodeCompletionContext::CCC_EnumTag: { contexts = CXCompletionContext_EnumTag | CXCompletionContext_NestedNameSpecifier; break; } case CodeCompletionContext::CCC_UnionTag: { contexts = CXCompletionContext_UnionTag | CXCompletionContext_NestedNameSpecifier; break; } case CodeCompletionContext::CCC_ClassOrStructTag: { contexts = CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; break; } case CodeCompletionContext::CCC_ObjCProtocolName: { contexts = CXCompletionContext_ObjCProtocol; break; } case CodeCompletionContext::CCC_Namespace: { contexts = CXCompletionContext_Namespace; break; } case CodeCompletionContext::CCC_PotentiallyQualifiedName: { contexts = CXCompletionContext_NestedNameSpecifier; break; } case CodeCompletionContext::CCC_MacroNameUse: { contexts = CXCompletionContext_MacroName; break; } case CodeCompletionContext::CCC_NaturalLanguage: { contexts = CXCompletionContext_NaturalLanguage; break; } case CodeCompletionContext::CCC_SelectorName: { contexts = CXCompletionContext_ObjCSelectorName; break; } case CodeCompletionContext::CCC_ParenthesizedExpression: { contexts = CXCompletionContext_AnyType | CXCompletionContext_ObjCInterface | CXCompletionContext_AnyValue; if (S.getLangOpts().CPlusPlus) { contexts |= CXCompletionContext_EnumTag | CXCompletionContext_UnionTag | CXCompletionContext_StructTag | CXCompletionContext_ClassTag | CXCompletionContext_NestedNameSpecifier; } break; } case CodeCompletionContext::CCC_ObjCInstanceMessage: { contexts = CXCompletionContext_ObjCInstanceMessage; break; } case CodeCompletionContext::CCC_ObjCClassMessage: { contexts = CXCompletionContext_ObjCClassMessage; break; } case CodeCompletionContext::CCC_ObjCInterfaceName: { contexts = CXCompletionContext_ObjCInterface; break; } case CodeCompletionContext::CCC_ObjCCategoryName: { contexts = CXCompletionContext_ObjCCategory; break; } case CodeCompletionContext::CCC_Other: case CodeCompletionContext::CCC_ObjCInterface: case CodeCompletionContext::CCC_ObjCImplementation: case CodeCompletionContext::CCC_Name: case CodeCompletionContext::CCC_MacroName: case CodeCompletionContext::CCC_PreprocessorExpression: case CodeCompletionContext::CCC_PreprocessorDirective: case CodeCompletionContext::CCC_TypeQualifiers: { //Only Clang results should be accepted, so we'll set all of the other //context bits to 0 (i.e. the empty set) contexts = CXCompletionContext_Unexposed; break; } case CodeCompletionContext::CCC_Recovery: { //We don't know what the current context is, so we'll return unknown //This is the equivalent of setting all of the other context bits contexts = CXCompletionContext_Unknown; break; } } return contexts; } namespace { class CaptureCompletionResults : public CodeCompleteConsumer { AllocatedCXCodeCompleteResults &AllocatedResults; CodeCompletionTUInfo CCTUInfo; SmallVector<CXCompletionResult, 16> StoredResults; CXTranslationUnit *TU; public: CaptureCompletionResults(const CodeCompleteOptions &Opts, AllocatedCXCodeCompleteResults &Results, CXTranslationUnit *TranslationUnit) : CodeCompleteConsumer(Opts, false), AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator), TU(TranslationUnit) { } ~CaptureCompletionResults() override { Finish(); } void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) override { StoredResults.reserve(StoredResults.size() + NumResults); for (unsigned I = 0; I != NumResults; ++I) { CodeCompletionString *StoredCompletion = Results[I].CreateCodeCompletionString(S, Context, getAllocator(), getCodeCompletionTUInfo(), includeBriefComments()); CXCompletionResult R; R.CursorKind = Results[I].CursorKind; R.CompletionString = StoredCompletion; StoredResults.push_back(R); } enum CodeCompletionContext::Kind contextKind = Context.getKind(); AllocatedResults.ContextKind = contextKind; AllocatedResults.Contexts = getContextsForContextKind(contextKind, S); AllocatedResults.Selector = ""; ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents(); for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(), E = SelIdents.end(); I != E; ++I) { if (IdentifierInfo *selIdent = *I) AllocatedResults.Selector += selIdent->getName(); AllocatedResults.Selector += ":"; } QualType baseType = Context.getBaseType(); NamedDecl *D = nullptr; if (!baseType.isNull()) { // Get the declaration for a class/struct/union/enum type if (const TagType *Tag = baseType->getAs<TagType>()) D = Tag->getDecl(); // Get the @interface declaration for a (possibly-qualified) Objective-C // object pointer type, e.g., NSString* else if (const ObjCObjectPointerType *ObjPtr = baseType->getAs<ObjCObjectPointerType>()) D = ObjPtr->getInterfaceDecl(); // Get the @interface declaration for an Objective-C object type else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>()) D = Obj->getInterface(); // Get the class for a C++ injected-class-name else if (const InjectedClassNameType *Injected = baseType->getAs<InjectedClassNameType>()) D = Injected->getDecl(); } if (D != nullptr) { CXCursor cursor = cxcursor::MakeCXCursor(D, *TU); AllocatedResults.ContainerKind = clang_getCursorKind(cursor); CXString CursorUSR = clang_getCursorUSR(cursor); AllocatedResults.ContainerUSR = clang_getCString(CursorUSR); clang_disposeString(CursorUSR); const Type *type = baseType.getTypePtrOrNull(); if (type) { AllocatedResults.ContainerIsIncomplete = type->isIncompleteType(); } else { AllocatedResults.ContainerIsIncomplete = 1; } } else { AllocatedResults.ContainerKind = CXCursor_InvalidCode; AllocatedResults.ContainerUSR.clear(); AllocatedResults.ContainerIsIncomplete = 1; } } void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates) override { StoredResults.reserve(StoredResults.size() + NumCandidates); for (unsigned I = 0; I != NumCandidates; ++I) { CodeCompletionString *StoredCompletion = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(), getCodeCompletionTUInfo(), includeBriefComments()); CXCompletionResult R; R.CursorKind = CXCursor_OverloadCandidate; R.CompletionString = StoredCompletion; StoredResults.push_back(R); } } CodeCompletionAllocator &getAllocator() override { return *AllocatedResults.CodeCompletionAllocator; } CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;} private: void Finish() { AllocatedResults.Results = new CXCompletionResult [StoredResults.size()]; AllocatedResults.NumResults = StoredResults.size(); std::memcpy(AllocatedResults.Results, StoredResults.data(), StoredResults.size() * sizeof(CXCompletionResult)); StoredResults.clear(); } }; } // extern "C" { // HLSL Change -Don't use c linkage. struct CodeCompleteAtInfo { CXTranslationUnit TU; const char *complete_filename; unsigned complete_line; unsigned complete_column; ArrayRef<CXUnsavedFile> unsaved_files; unsigned options; CXCodeCompleteResults *result; }; static void clang_codeCompleteAt_Impl(void *UserData) { CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData); CXTranslationUnit TU = CCAI->TU; const char *complete_filename = CCAI->complete_filename; unsigned complete_line = CCAI->complete_line; unsigned complete_column = CCAI->complete_column; unsigned options = CCAI->options; bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments; CCAI->result = nullptr; #ifdef UDP_CODE_COMPLETION_LOGGER #ifdef UDP_CODE_COMPLETION_LOGGER_PORT const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime(); #endif #endif bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr; if (cxtu::isNotUsableTU(TU)) { LOG_BAD_TU(TU); return; } ASTUnit *AST = cxtu::getASTUnit(TU); if (!AST) return; CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) setThreadBackgroundPriority(); ASTUnit::ConcurrencyCheck Check(*AST); // Perform the remapping of source files. SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; for (auto &UF : CCAI->unsaved_files) { std::unique_ptr<llvm::MemoryBuffer> MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release())); } if (EnableLogging) { // FIXME: Add logging. } // Parse the resulting source file to find code-completion results. AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults( &AST->getFileManager()); Results->Results = nullptr; Results->NumResults = 0; // Create a code-completion consumer to capture the results. CodeCompleteOptions Opts; Opts.IncludeBriefComments = IncludeBriefComments; CaptureCompletionResults Capture(Opts, *Results, &TU); // Perform completion. AST->CodeComplete(complete_filename, complete_line, complete_column, RemappedFiles, (options & CXCodeComplete_IncludeMacros), (options & CXCodeComplete_IncludeCodePatterns), IncludeBriefComments, Capture, CXXIdx->getPCHContainerOperations(), *Results->Diag, Results->LangOpts, *Results->SourceMgr, *Results->FileMgr, Results->Diagnostics, Results->TemporaryBuffers); Results->DiagnosticsWrappers.resize(Results->Diagnostics.size()); // Keep a reference to the allocator used for cached global completions, so // that we can be sure that the memory used by our code completion strings // doesn't get freed due to subsequent reparses (while the code completion // results are still active). Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator(); #ifdef UDP_CODE_COMPLETION_LOGGER #ifdef UDP_CODE_COMPLETION_LOGGER_PORT const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime(); SmallString<256> LogResult; llvm::raw_svector_ostream os(LogResult); // Figure out the language and whether or not it uses PCH. const char *lang = 0; bool usesPCH = false; for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end(); I != E; ++I) { if (*I == 0) continue; if (strcmp(*I, "-x") == 0) { if (I + 1 != E) { lang = *(++I); continue; } } else if (strcmp(*I, "-include") == 0) { if (I+1 != E) { const char *arg = *(++I); SmallString<512> pchName; { llvm::raw_svector_ostream os(pchName); os << arg << ".pth"; } pchName.push_back('\0'); struct stat stat_results; if (stat(pchName.str().c_str(), &stat_results) == 0) usesPCH = true; continue; } } } os << "{ "; os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime()); os << ", \"numRes\": " << Results->NumResults; os << ", \"diags\": " << Results->Diagnostics.size(); os << ", \"pch\": " << (usesPCH ? "true" : "false"); os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"'; const char *name = getlogin(); os << ", \"user\": \"" << (name ? name : "unknown") << '"'; os << ", \"clangVer\": \"" << getClangFullVersion() << '"'; os << " }"; StringRef res = os.str(); if (res.size() > 0) { do { // Setup the UDP socket. struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT); if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER, &servaddr.sin_addr) <= 0) break; int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) break; sendto(sockfd, res.data(), res.size(), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); close(sockfd); } while (false); } #endif #endif CCAI->result = Results; } CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, const char *complete_filename, unsigned complete_line, unsigned complete_column, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options) { LOG_FUNC_SECTION { *Log << TU << ' ' << complete_filename << ':' << complete_line << ':' << complete_column; } if (num_unsaved_files && !unsaved_files) return nullptr; CodeCompleteAtInfo CCAI = {TU, complete_filename, complete_line, complete_column, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, nullptr}; // HLSL Change - Force code completion to run on current thread. if (true || getenv("LIBCLANG_NOTHREADS")) { clang_codeCompleteAt_Impl(&CCAI); return CCAI.result; } llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) { fprintf(stderr, "libclang: crash detected in code completion\n"); cxtu::getASTUnit(TU)->setUnsafeToFree(true); return nullptr; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) PrintLibclangResourceUsage(TU); return CCAI.result; } unsigned clang_defaultCodeCompleteOptions(void) { return CXCodeComplete_IncludeMacros; } void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) { if (!ResultsIn) return; AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); delete Results; } unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); if (!Results) return 0; return Results->Diagnostics.size(); } CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn, unsigned Index) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); if (!Results || Index >= Results->Diagnostics.size()) return nullptr; CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index]; if (!Diag) Results->DiagnosticsWrappers[Index] = Diag = new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts); return Diag; } unsigned long long clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); if (!Results) return 0; return Results->Contexts; } enum CXCursorKind clang_codeCompleteGetContainerKind( CXCodeCompleteResults *ResultsIn, unsigned *IsIncomplete) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); if (!Results) return CXCursor_InvalidCode; if (IsIncomplete != nullptr) { *IsIncomplete = Results->ContainerIsIncomplete; } return Results->ContainerKind; } CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); if (!Results) return cxstring::createEmpty(); return cxstring::createRef(Results->ContainerUSR.c_str()); } CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) { AllocatedCXCodeCompleteResults *Results = static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); if (!Results) return cxstring::createEmpty(); return cxstring::createDup(Results->Selector); } // } // end extern "C" // HLSL Change -Don't use c linkage. /// \brief Simple utility function that appends a \p New string to the given /// \p Old string, using the \p Buffer for storage. /// /// \param Old The string to which we are appending. This parameter will be /// updated to reflect the complete string. /// /// /// \param New The string to append to \p Old. /// /// \param Buffer A buffer that stores the actual, concatenated string. It will /// be used if the old string is already-non-empty. static void AppendToString(StringRef &Old, StringRef New, SmallString<256> &Buffer) { if (Old.empty()) { Old = New; return; } if (Buffer.empty()) Buffer.append(Old.begin(), Old.end()); Buffer.append(New.begin(), New.end()); Old = Buffer.str(); } /// \brief Get the typed-text blocks from the given code-completion string /// and return them as a single string. /// /// \param String The code-completion string whose typed-text blocks will be /// concatenated. /// /// \param Buffer A buffer used for storage of the completed name. static StringRef GetTypedName(CodeCompletionString *String, SmallString<256> &Buffer) { StringRef Result; for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end(); C != CEnd; ++C) { if (C->Kind == CodeCompletionString::CK_TypedText) AppendToString(Result, C->Text, Buffer); } return Result; } namespace { struct OrderCompletionResults { bool operator()(const CXCompletionResult &XR, const CXCompletionResult &YR) const { CodeCompletionString *X = (CodeCompletionString *)XR.CompletionString; CodeCompletionString *Y = (CodeCompletionString *)YR.CompletionString; SmallString<256> XBuffer; StringRef XText = GetTypedName(X, XBuffer); SmallString<256> YBuffer; StringRef YText = GetTypedName(Y, YBuffer); if (XText.empty() || YText.empty()) return !XText.empty(); int result = XText.compare_lower(YText); if (result < 0) return true; if (result > 0) return false; result = XText.compare(YText); return result < 0; } }; } // extern "C" { // HLSL Change -Don't use c linkage. void clang_sortCodeCompletionResults(CXCompletionResult *Results, unsigned NumResults) { std::stable_sort(Results, Results + NumResults, OrderCompletionResults()); } // } // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/dxcisenseimpl.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxcisenseimpl.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements the DirectX Compiler IntelliSense component. // // // /////////////////////////////////////////////////////////////////////////////// #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/ParseAST.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Sema/SemaConsumer.h" #include "clang/Sema/SemaHLSL.h" #include "llvm/Support/Host.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "dxcisenseimpl.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MSFileSystem.h" /////////////////////////////////////////////////////////////////////////////// HRESULT CreateDxcIntelliSense(REFIID riid, LPVOID *ppv) throw() { CComPtr<DxcIntelliSense> isense = CreateOnMalloc<DxcIntelliSense>(DxcGetThreadMallocNoRef()); if (isense == nullptr) { *ppv = nullptr; return E_OUTOFMEMORY; } return isense.p->QueryInterface(riid, ppv); } /////////////////////////////////////////////////////////////////////////////// // This is exposed as a helper class, but the implementation works on // interfaces; we expect callers should be able to use their own. class DxcBasicUnsavedFile : public IDxcUnsavedFile { private: DXC_MICROCOM_TM_REF_FIELDS() LPSTR m_fileName; LPSTR m_contents; unsigned m_length; public: DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL() DXC_MICROCOM_TM_ALLOC(DxcBasicUnsavedFile) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) override { return DoBasicQueryInterface<IDxcUnsavedFile>(this, iid, ppvObject); } DxcBasicUnsavedFile(IMalloc *pMalloc); ~DxcBasicUnsavedFile(); HRESULT Initialize(LPCSTR fileName, LPCSTR contents, unsigned length); static HRESULT Create(LPCSTR fileName, LPCSTR contents, unsigned length, IDxcUnsavedFile **pObject); HRESULT STDMETHODCALLTYPE GetFileName(LPSTR *pFileName) override; HRESULT STDMETHODCALLTYPE GetContents(LPSTR *pContents) override; HRESULT STDMETHODCALLTYPE GetLength(unsigned *pLength) override; }; /////////////////////////////////////////////////////////////////////////////// static bool IsCursorKindQualifiedByParent(CXCursorKind kind) throw(); /////////////////////////////////////////////////////////////////////////////// static HRESULT AnsiToBSTR(const char *text, BSTR *pValue) throw() { if (pValue == nullptr) return E_POINTER; *pValue = nullptr; if (text == nullptr) { return S_OK; } // // charCount will include the null terminating character, because // -1 is used as the input length. // SysAllocStringLen takes the character count and adds one for the // null terminator, so we remove that from charCount for that call. // int charCount = MultiByteToWideChar(CP_UTF8, 0, text, -1, nullptr, 0); if (charCount <= 0) { return HRESULT_FROM_WIN32(GetLastError()); } *pValue = SysAllocStringLen(nullptr, charCount - 1); if (*pValue == nullptr) { return E_OUTOFMEMORY; } MultiByteToWideChar(CP_UTF8, 0, text, -1, *pValue, charCount); return S_OK; } static LPVOID CoTaskMemAllocZero(SIZE_T cb) throw() { LPVOID result = CoTaskMemAlloc(cb); if (result != nullptr) { ZeroMemory(result, cb); } return result; } /// <summary>Allocates one or more zero-initialized structures in task /// memory.</summary> <remarks> This does more work than CoTaskMemAlloc, but /// often simplifies cleanup for error cases. /// </remarks> template <typename T> static void CoTaskMemAllocZeroElems(SIZE_T elementCount, T **buf) throw() { *buf = reinterpret_cast<T *>(CoTaskMemAllocZero(elementCount * sizeof(T))); } static HRESULT CXStringToAnsiAndDispose(CXString value, LPSTR *pValue) throw() { if (pValue == nullptr) return E_POINTER; *pValue = nullptr; const char *text = clang_getCString(value); if (text == nullptr) { return S_OK; } size_t len = strlen(text); *pValue = (char *)CoTaskMemAlloc(len + 1); if (*pValue == nullptr) { return E_OUTOFMEMORY; } memcpy(*pValue, text, len + 1); clang_disposeString(value); return S_OK; } static HRESULT CXStringToBSTRAndDispose(CXString value, BSTR *pValue) throw() { HRESULT hr = AnsiToBSTR(clang_getCString(value), pValue); clang_disposeString(value); return hr; } static void CleanupUnsavedFiles(CXUnsavedFile *files, unsigned file_count) throw() { for (unsigned i = 0; i < file_count; ++i) { CoTaskMemFree((LPVOID)files[i].Filename); CoTaskMemFree((LPVOID)files[i].Contents); } delete[] files; } static HRESULT CoTaskMemAllocString(const char *src, LPSTR *pResult) throw() { assert(src != nullptr); if (pResult == nullptr) { return E_POINTER; } unsigned len = strlen(src); *pResult = (char *)CoTaskMemAlloc(len + 1); if (*pResult == nullptr) { return E_OUTOFMEMORY; } CopyMemory(*pResult, src, len + 1); return S_OK; } static HRESULT GetCursorQualifiedName(CXCursor cursor, bool includeTemplateArgs, BSTR *pResult) throw() { *pResult = nullptr; if (IsCursorKindQualifiedByParent(clang_getCursorKind(cursor))) { CXString text; text = clang_getCursorSpellingWithFormatting( cursor, CXCursorFormatting_SuppressTagKeyword); return CXStringToBSTRAndDispose(text, pResult); } if (clang_getCursorKind(cursor) == CXCursor_VarDecl || (clang_getCursorKind(cursor) == CXCursor_DeclRefExpr && clang_getCursorKind(clang_getCursorReferenced(cursor)) == CXCursor_VarDecl)) { return CXStringToBSTRAndDispose( clang_getCursorSpellingWithFormatting( cursor, CXCursorFormatting_SuppressTagKeyword | CXCursorFormatting_SuppressSpecifiers), pResult); } return CXStringToBSTRAndDispose( clang_getCursorSpellingWithFormatting( cursor, CXCursorFormatting_SuppressTagKeyword), pResult); } static bool IsCursorKindQualifiedByParent(CXCursorKind kind) throw() { return kind == CXCursor_TypeRef || kind == CXCursor_TemplateRef || kind == CXCursor_NamespaceRef || kind == CXCursor_MemberRef || kind == CXCursor_OverloadedDeclRef || kind == CXCursor_StructDecl || kind == CXCursor_UnionDecl || kind == CXCursor_ClassDecl || kind == CXCursor_EnumDecl || kind == CXCursor_FieldDecl || kind == CXCursor_EnumConstantDecl || kind == CXCursor_FunctionDecl || kind == CXCursor_CXXMethod || kind == CXCursor_Namespace || kind == CXCursor_Constructor || kind == CXCursor_Destructor || kind == CXCursor_FunctionTemplate || kind == CXCursor_ClassTemplate || kind == CXCursor_ClassTemplatePartialSpecialization; } template <typename TIface> static void SafeReleaseIfaceArray(TIface **arr, unsigned count) throw() { if (arr != nullptr) { for (unsigned i = 0; i < count; i++) { if (arr[i] != nullptr) { arr[i]->Release(); arr[i] = nullptr; } } } } static HRESULT SetupUnsavedFiles(IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files, CXUnsavedFile **files) { *files = nullptr; if (num_unsaved_files == 0) { return S_OK; } HRESULT hr = S_OK; CXUnsavedFile *localFiles = new (std::nothrow) CXUnsavedFile[num_unsaved_files]; IFROOM(localFiles); ZeroMemory(localFiles, num_unsaved_files * sizeof(localFiles[0])); for (unsigned i = 0; i < num_unsaved_files; ++i) { if (unsaved_files[i] == nullptr) { hr = E_INVALIDARG; break; } LPSTR strPtr; hr = unsaved_files[i]->GetFileName(&strPtr); if (FAILED(hr)) break; localFiles[i].Filename = strPtr; hr = unsaved_files[i]->GetContents(&strPtr); if (FAILED(hr)) break; localFiles[i].Contents = strPtr; hr = unsaved_files[i]->GetLength((unsigned *)&localFiles[i].Length); if (FAILED(hr)) break; } if (SUCCEEDED(hr)) { *files = localFiles; } else { CleanupUnsavedFiles(localFiles, num_unsaved_files); } return hr; } struct PagedCursorVisitorContext { unsigned skip; // References to skip at the beginning. unsigned top; // Maximum number of references to get. CSimpleArray<CXCursor> refs; // Cursor references found. }; static CXVisitorResult LIBCLANG_CC PagedCursorFindVisit(void *context, CXCursor c, CXSourceRange range) { PagedCursorVisitorContext *pagedContext = (PagedCursorVisitorContext *)context; if (pagedContext->skip > 0) { --pagedContext->skip; return CXVisit_Continue; } pagedContext->refs.Add(c); --pagedContext->top; return (pagedContext->top == 0) ? CXVisit_Break : CXVisit_Continue; } CXChildVisitResult LIBCLANG_CC PagedCursorTraverseVisit( CXCursor cursor, CXCursor parent, CXClientData client_data) { PagedCursorVisitorContext *pagedContext = (PagedCursorVisitorContext *)client_data; if (pagedContext->skip > 0) { --pagedContext->skip; return CXChildVisit_Continue; } pagedContext->refs.Add(cursor); --pagedContext->top; return (pagedContext->top == 0) ? CXChildVisit_Break : CXChildVisit_Continue; } static HRESULT PagedCursorVisitorCopyResults(PagedCursorVisitorContext *context, unsigned *pResultLength, IDxcCursor ***pResult) { *pResultLength = 0; *pResult = nullptr; unsigned resultLength = context->refs.GetSize(); CoTaskMemAllocZeroElems(resultLength, pResult); if (*pResult == nullptr) { return E_OUTOFMEMORY; } *pResultLength = resultLength; HRESULT hr = S_OK; for (unsigned i = 0; i < resultLength; ++i) { IDxcCursor *newCursor; hr = DxcCursor::Create(context->refs[i], &newCursor); if (FAILED(hr)) { break; } (*pResult)[i] = newCursor; } // Clean up any progress on failure. if (FAILED(hr)) { SafeReleaseIfaceArray(*pResult, resultLength); CoTaskMemFree(*pResult); *pResult = nullptr; *pResultLength = 0; } return hr; } struct SourceCursorVisitorContext { const CXSourceLocation &loc; CXFile file; unsigned offset; bool found; CXCursor result; unsigned resultOffset; SourceCursorVisitorContext(const CXSourceLocation &l) : loc(l), found(false) { clang_getSpellingLocation(loc, &file, nullptr, nullptr, &offset); } }; static CXChildVisitResult LIBCLANG_CC SourceCursorVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { SourceCursorVisitorContext *context = (SourceCursorVisitorContext *)client_data; CXSourceRange range = clang_getCursorExtent(cursor); // If the range ends before our location of interest, simply continue; no need // to recurse. CXFile cursorFile; unsigned cursorEndOffset; clang_getSpellingLocation(clang_getRangeEnd(range), &cursorFile, nullptr, nullptr, &cursorEndOffset); if (cursorFile != context->file || cursorEndOffset < context->offset) { return CXChildVisit_Continue; } // If the range start is before or equal to our position, we cover the // location, and we have a result but might need to recurse. If the range // start is after, this is where snapping behavior kicks in, and we'll // consider it just as good as overlap (for the closest match we have). So we // don't in fact need to consider the value, other than to snap to the closest // cursor. unsigned cursorStartOffset; clang_getSpellingLocation(clang_getRangeStart(range), &cursorFile, nullptr, nullptr, &cursorStartOffset); bool isKindResult = cursor.kind != CXCursor_CompoundStmt && cursor.kind != CXCursor_TranslationUnit && !clang_isInvalid(cursor.kind); if (isKindResult) { bool cursorIsBetter = context->found == false || (cursorStartOffset < context->resultOffset) || (cursorStartOffset == context->resultOffset && (int)cursor.kind == (int)DxcCursor_DeclRefExpr); if (cursorIsBetter) { context->found = true; context->result = cursor; context->resultOffset = cursorStartOffset; } } return CXChildVisit_Recurse; } /////////////////////////////////////////////////////////////////////////////// DxcBasicUnsavedFile::DxcBasicUnsavedFile(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_fileName(nullptr), m_contents(nullptr) { } DxcBasicUnsavedFile::~DxcBasicUnsavedFile() { free(m_fileName); delete[] m_contents; } HRESULT DxcBasicUnsavedFile::Initialize(LPCSTR fileName, LPCSTR contents, unsigned contentLength) { if (fileName == nullptr) return E_INVALIDARG; if (contents == nullptr) return E_INVALIDARG; m_fileName = _strdup(fileName); if (m_fileName == nullptr) return E_OUTOFMEMORY; unsigned bufferLength = strlen(contents); if (contentLength > bufferLength) { contentLength = bufferLength; } m_contents = new (std::nothrow) char[contentLength + 1]; if (m_contents == nullptr) { free(m_fileName); m_fileName = nullptr; return E_OUTOFMEMORY; } CopyMemory(m_contents, contents, contentLength); m_contents[contentLength] = '\0'; m_length = contentLength; return S_OK; } HRESULT DxcBasicUnsavedFile::Create(LPCSTR fileName, LPCSTR contents, unsigned contentLength, IDxcUnsavedFile **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcBasicUnsavedFile *newValue = DxcBasicUnsavedFile::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; HRESULT hr = newValue->Initialize(fileName, contents, contentLength); if (FAILED(hr)) { CComPtr<IMalloc> pTmp(newValue->m_pMalloc); newValue->DxcBasicUnsavedFile::~DxcBasicUnsavedFile(); pTmp->Free(newValue); return hr; } newValue->AddRef(); *pObject = newValue; return S_OK; } HRESULT DxcBasicUnsavedFile::GetFileName(LPSTR *pFileName) { return CoTaskMemAllocString(m_fileName, pFileName); } HRESULT DxcBasicUnsavedFile::GetContents(LPSTR *pContents) { return CoTaskMemAllocString(m_contents, pContents); } HRESULT DxcBasicUnsavedFile::GetLength(unsigned *pLength) { if (pLength == nullptr) return E_POINTER; *pLength = m_length; return S_OK; } /////////////////////////////////////////////////////////////////////////////// HRESULT DxcCursor::Create(const CXCursor &cursor, IDxcCursor **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcCursor *newValue = DxcCursor::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(cursor); newValue->AddRef(); *pObject = newValue; return S_OK; } void DxcCursor::Initialize(const CXCursor &cursor) { m_cursor = cursor; } HRESULT DxcCursor::GetExtent(IDxcSourceRange **pValue) { DxcThreadMalloc TM(m_pMalloc); CXSourceRange range = clang_getCursorExtent(m_cursor); return DxcSourceRange::Create(range, pValue); } HRESULT DxcCursor::GetLocation(IDxcSourceLocation **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(clang_getCursorLocation(m_cursor), pResult); } HRESULT DxcCursor::GetKind(DxcCursorKind *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = (DxcCursorKind)clang_getCursorKind(m_cursor); return S_OK; } HRESULT DxcCursor::GetKindFlags(DxcCursorKindFlags *pResult) { if (pResult == nullptr) return E_POINTER; DxcCursorKindFlags f = DxcCursorKind_None; CXCursorKind kind = clang_getCursorKind(m_cursor); if (0 != clang_isDeclaration(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Declaration); if (0 != clang_isReference(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Reference); if (0 != clang_isExpression(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Expression); if (0 != clang_isStatement(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Statement); if (0 != clang_isAttribute(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Attribute); if (0 != clang_isInvalid(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Invalid); if (0 != clang_isTranslationUnit(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_TranslationUnit); if (0 != clang_isPreprocessing(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Preprocessing); if (0 != clang_isUnexposed(kind)) f = (DxcCursorKindFlags)(f | DxcCursorKind_Unexposed); *pResult = f; return S_OK; } HRESULT DxcCursor::GetSemanticParent(IDxcCursor **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_getCursorSemanticParent(m_cursor), pResult); } HRESULT DxcCursor::GetLexicalParent(IDxcCursor **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_getCursorLexicalParent(m_cursor), pResult); } HRESULT DxcCursor::GetCursorType(IDxcType **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcType::Create(clang_getCursorType(m_cursor), pResult); } HRESULT DxcCursor::GetNumArguments(int *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = clang_Cursor_getNumArguments(m_cursor); return S_OK; } HRESULT DxcCursor::GetArgumentAt(int index, IDxcCursor **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_Cursor_getArgument(m_cursor, index), pResult); } HRESULT DxcCursor::GetReferencedCursor(IDxcCursor **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_getCursorReferenced(m_cursor), pResult); } HRESULT DxcCursor::GetDefinitionCursor(IDxcCursor **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_getCursorDefinition(m_cursor), pResult); } HRESULT DxcCursor::FindReferencesInFile(IDxcFile *file, unsigned skip, unsigned top, unsigned *pResultLength, IDxcCursor ***pResult) { if (pResultLength == nullptr) return E_POINTER; if (pResult == nullptr) return E_POINTER; if (file == nullptr) return E_INVALIDARG; *pResult = nullptr; *pResultLength = 0; if (top == 0) { return S_OK; } DxcThreadMalloc TM(m_pMalloc); CXCursorAndRangeVisitor visitor; PagedCursorVisitorContext findReferencesInFileContext; findReferencesInFileContext.skip = skip; findReferencesInFileContext.top = top; visitor.context = &findReferencesInFileContext; visitor.visit = PagedCursorFindVisit; DxcFile *fileImpl = reinterpret_cast<DxcFile *>(file); clang_findReferencesInFile(m_cursor, fileImpl->GetFile(), visitor); // known visitor, so ignore result return PagedCursorVisitorCopyResults(&findReferencesInFileContext, pResultLength, pResult); } HRESULT DxcCursor::GetSpelling(LPSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_getCursorSpelling(m_cursor), pResult); } HRESULT DxcCursor::IsEqualTo(IDxcCursor *other, BOOL *pResult) { if (pResult == nullptr) return E_POINTER; if (other == nullptr) { *pResult = FALSE; } else { DxcCursor *otherImpl = reinterpret_cast<DxcCursor *>(other); *pResult = 0 != clang_equalCursors(m_cursor, otherImpl->m_cursor); } return S_OK; } HRESULT DxcCursor::IsNull(BOOL *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = 0 != clang_Cursor_isNull(m_cursor); return S_OK; } HRESULT DxcCursor::IsDefinition(BOOL *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = 0 != clang_isCursorDefinition(m_cursor); return S_OK; } HRESULT DxcCursor::GetDisplayName(BSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToBSTRAndDispose(clang_getCursorDisplayName(m_cursor), pResult); } HRESULT DxcCursor::GetQualifiedName(BOOL includeTemplateArgs, BSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return GetCursorQualifiedName(m_cursor, includeTemplateArgs, pResult); } HRESULT DxcCursor::GetFormattedName(DxcCursorFormatting formatting, BSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToBSTRAndDispose( clang_getCursorSpellingWithFormatting(m_cursor, formatting), pResult); } HRESULT DxcCursor::GetChildren(unsigned skip, unsigned top, unsigned *pResultLength, IDxcCursor ***pResult) { if (pResultLength == nullptr) return E_POINTER; if (pResult == nullptr) return E_POINTER; *pResult = nullptr; *pResultLength = 0; if (top == 0) { return S_OK; } DxcThreadMalloc TM(m_pMalloc); PagedCursorVisitorContext visitorContext; visitorContext.skip = skip; visitorContext.top = top; clang_visitChildren(m_cursor, PagedCursorTraverseVisit, &visitorContext); // known visitor, so ignore result return PagedCursorVisitorCopyResults(&visitorContext, pResultLength, pResult); } HRESULT DxcCursor::GetSnappedChild(IDxcSourceLocation *location, IDxcCursor **pResult) { if (location == nullptr) return E_POINTER; if (pResult == nullptr) return E_POINTER; *pResult = nullptr; DxcThreadMalloc TM(m_pMalloc); DxcSourceLocation *locationImpl = reinterpret_cast<DxcSourceLocation *>(location); const CXSourceLocation &snapLocation = locationImpl->GetLocation(); SourceCursorVisitorContext visitorContext(snapLocation); clang_visitChildren(m_cursor, SourceCursorVisit, &visitorContext); if (visitorContext.found) { return DxcCursor::Create(visitorContext.result, pResult); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// DxcDiagnostic::DxcDiagnostic(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_diagnostic(nullptr) {} DxcDiagnostic::~DxcDiagnostic() { if (m_diagnostic) { clang_disposeDiagnostic(m_diagnostic); } } void DxcDiagnostic::Initialize(const CXDiagnostic &diagnostic) { m_diagnostic = diagnostic; } HRESULT DxcDiagnostic::Create(const CXDiagnostic &diagnostic, IDxcDiagnostic **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcDiagnostic *newValue = DxcDiagnostic::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(diagnostic); newValue->AddRef(); *pObject = newValue; return S_OK; } HRESULT DxcDiagnostic::FormatDiagnostic(DxcDiagnosticDisplayOptions options, LPSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_formatDiagnostic(m_diagnostic, options), pResult); } HRESULT DxcDiagnostic::GetSeverity(DxcDiagnosticSeverity *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = (DxcDiagnosticSeverity)clang_getDiagnosticSeverity(m_diagnostic); return S_OK; } HRESULT DxcDiagnostic::GetLocation(IDxcSourceLocation **pResult) { return DxcSourceLocation::Create(clang_getDiagnosticLocation(m_diagnostic), pResult); } HRESULT DxcDiagnostic::GetSpelling(LPSTR *pResult) { return CXStringToAnsiAndDispose(clang_getDiagnosticSpelling(m_diagnostic), pResult); } HRESULT DxcDiagnostic::GetCategoryText(LPSTR *pResult) { return CXStringToAnsiAndDispose(clang_getDiagnosticCategoryText(m_diagnostic), pResult); } HRESULT DxcDiagnostic::GetNumRanges(unsigned *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = clang_getDiagnosticNumRanges(m_diagnostic); return S_OK; } HRESULT DxcDiagnostic::GetRangeAt(unsigned index, IDxcSourceRange **pResult) { return DxcSourceRange::Create(clang_getDiagnosticRange(m_diagnostic, index), pResult); } HRESULT DxcDiagnostic::GetNumFixIts(unsigned *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = clang_getDiagnosticNumFixIts(m_diagnostic); return S_OK; } HRESULT DxcDiagnostic::GetFixItAt(unsigned index, IDxcSourceRange **pReplacementRange, LPSTR *pText) { if (pReplacementRange == nullptr) return E_POINTER; if (pText == nullptr) return E_POINTER; *pReplacementRange = nullptr; *pText = nullptr; DxcThreadMalloc TM(m_pMalloc); CXSourceRange range; CXString text = clang_getDiagnosticFixIt(m_diagnostic, index, &range); HRESULT hr = DxcSourceRange::Create(range, pReplacementRange); if (SUCCEEDED(hr)) { hr = CXStringToAnsiAndDispose(text, pText); if (FAILED(hr)) { (*pReplacementRange)->Release(); *pReplacementRange = nullptr; } } return hr; } /////////////////////////////////////////////////////////////////////////////// void DxcFile::Initialize(const CXFile &file) { m_file = file; } HRESULT DxcFile::Create(const CXFile &file, IDxcFile **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcFile *newValue = DxcFile::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(file); newValue->AddRef(); *pObject = newValue; return S_OK; } HRESULT DxcFile::GetName(LPSTR *pResult) { DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_getFileName(m_file), pResult); } HRESULT DxcFile::IsEqualTo(IDxcFile *other, BOOL *pResult) { if (!pResult) return E_POINTER; if (other == nullptr) { *pResult = FALSE; } else { // CXFile is an internal pointer into the source manager, and so // should be equal for the same file. DxcFile *otherImpl = reinterpret_cast<DxcFile *>(other); *pResult = (m_file == otherImpl->m_file) ? TRUE : FALSE; } return S_OK; } /////////////////////////////////////////////////////////////////////////////// DxcInclusion::DxcInclusion(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_file(nullptr), m_locations(nullptr), m_locationLength(0) {} DxcInclusion::~DxcInclusion() { delete[] m_locations; } HRESULT DxcInclusion::Initialize(CXFile file, unsigned locations, CXSourceLocation *pLocations) { if (locations) { m_locations = new (std::nothrow) CXSourceLocation[locations]; if (m_locations == nullptr) return E_OUTOFMEMORY; std::copy(pLocations, pLocations + locations, m_locations); m_locationLength = locations; } m_file = file; return S_OK; } HRESULT DxcInclusion::Create(CXFile file, unsigned locations, CXSourceLocation *pLocations, IDxcInclusion **pResult) { if (pResult == nullptr) return E_POINTER; *pResult = nullptr; CComPtr<DxcInclusion> local; local = DxcInclusion::Alloc(DxcGetThreadMallocNoRef()); if (local == nullptr) return E_OUTOFMEMORY; HRESULT hr = local->Initialize(file, locations, pLocations); if (FAILED(hr)) return hr; *pResult = local.Detach(); return S_OK; } HRESULT DxcInclusion::GetIncludedFile(IDxcFile **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcFile::Create(m_file, pResult); } HRESULT DxcInclusion::GetStackLength(unsigned *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = m_locationLength; return S_OK; } HRESULT DxcInclusion::GetStackItem(unsigned index, IDxcSourceLocation **pResult) { if (pResult == nullptr) return E_POINTER; if (index >= m_locationLength) return E_INVALIDARG; DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(m_locations[index], pResult); } /////////////////////////////////////////////////////////////////////////////// DxcIndex::DxcIndex(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_index(0), m_options(DxcGlobalOpt_None) { } DxcIndex::~DxcIndex() { if (m_index) { clang_disposeIndex(m_index); m_index = 0; } } HRESULT DxcIndex::Initialize(hlsl::DxcLangExtensionsHelper &langHelper) { try { m_langHelper = langHelper; // Clone the object. m_index = clang_createIndex(1, 0); if (m_index == 0) { return E_FAIL; } hlsl::DxcLangExtensionsHelperApply *apply = &m_langHelper; clang_index_setLangHelper(m_index, apply); } CATCH_CPP_RETURN_HRESULT(); return S_OK; } HRESULT DxcIndex::Create(hlsl::DxcLangExtensionsHelper &langHelper, DxcIndex **index) { if (index == nullptr) return E_POINTER; *index = nullptr; CComPtr<DxcIndex> local; local = DxcIndex::Alloc(DxcGetThreadMallocNoRef()); if (local == nullptr) return E_OUTOFMEMORY; HRESULT hr = local->Initialize(langHelper); if (FAILED(hr)) return hr; *index = local.Detach(); return S_OK; } HRESULT DxcIndex::SetGlobalOptions(DxcGlobalOptions options) { m_options = options; return S_OK; } HRESULT DxcIndex::GetGlobalOptions(DxcGlobalOptions *options) { if (options == nullptr) return E_POINTER; *options = m_options; return S_OK; } /////////////////////////////////////////////////////////////////////////////// HRESULT DxcIndex::ParseTranslationUnit(const char *source_filename, const char *const *command_line_args, int num_command_line_args, IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files, DxcTranslationUnitFlags options, IDxcTranslationUnit **pTranslationUnit) { if (pTranslationUnit == nullptr) return E_POINTER; *pTranslationUnit = nullptr; if (m_index == 0) return E_FAIL; DxcThreadMalloc TM(m_pMalloc); CXUnsavedFile *files; HRESULT hr = SetupUnsavedFiles(unsaved_files, num_unsaved_files, &files); if (FAILED(hr)) return hr; try { // TODO: until an interface to file access is defined and implemented, // simply fall back to pure Win32/CRT calls. ::llvm::sys::fs::MSFileSystem *msfPtr; IFT(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); IFTLLVM(pts.error_code()); CXTranslationUnit tu = clang_parseTranslationUnit( m_index, source_filename, command_line_args, num_command_line_args, files, num_unsaved_files, options); CleanupUnsavedFiles(files, num_unsaved_files); if (tu == nullptr) { return E_FAIL; } CComPtr<DxcTranslationUnit> localTU = DxcTranslationUnit::Alloc(DxcGetThreadMallocNoRef()); if (localTU == nullptr) { clang_disposeTranslationUnit(tu); return E_OUTOFMEMORY; } localTU->Initialize(tu); *pTranslationUnit = localTU.Detach(); return S_OK; } CATCH_CPP_RETURN_HRESULT(); } /////////////////////////////////////////////////////////////////////////////// HRESULT DxcIntelliSense::CreateIndex(IDxcIndex **index) { DxcThreadMalloc TM(m_pMalloc); CComPtr<DxcIndex> local; HRESULT hr = DxcIndex::Create(m_langHelper, &local); *index = local.Detach(); return hr; } HRESULT DxcIntelliSense::GetNullLocation(IDxcSourceLocation **location) { DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(clang_getNullLocation(), location); } HRESULT DxcIntelliSense::GetNullRange(IDxcSourceRange **location) { DxcThreadMalloc TM(m_pMalloc); return DxcSourceRange::Create(clang_getNullRange(), location); } HRESULT DxcIntelliSense::GetRange(IDxcSourceLocation *start, IDxcSourceLocation *end, IDxcSourceRange **pResult) { if (start == nullptr || end == nullptr) return E_INVALIDARG; if (pResult == nullptr) return E_POINTER; DxcSourceLocation *startImpl = reinterpret_cast<DxcSourceLocation *>(start); DxcSourceLocation *endImpl = reinterpret_cast<DxcSourceLocation *>(end); DxcThreadMalloc TM(m_pMalloc); return DxcSourceRange::Create( clang_getRange(startImpl->GetLocation(), endImpl->GetLocation()), pResult); } HRESULT DxcIntelliSense::GetDefaultDiagnosticDisplayOptions( DxcDiagnosticDisplayOptions *pValue) { if (pValue == nullptr) return E_POINTER; *pValue = (DxcDiagnosticDisplayOptions)clang_defaultDiagnosticDisplayOptions(); return S_OK; } HRESULT DxcIntelliSense::GetDefaultEditingTUOptions(DxcTranslationUnitFlags *pValue) { if (pValue == nullptr) return E_POINTER; *pValue = (DxcTranslationUnitFlags)(clang_defaultEditingTranslationUnitOptions() | (unsigned) DxcTranslationUnitFlags_UseCallerThread); return S_OK; } HRESULT DxcIntelliSense::CreateUnsavedFile(LPCSTR fileName, LPCSTR contents, unsigned contentLength, IDxcUnsavedFile **pResult) { DxcThreadMalloc TM(m_pMalloc); return DxcBasicUnsavedFile::Create(fileName, contents, contentLength, pResult); } /////////////////////////////////////////////////////////////////////////////// void DxcSourceLocation::Initialize(const CXSourceLocation &location) { m_location = location; } HRESULT DxcSourceLocation::Create(const CXSourceLocation &location, IDxcSourceLocation **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcSourceLocation *local = DxcSourceLocation::Alloc(DxcGetThreadMallocNoRef()); if (local == nullptr) return E_OUTOFMEMORY; local->Initialize(location); local->AddRef(); *pObject = local; return S_OK; } HRESULT DxcSourceLocation::IsEqualTo(IDxcSourceLocation *other, BOOL *pResult) { if (pResult == nullptr) return E_POINTER; if (other == nullptr) { *pResult = FALSE; } else { DxcSourceLocation *otherImpl = reinterpret_cast<DxcSourceLocation *>(other); *pResult = clang_equalLocations(m_location, otherImpl->m_location) != 0; } return S_OK; } HRESULT DxcSourceLocation::GetSpellingLocation(IDxcFile **pFile, unsigned *pLine, unsigned *pCol, unsigned *pOffset) { CXFile file; unsigned line, col, offset; DxcThreadMalloc TM(m_pMalloc); clang_getSpellingLocation(m_location, &file, &line, &col, &offset); if (pFile != nullptr) { HRESULT hr = DxcFile::Create(file, pFile); if (FAILED(hr)) return hr; } if (pLine) *pLine = line; if (pCol) *pCol = col; if (pOffset) *pOffset = offset; return S_OK; } HRESULT DxcSourceLocation::IsNull(BOOL *pResult) { if (pResult == nullptr) return E_POINTER; CXSourceLocation nullLocation = clang_getNullLocation(); *pResult = 0 != clang_equalLocations(nullLocation, m_location); return S_OK; } HRESULT DxcSourceLocation::GetPresumedLocation(LPSTR *pFilename, unsigned *pLine, unsigned *pCol) { DxcThreadMalloc TM(m_pMalloc); CXString filename; unsigned line, col; clang_getPresumedLocation(m_location, &filename, &line, &col); if (pFilename != nullptr) { HRESULT hr = CXStringToAnsiAndDispose(filename, pFilename); if (FAILED(hr)) return hr; } if (pLine) *pLine = line; if (pCol) *pCol = col; return S_OK; } /////////////////////////////////////////////////////////////////////////////// void DxcSourceRange::Initialize(const CXSourceRange &range) { m_range = range; } HRESULT DxcSourceRange::Create(const CXSourceRange &range, IDxcSourceRange **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcSourceRange *local = DxcSourceRange::Alloc(DxcGetThreadMallocNoRef()); if (local == nullptr) return E_OUTOFMEMORY; local->Initialize(range); local->AddRef(); *pObject = local; return S_OK; } HRESULT DxcSourceRange::IsNull(BOOL *pValue) { if (pValue == nullptr) return E_POINTER; *pValue = clang_Range_isNull(m_range) != 0; return S_OK; } HRESULT DxcSourceRange::GetStart(IDxcSourceLocation **pValue) { CXSourceLocation location = clang_getRangeStart(m_range); DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(location, pValue); } HRESULT DxcSourceRange::GetEnd(IDxcSourceLocation **pValue) { CXSourceLocation location = clang_getRangeEnd(m_range); DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(location, pValue); } HRESULT DxcSourceRange::GetOffsets(unsigned *startOffset, unsigned *endOffset) { if (startOffset == nullptr) return E_POINTER; if (endOffset == nullptr) return E_POINTER; CXSourceLocation startLocation = clang_getRangeStart(m_range); CXSourceLocation endLocation = clang_getRangeEnd(m_range); CXFile file; unsigned line, col; clang_getSpellingLocation(startLocation, &file, &line, &col, startOffset); clang_getSpellingLocation(endLocation, &file, &line, &col, endOffset); return S_OK; } /////////////////////////////////////////////////////////////////////////////// void DxcToken::Initialize(const CXTranslationUnit &tu, const CXToken &token) { m_tu = tu; m_token = token; } HRESULT DxcToken::Create(const CXTranslationUnit &tu, const CXToken &token, IDxcToken **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcToken *local = DxcToken::Alloc(DxcGetThreadMallocNoRef()); if (local == nullptr) return E_OUTOFMEMORY; local->Initialize(tu, token); local->AddRef(); *pObject = local; return S_OK; } HRESULT DxcToken::GetKind(DxcTokenKind *pValue) { if (pValue == nullptr) return E_POINTER; switch (clang_getTokenKind(m_token)) { case CXToken_Punctuation: *pValue = DxcTokenKind_Punctuation; break; case CXToken_Keyword: *pValue = DxcTokenKind_Keyword; break; case CXToken_Identifier: *pValue = DxcTokenKind_Identifier; break; case CXToken_Literal: *pValue = DxcTokenKind_Literal; break; case CXToken_Comment: *pValue = DxcTokenKind_Comment; break; case CXToken_BuiltInType: *pValue = DxcTokenKind_BuiltInType; break; default: *pValue = DxcTokenKind_Unknown; break; } return S_OK; } HRESULT DxcToken::GetLocation(IDxcSourceLocation **pValue) { if (pValue == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create(clang_getTokenLocation(m_tu, m_token), pValue); } HRESULT DxcToken::GetExtent(IDxcSourceRange **pValue) { if (pValue == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return DxcSourceRange::Create(clang_getTokenExtent(m_tu, m_token), pValue); } HRESULT DxcToken::GetSpelling(LPSTR *pValue) { if (pValue == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_getTokenSpelling(m_tu, m_token), pValue); } /////////////////////////////////////////////////////////////////////////////// DxcTranslationUnit::DxcTranslationUnit(IMalloc *pMalloc) : m_dwRef(0), m_pMalloc(pMalloc), m_tu(nullptr) {} DxcTranslationUnit::~DxcTranslationUnit() { if (m_tu != nullptr) { // TODO: until an interface to file access is defined and implemented, // simply fall back to pure Win32/CRT calls. Also, note that this can throw // / fail in a destructor, which is a big no-no. ::llvm::sys::fs::MSFileSystem *msfPtr; CreateMSFileSystemForDisk(&msfPtr); assert(msfPtr != nullptr); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); assert(!pts.error_code()); clang_disposeTranslationUnit(m_tu); m_tu = nullptr; } } void DxcTranslationUnit::Initialize(CXTranslationUnit tu) { m_tu = tu; } HRESULT DxcTranslationUnit::GetCursor(IDxcCursor **pCursor) { DxcThreadMalloc TM(m_pMalloc); if (m_tu == nullptr) return E_FAIL; return DxcCursor::Create(clang_getTranslationUnitCursor(m_tu), pCursor); } HRESULT DxcTranslationUnit::Tokenize(IDxcSourceRange *range, IDxcToken ***pTokens, unsigned *pTokenCount) { if (range == nullptr) return E_INVALIDARG; if (pTokens == nullptr) return E_POINTER; if (pTokenCount == nullptr) return E_POINTER; *pTokens = nullptr; *pTokenCount = 0; // Only accept our own source range. DxcThreadMalloc TM(m_pMalloc); HRESULT hr = S_OK; DxcSourceRange *rangeImpl = reinterpret_cast<DxcSourceRange *>(range); IDxcToken **localTokens = nullptr; CXToken *tokens = nullptr; unsigned numTokens = 0; clang_tokenize(m_tu, rangeImpl->GetRange(), &tokens, &numTokens); if (numTokens != 0) { CoTaskMemAllocZeroElems(numTokens, &localTokens); if (localTokens == nullptr) { hr = E_OUTOFMEMORY; } else { for (unsigned i = 0; i < numTokens; ++i) { hr = DxcToken::Create(m_tu, tokens[i], &localTokens[i]); if (FAILED(hr)) break; } *pTokens = localTokens; *pTokenCount = numTokens; } } // Cleanup partial progress on failures. if (FAILED(hr)) { SafeReleaseIfaceArray(localTokens, numTokens); delete[] localTokens; } if (tokens != nullptr) { clang_disposeTokens(m_tu, tokens, numTokens); } return hr; } HRESULT DxcTranslationUnit::GetLocation(IDxcFile *file, unsigned line, unsigned column, IDxcSourceLocation **pResult) { if (pResult == nullptr) return E_POINTER; *pResult = nullptr; if (file == nullptr) return E_INVALIDARG; DxcThreadMalloc TM(m_pMalloc); DxcFile *fileImpl = reinterpret_cast<DxcFile *>(file); return DxcSourceLocation::Create( clang_getLocation(m_tu, fileImpl->GetFile(), line, column), pResult); } HRESULT DxcTranslationUnit::GetNumDiagnostics(unsigned *pValue) { if (pValue == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); *pValue = clang_getNumDiagnostics(m_tu); return S_OK; } HRESULT DxcTranslationUnit::GetDiagnostic(unsigned index, IDxcDiagnostic **pValue) { if (pValue == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return DxcDiagnostic::Create(clang_getDiagnostic(m_tu, index), pValue); } HRESULT DxcTranslationUnit::GetFile(LPCSTR name, IDxcFile **pResult) { if (name == nullptr) return E_INVALIDARG; if (pResult == nullptr) return E_POINTER; *pResult = nullptr; // TODO: until an interface to file access is defined and implemented, simply // fall back to pure Win32/CRT calls. DxcThreadMalloc TM(m_pMalloc); ::llvm::sys::fs::MSFileSystem *msfPtr; IFR(CreateMSFileSystemForDisk(&msfPtr)); std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr); ::llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); CXFile localFile = clang_getFile(m_tu, name); return localFile == nullptr ? DISP_E_BADINDEX : DxcFile::Create(localFile, pResult); } HRESULT DxcTranslationUnit::GetFileName(LPSTR *pResult) { DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_getTranslationUnitSpelling(m_tu), pResult); } HRESULT DxcTranslationUnit::Reparse(IDxcUnsavedFile **unsaved_files, unsigned num_unsaved_files) { HRESULT hr; CXUnsavedFile *local_unsaved_files; DxcThreadMalloc TM(m_pMalloc); hr = SetupUnsavedFiles(unsaved_files, num_unsaved_files, &local_unsaved_files); if (FAILED(hr)) return hr; int reparseResult = clang_reparseTranslationUnit(m_tu, num_unsaved_files, local_unsaved_files, clang_defaultReparseOptions(m_tu)); CleanupUnsavedFiles(local_unsaved_files, num_unsaved_files); return reparseResult == 0 ? S_OK : E_FAIL; } HRESULT DxcTranslationUnit::GetCursorForLocation(IDxcSourceLocation *location, IDxcCursor **pResult) { if (location == nullptr) return E_INVALIDARG; if (pResult == nullptr) return E_POINTER; DxcSourceLocation *locationImpl = reinterpret_cast<DxcSourceLocation *>(location); DxcThreadMalloc TM(m_pMalloc); return DxcCursor::Create(clang_getCursor(m_tu, locationImpl->GetLocation()), pResult); } HRESULT DxcTranslationUnit::GetLocationForOffset(IDxcFile *file, unsigned offset, IDxcSourceLocation **pResult) { if (file == nullptr) return E_INVALIDARG; if (pResult == nullptr) return E_POINTER; DxcFile *fileImpl = reinterpret_cast<DxcFile *>(file); DxcThreadMalloc TM(m_pMalloc); return DxcSourceLocation::Create( clang_getLocationForOffset(m_tu, fileImpl->GetFile(), offset), pResult); } HRESULT DxcTranslationUnit::GetSkippedRanges(IDxcFile *file, unsigned *pResultCount, IDxcSourceRange ***pResult) { if (file == nullptr) return E_INVALIDARG; if (pResultCount == nullptr) return E_POINTER; if (pResult == nullptr) return E_POINTER; *pResultCount = 0; *pResult = nullptr; DxcThreadMalloc TM(m_pMalloc); DxcFile *fileImpl = reinterpret_cast<DxcFile *>(file); unsigned len = clang_ms_countSkippedRanges(m_tu, fileImpl->GetFile()); if (len == 0) { return S_OK; } CoTaskMemAllocZeroElems(len, pResult); if (*pResult == nullptr) { return E_OUTOFMEMORY; } HRESULT hr = S_OK; CXSourceRange *ranges = new CXSourceRange[len]; clang_ms_getSkippedRanges(m_tu, fileImpl->GetFile(), ranges, len); for (unsigned i = 0; i < len; ++i) { hr = DxcSourceRange::Create(ranges[i], &(*pResult)[i]); if (FAILED(hr)) break; } // Cleanup partial progress. if (FAILED(hr)) { SafeReleaseIfaceArray(*pResult, len); CoTaskMemFree(*pResult); *pResult = nullptr; } else { *pResultCount = len; } delete[] ranges; return hr; } HRESULT DxcTranslationUnit::GetDiagnosticDetails( unsigned index, DxcDiagnosticDisplayOptions options, unsigned *errorCode, unsigned *errorLine, unsigned *errorColumn, BSTR *errorFile, unsigned *errorOffset, unsigned *errorLength, BSTR *errorMessage) { if (errorCode == nullptr || errorLine == nullptr || errorColumn == nullptr || errorFile == nullptr || errorOffset == nullptr || errorLength == nullptr || errorMessage == nullptr) { return E_POINTER; } *errorCode = *errorLine = *errorColumn = *errorOffset = *errorLength = 0; *errorFile = *errorMessage = nullptr; HRESULT hr = S_OK; DxcThreadMalloc TM(m_pMalloc); CXDiagnostic diag = clang_getDiagnostic(m_tu, index); hr = CXStringToBSTRAndDispose(clang_formatDiagnostic(diag, options), errorMessage); if (FAILED(hr)) { return hr; } CXSourceLocation diagLoc = clang_getDiagnosticLocation(diag); CXFile diagFile; clang_getSpellingLocation(diagLoc, &diagFile, errorLine, errorColumn, errorOffset); hr = CXStringToBSTRAndDispose(clang_getFileName(diagFile), errorFile); if (FAILED(hr)) { SysFreeString(*errorMessage); *errorMessage = nullptr; return hr; } return S_OK; } struct InclusionData { HRESULT result; CSimpleArray<CComPtr<IDxcInclusion>> inclusions; }; static void VisitInclusion(CXFile included_file, CXSourceLocation *inclusion_stack, unsigned include_len, CXClientData client_data) { InclusionData *D = (InclusionData *)client_data; if (SUCCEEDED(D->result)) { CComPtr<IDxcInclusion> pInclusion; HRESULT hr = DxcInclusion::Create(included_file, include_len, inclusion_stack, &pInclusion); if (FAILED(hr)) { D->result = E_FAIL; } else if (!D->inclusions.Add(pInclusion)) { D->result = E_OUTOFMEMORY; } } } HRESULT DxcTranslationUnit::GetInclusionList(unsigned *pResultCount, IDxcInclusion ***pResult) { if (pResultCount == nullptr || pResult == nullptr) { return E_POINTER; } *pResultCount = 0; *pResult = nullptr; DxcThreadMalloc TM(m_pMalloc); InclusionData D; D.result = S_OK; clang_getInclusions(m_tu, VisitInclusion, &D); if (FAILED(D.result)) { return D.result; } int inclusionCount = D.inclusions.GetSize(); if (inclusionCount > 0) { CoTaskMemAllocZeroElems<IDxcInclusion *>(inclusionCount, pResult); if (*pResult == nullptr) { return E_OUTOFMEMORY; } for (int i = 0; i < inclusionCount; ++i) { (*pResult)[i] = D.inclusions[i].Detach(); } *pResultCount = inclusionCount; } return S_OK; } HRESULT DxcTranslationUnit::CodeCompleteAt(const char *fileName, unsigned line, unsigned column, IDxcUnsavedFile **pUnsavedFiles, unsigned numUnsavedFiles, DxcCodeCompleteFlags options, IDxcCodeCompleteResults **pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); CXUnsavedFile *files; HRESULT hr = SetupUnsavedFiles(pUnsavedFiles, numUnsavedFiles, &files); if (FAILED(hr)) return hr; CXCodeCompleteResults *results = clang_codeCompleteAt( m_tu, fileName, line, column, files, numUnsavedFiles, options); CleanupUnsavedFiles(files, numUnsavedFiles); if (results == nullptr) return E_FAIL; *pResult = nullptr; DxcCodeCompleteResults *newValue = DxcCodeCompleteResults::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) { clang_disposeCodeCompleteResults(results); return E_OUTOFMEMORY; } newValue->Initialize(results); newValue->AddRef(); *pResult = newValue; return S_OK; } /////////////////////////////////////////////////////////////////////////////// HRESULT DxcType::Create(const CXType &type, IDxcType **pObject) { if (pObject == nullptr) return E_POINTER; *pObject = nullptr; DxcType *newValue = DxcType::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(type); newValue->AddRef(); *pObject = newValue; return S_OK; } void DxcType::Initialize(const CXType &type) { m_type = type; } HRESULT DxcType::GetSpelling(LPSTR *pResult) { DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose(clang_getTypeSpelling(m_type), pResult); } HRESULT DxcType::IsEqualTo(IDxcType *other, BOOL *pResult) { if (pResult == nullptr) return E_POINTER; if (other == nullptr) { *pResult = FALSE; return S_OK; } DxcType *otherImpl = reinterpret_cast<DxcType *>(other); *pResult = 0 != clang_equalTypes(m_type, otherImpl->m_type); return S_OK; } HRESULT DxcType::GetKind(DxcTypeKind *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = (DxcTypeKind)m_type.kind; return S_OK; } /////////////////////////////////////////////////////////////////////////////// DxcCodeCompleteResults::~DxcCodeCompleteResults() { clang_disposeCodeCompleteResults(m_ccr); } void DxcCodeCompleteResults::Initialize(CXCodeCompleteResults *ccr) { m_ccr = ccr; } HRESULT DxcCodeCompleteResults::GetNumResults(unsigned *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); *pResult = m_ccr->NumResults; return S_OK; } HRESULT DxcCodeCompleteResults::GetResultAt(unsigned index, IDxcCompletionResult **pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); CXCompletionResult result = m_ccr->Results[index]; *pResult = nullptr; DxcCompletionResult *newValue = DxcCompletionResult::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(result); newValue->AddRef(); *pResult = newValue; return S_OK; } /////////////////////////////////////////////////////////////////////////////// void DxcCompletionResult::Initialize(const CXCompletionResult &cr) { m_cr = cr; } HRESULT DxcCompletionResult::GetCursorKind(DxcCursorKind *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = (DxcCursorKind)m_cr.CursorKind; return S_OK; } HRESULT DxcCompletionResult::GetCompletionString(IDxcCompletionString **pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); *pResult = nullptr; DxcCompletionString *newValue = DxcCompletionString::Alloc(DxcGetThreadMallocNoRef()); if (newValue == nullptr) return E_OUTOFMEMORY; newValue->Initialize(m_cr.CompletionString); newValue->AddRef(); *pResult = newValue; return S_OK; } /////////////////////////////////////////////////////////////////////////////// void DxcCompletionString::Initialize(const CXCompletionString &cs) { m_cs = cs; } HRESULT DxcCompletionString::GetNumCompletionChunks(unsigned *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = clang_getNumCompletionChunks(m_cs); return S_OK; } HRESULT DxcCompletionString::GetCompletionChunkKind(unsigned chunkNumber, DxcCompletionChunkKind *pResult) { if (pResult == nullptr) return E_POINTER; *pResult = (DxcCompletionChunkKind)clang_getCompletionChunkKind(m_cs, chunkNumber); return S_OK; } HRESULT DxcCompletionString::GetCompletionChunkText(unsigned chunkNumber, LPSTR *pResult) { if (pResult == nullptr) return E_POINTER; DxcThreadMalloc TM(m_pMalloc); return CXStringToAnsiAndDispose( clang_getCompletionChunkText(m_cs, chunkNumber), pResult); } /////////////////////////////////////////////////////////////////////////////// C_ASSERT((int)DxcCursor_UnexposedDecl == (int)CXCursor_UnexposedDecl); C_ASSERT((int)DxcCursor_StructDecl == (int)CXCursor_StructDecl); C_ASSERT((int)DxcCursor_UnionDecl == (int)CXCursor_UnionDecl); C_ASSERT((int)DxcCursor_ClassDecl == (int)CXCursor_ClassDecl); C_ASSERT((int)DxcCursor_EnumDecl == (int)CXCursor_EnumDecl); C_ASSERT((int)DxcCursor_FieldDecl == (int)CXCursor_FieldDecl); C_ASSERT((int)DxcCursor_EnumConstantDecl == (int)CXCursor_EnumConstantDecl); C_ASSERT((int)DxcCursor_FunctionDecl == (int)CXCursor_FunctionDecl); C_ASSERT((int)DxcCursor_VarDecl == (int)CXCursor_VarDecl); C_ASSERT((int)DxcCursor_ParmDecl == (int)CXCursor_ParmDecl); C_ASSERT((int)DxcCursor_ObjCInterfaceDecl == (int)CXCursor_ObjCInterfaceDecl); C_ASSERT((int)DxcCursor_ObjCCategoryDecl == (int)CXCursor_ObjCCategoryDecl); C_ASSERT((int)DxcCursor_ObjCProtocolDecl == (int)CXCursor_ObjCProtocolDecl); C_ASSERT((int)DxcCursor_ObjCPropertyDecl == (int)CXCursor_ObjCPropertyDecl); C_ASSERT((int)DxcCursor_ObjCIvarDecl == (int)CXCursor_ObjCIvarDecl); C_ASSERT((int)DxcCursor_ObjCInstanceMethodDecl == (int)CXCursor_ObjCInstanceMethodDecl); C_ASSERT((int)DxcCursor_ObjCClassMethodDecl == (int)CXCursor_ObjCClassMethodDecl); C_ASSERT((int)DxcCursor_ObjCImplementationDecl == (int)CXCursor_ObjCImplementationDecl); C_ASSERT((int)DxcCursor_ObjCCategoryImplDecl == (int)CXCursor_ObjCCategoryImplDecl); C_ASSERT((int)DxcCursor_TypedefDecl == (int)CXCursor_TypedefDecl); C_ASSERT((int)DxcCursor_CXXMethod == (int)CXCursor_CXXMethod); C_ASSERT((int)DxcCursor_Namespace == (int)CXCursor_Namespace); C_ASSERT((int)DxcCursor_LinkageSpec == (int)CXCursor_LinkageSpec); C_ASSERT((int)DxcCursor_Constructor == (int)CXCursor_Constructor); C_ASSERT((int)DxcCursor_Destructor == (int)CXCursor_Destructor); C_ASSERT((int)DxcCursor_ConversionFunction == (int)CXCursor_ConversionFunction); C_ASSERT((int)DxcCursor_TemplateTypeParameter == (int)CXCursor_TemplateTypeParameter); C_ASSERT((int)DxcCursor_NonTypeTemplateParameter == (int)CXCursor_NonTypeTemplateParameter); C_ASSERT((int)DxcCursor_TemplateTemplateParameter == (int)CXCursor_TemplateTemplateParameter); C_ASSERT((int)DxcCursor_FunctionTemplate == (int)CXCursor_FunctionTemplate); C_ASSERT((int)DxcCursor_ClassTemplate == (int)CXCursor_ClassTemplate); C_ASSERT((int)DxcCursor_ClassTemplatePartialSpecialization == (int)CXCursor_ClassTemplatePartialSpecialization); C_ASSERT((int)DxcCursor_NamespaceAlias == (int)CXCursor_NamespaceAlias); C_ASSERT((int)DxcCursor_UsingDirective == (int)CXCursor_UsingDirective); C_ASSERT((int)DxcCursor_UsingDeclaration == (int)CXCursor_UsingDeclaration); C_ASSERT((int)DxcCursor_TypeAliasDecl == (int)CXCursor_TypeAliasDecl); C_ASSERT((int)DxcCursor_ObjCSynthesizeDecl == (int)CXCursor_ObjCSynthesizeDecl); C_ASSERT((int)DxcCursor_ObjCDynamicDecl == (int)CXCursor_ObjCDynamicDecl); C_ASSERT((int)DxcCursor_CXXAccessSpecifier == (int)CXCursor_CXXAccessSpecifier); C_ASSERT((int)DxcCursor_FirstDecl == (int)CXCursor_FirstDecl); C_ASSERT((int)DxcCursor_LastDecl == (int)CXCursor_LastDecl); C_ASSERT((int)DxcCursor_FirstRef == (int)CXCursor_FirstRef); C_ASSERT((int)DxcCursor_ObjCSuperClassRef == (int)CXCursor_ObjCSuperClassRef); C_ASSERT((int)DxcCursor_ObjCProtocolRef == (int)CXCursor_ObjCProtocolRef); C_ASSERT((int)DxcCursor_ObjCClassRef == (int)CXCursor_ObjCClassRef); C_ASSERT((int)DxcCursor_TypeRef == (int)CXCursor_TypeRef); C_ASSERT((int)DxcCursor_CXXBaseSpecifier == (int)CXCursor_CXXBaseSpecifier); C_ASSERT((int)DxcCursor_TemplateRef == (int)CXCursor_TemplateRef); C_ASSERT((int)DxcCursor_NamespaceRef == (int)CXCursor_NamespaceRef); C_ASSERT((int)DxcCursor_MemberRef == (int)CXCursor_MemberRef); C_ASSERT((int)DxcCursor_LabelRef == (int)CXCursor_LabelRef); C_ASSERT((int)DxcCursor_OverloadedDeclRef == (int)CXCursor_OverloadedDeclRef); C_ASSERT((int)DxcCursor_VariableRef == (int)CXCursor_VariableRef); C_ASSERT((int)DxcCursor_LastRef == (int)CXCursor_LastRef); C_ASSERT((int)DxcCursor_FirstInvalid == (int)CXCursor_FirstInvalid); C_ASSERT((int)DxcCursor_InvalidFile == (int)CXCursor_InvalidFile); C_ASSERT((int)DxcCursor_NoDeclFound == (int)CXCursor_NoDeclFound); C_ASSERT((int)DxcCursor_NotImplemented == (int)CXCursor_NotImplemented); C_ASSERT((int)DxcCursor_InvalidCode == (int)CXCursor_InvalidCode); C_ASSERT((int)DxcCursor_LastInvalid == (int)CXCursor_LastInvalid); C_ASSERT((int)DxcCursor_FirstExpr == (int)CXCursor_FirstExpr); C_ASSERT((int)DxcCursor_UnexposedExpr == (int)CXCursor_UnexposedExpr); C_ASSERT((int)DxcCursor_DeclRefExpr == (int)CXCursor_DeclRefExpr); C_ASSERT((int)DxcCursor_MemberRefExpr == (int)CXCursor_MemberRefExpr); C_ASSERT((int)DxcCursor_CallExpr == (int)CXCursor_CallExpr); C_ASSERT((int)DxcCursor_ObjCMessageExpr == (int)CXCursor_ObjCMessageExpr); C_ASSERT((int)DxcCursor_BlockExpr == (int)CXCursor_BlockExpr); C_ASSERT((int)DxcCursor_IntegerLiteral == (int)CXCursor_IntegerLiteral); C_ASSERT((int)DxcCursor_FloatingLiteral == (int)CXCursor_FloatingLiteral); C_ASSERT((int)DxcCursor_ImaginaryLiteral == (int)CXCursor_ImaginaryLiteral); C_ASSERT((int)DxcCursor_StringLiteral == (int)CXCursor_StringLiteral); C_ASSERT((int)DxcCursor_CharacterLiteral == (int)CXCursor_CharacterLiteral); C_ASSERT((int)DxcCursor_ParenExpr == (int)CXCursor_ParenExpr); C_ASSERT((int)DxcCursor_UnaryOperator == (int)CXCursor_UnaryOperator); C_ASSERT((int)DxcCursor_ArraySubscriptExpr == (int)CXCursor_ArraySubscriptExpr); C_ASSERT((int)DxcCursor_BinaryOperator == (int)CXCursor_BinaryOperator); C_ASSERT((int)DxcCursor_CompoundAssignOperator == (int)CXCursor_CompoundAssignOperator); C_ASSERT((int)DxcCursor_ConditionalOperator == (int)CXCursor_ConditionalOperator); C_ASSERT((int)DxcCursor_CStyleCastExpr == (int)CXCursor_CStyleCastExpr); C_ASSERT((int)DxcCursor_CompoundLiteralExpr == (int)CXCursor_CompoundLiteralExpr); C_ASSERT((int)DxcCursor_InitListExpr == (int)CXCursor_InitListExpr); C_ASSERT((int)DxcCursor_AddrLabelExpr == (int)CXCursor_AddrLabelExpr); C_ASSERT((int)DxcCursor_StmtExpr == (int)CXCursor_StmtExpr); C_ASSERT((int)DxcCursor_GenericSelectionExpr == (int)CXCursor_GenericSelectionExpr); C_ASSERT((int)DxcCursor_GNUNullExpr == (int)CXCursor_GNUNullExpr); C_ASSERT((int)DxcCursor_CXXStaticCastExpr == (int)CXCursor_CXXStaticCastExpr); C_ASSERT((int)DxcCursor_CXXDynamicCastExpr == (int)CXCursor_CXXDynamicCastExpr); C_ASSERT((int)DxcCursor_CXXReinterpretCastExpr == (int)CXCursor_CXXReinterpretCastExpr); C_ASSERT((int)DxcCursor_CXXConstCastExpr == (int)CXCursor_CXXConstCastExpr); C_ASSERT((int)DxcCursor_CXXFunctionalCastExpr == (int)CXCursor_CXXFunctionalCastExpr); C_ASSERT((int)DxcCursor_CXXTypeidExpr == (int)CXCursor_CXXTypeidExpr); C_ASSERT((int)DxcCursor_CXXBoolLiteralExpr == (int)CXCursor_CXXBoolLiteralExpr); C_ASSERT((int)DxcCursor_CXXNullPtrLiteralExpr == (int)CXCursor_CXXNullPtrLiteralExpr); C_ASSERT((int)DxcCursor_CXXThisExpr == (int)CXCursor_CXXThisExpr); C_ASSERT((int)DxcCursor_CXXThrowExpr == (int)CXCursor_CXXThrowExpr); C_ASSERT((int)DxcCursor_CXXNewExpr == (int)CXCursor_CXXNewExpr); C_ASSERT((int)DxcCursor_CXXDeleteExpr == (int)CXCursor_CXXDeleteExpr); C_ASSERT((int)DxcCursor_UnaryExpr == (int)CXCursor_UnaryExpr); C_ASSERT((int)DxcCursor_ObjCStringLiteral == (int)CXCursor_ObjCStringLiteral); C_ASSERT((int)DxcCursor_ObjCEncodeExpr == (int)CXCursor_ObjCEncodeExpr); C_ASSERT((int)DxcCursor_ObjCSelectorExpr == (int)CXCursor_ObjCSelectorExpr); C_ASSERT((int)DxcCursor_ObjCProtocolExpr == (int)CXCursor_ObjCProtocolExpr); C_ASSERT((int)DxcCursor_ObjCBridgedCastExpr == (int)CXCursor_ObjCBridgedCastExpr); C_ASSERT((int)DxcCursor_PackExpansionExpr == (int)CXCursor_PackExpansionExpr); C_ASSERT((int)DxcCursor_SizeOfPackExpr == (int)CXCursor_SizeOfPackExpr); C_ASSERT((int)DxcCursor_LambdaExpr == (int)CXCursor_LambdaExpr); C_ASSERT((int)DxcCursor_ObjCBoolLiteralExpr == (int)CXCursor_ObjCBoolLiteralExpr); C_ASSERT((int)DxcCursor_ObjCSelfExpr == (int)CXCursor_ObjCSelfExpr); C_ASSERT((int)DxcCursor_LastExpr == (int)CXCursor_LastExpr); C_ASSERT((int)DxcCursor_FirstStmt == (int)CXCursor_FirstStmt); C_ASSERT((int)DxcCursor_UnexposedStmt == (int)CXCursor_UnexposedStmt); C_ASSERT((int)DxcCursor_LabelStmt == (int)CXCursor_LabelStmt); C_ASSERT((int)DxcCursor_CompoundStmt == (int)CXCursor_CompoundStmt); C_ASSERT((int)DxcCursor_CaseStmt == (int)CXCursor_CaseStmt); C_ASSERT((int)DxcCursor_DefaultStmt == (int)CXCursor_DefaultStmt); C_ASSERT((int)DxcCursor_IfStmt == (int)CXCursor_IfStmt); C_ASSERT((int)DxcCursor_SwitchStmt == (int)CXCursor_SwitchStmt); C_ASSERT((int)DxcCursor_WhileStmt == (int)CXCursor_WhileStmt); C_ASSERT((int)DxcCursor_DoStmt == (int)CXCursor_DoStmt); C_ASSERT((int)DxcCursor_ForStmt == (int)CXCursor_ForStmt); C_ASSERT((int)DxcCursor_GotoStmt == (int)CXCursor_GotoStmt); C_ASSERT((int)DxcCursor_IndirectGotoStmt == (int)CXCursor_IndirectGotoStmt); C_ASSERT((int)DxcCursor_ContinueStmt == (int)CXCursor_ContinueStmt); C_ASSERT((int)DxcCursor_BreakStmt == (int)CXCursor_BreakStmt); C_ASSERT((int)DxcCursor_ReturnStmt == (int)CXCursor_ReturnStmt); C_ASSERT((int)DxcCursor_GCCAsmStmt == (int)CXCursor_GCCAsmStmt); C_ASSERT((int)DxcCursor_AsmStmt == (int)CXCursor_AsmStmt); C_ASSERT((int)DxcCursor_ObjCAtTryStmt == (int)CXCursor_ObjCAtTryStmt); C_ASSERT((int)DxcCursor_ObjCAtCatchStmt == (int)CXCursor_ObjCAtCatchStmt); C_ASSERT((int)DxcCursor_ObjCAtFinallyStmt == (int)CXCursor_ObjCAtFinallyStmt); C_ASSERT((int)DxcCursor_ObjCAtThrowStmt == (int)CXCursor_ObjCAtThrowStmt); C_ASSERT((int)DxcCursor_ObjCAtSynchronizedStmt == (int)CXCursor_ObjCAtSynchronizedStmt); C_ASSERT((int)DxcCursor_ObjCAutoreleasePoolStmt == (int)CXCursor_ObjCAutoreleasePoolStmt); C_ASSERT((int)DxcCursor_ObjCForCollectionStmt == (int)CXCursor_ObjCForCollectionStmt); C_ASSERT((int)DxcCursor_CXXCatchStmt == (int)CXCursor_CXXCatchStmt); C_ASSERT((int)DxcCursor_CXXTryStmt == (int)CXCursor_CXXTryStmt); C_ASSERT((int)DxcCursor_CXXForRangeStmt == (int)CXCursor_CXXForRangeStmt); C_ASSERT((int)DxcCursor_SEHTryStmt == (int)CXCursor_SEHTryStmt); C_ASSERT((int)DxcCursor_SEHExceptStmt == (int)CXCursor_SEHExceptStmt); C_ASSERT((int)DxcCursor_SEHFinallyStmt == (int)CXCursor_SEHFinallyStmt); C_ASSERT((int)DxcCursor_MSAsmStmt == (int)CXCursor_MSAsmStmt); C_ASSERT((int)DxcCursor_NullStmt == (int)CXCursor_NullStmt); C_ASSERT((int)DxcCursor_DeclStmt == (int)CXCursor_DeclStmt); C_ASSERT((int)DxcCursor_OMPParallelDirective == (int)CXCursor_OMPParallelDirective); C_ASSERT((int)DxcCursor_LastStmt == (int)CXCursor_LastStmt); C_ASSERT((int)DxcCursor_TranslationUnit == (int)CXCursor_TranslationUnit); C_ASSERT((int)DxcCursor_FirstAttr == (int)CXCursor_FirstAttr); C_ASSERT((int)DxcCursor_UnexposedAttr == (int)CXCursor_UnexposedAttr); C_ASSERT((int)DxcCursor_IBActionAttr == (int)CXCursor_IBActionAttr); C_ASSERT((int)DxcCursor_IBOutletAttr == (int)CXCursor_IBOutletAttr); C_ASSERT((int)DxcCursor_IBOutletCollectionAttr == (int)CXCursor_IBOutletCollectionAttr); C_ASSERT((int)DxcCursor_CXXFinalAttr == (int)CXCursor_CXXFinalAttr); C_ASSERT((int)DxcCursor_CXXOverrideAttr == (int)CXCursor_CXXOverrideAttr); C_ASSERT((int)DxcCursor_AnnotateAttr == (int)CXCursor_AnnotateAttr); C_ASSERT((int)DxcCursor_AsmLabelAttr == (int)CXCursor_AsmLabelAttr); C_ASSERT((int)DxcCursor_PackedAttr == (int)CXCursor_PackedAttr); C_ASSERT((int)DxcCursor_LastAttr == (int)CXCursor_LastAttr); C_ASSERT((int)DxcCursor_PreprocessingDirective == (int)CXCursor_PreprocessingDirective); C_ASSERT((int)DxcCursor_MacroDefinition == (int)CXCursor_MacroDefinition); C_ASSERT((int)DxcCursor_MacroExpansion == (int)CXCursor_MacroExpansion); C_ASSERT((int)DxcCursor_MacroInstantiation == (int)CXCursor_MacroInstantiation); C_ASSERT((int)DxcCursor_InclusionDirective == (int)CXCursor_InclusionDirective); C_ASSERT((int)DxcCursor_FirstPreprocessing == (int)CXCursor_FirstPreprocessing); C_ASSERT((int)DxcCursor_LastPreprocessing == (int)CXCursor_LastPreprocessing); C_ASSERT((int)DxcCursor_ModuleImportDecl == (int)CXCursor_ModuleImportDecl); C_ASSERT((int)DxcCursor_FirstExtraDecl == (int)CXCursor_FirstExtraDecl); C_ASSERT((int)DxcCursor_LastExtraDecl == (int)CXCursor_LastExtraDecl); C_ASSERT((int)DxcTranslationUnitFlags_UseCallerThread == (int)CXTranslationUnit_UseCallerThread); C_ASSERT((int)DxcCodeCompleteFlags_IncludeMacros == (int)CXCodeComplete_IncludeMacros); C_ASSERT((int)DxcCodeCompleteFlags_IncludeCodePatterns == (int)CXCodeComplete_IncludeCodePatterns); C_ASSERT((int)DxcCodeCompleteFlags_IncludeBriefComments == (int)CXCodeComplete_IncludeBriefComments); C_ASSERT((int)DxcCompletionChunk_Optional == (int)CXCompletionChunk_Optional); C_ASSERT((int)DxcCompletionChunk_TypedText == (int)CXCompletionChunk_TypedText); C_ASSERT((int)DxcCompletionChunk_Text == (int)CXCompletionChunk_Text); C_ASSERT((int)DxcCompletionChunk_Placeholder == (int)CXCompletionChunk_Placeholder); C_ASSERT((int)DxcCompletionChunk_Informative == (int)CXCompletionChunk_Informative); C_ASSERT((int)DxcCompletionChunk_CurrentParameter == (int)CXCompletionChunk_CurrentParameter); C_ASSERT((int)DxcCompletionChunk_LeftParen == (int)CXCompletionChunk_LeftParen); C_ASSERT((int)DxcCompletionChunk_RightParen == (int)CXCompletionChunk_RightParen); C_ASSERT((int)DxcCompletionChunk_LeftBracket == (int)CXCompletionChunk_LeftBracket); C_ASSERT((int)DxcCompletionChunk_RightBracket == (int)CXCompletionChunk_RightBracket); C_ASSERT((int)DxcCompletionChunk_LeftBrace == (int)CXCompletionChunk_LeftBrace); C_ASSERT((int)DxcCompletionChunk_RightBrace == (int)CXCompletionChunk_RightBrace); C_ASSERT((int)DxcCompletionChunk_Comma == (int)CXCompletionChunk_Comma); C_ASSERT((int)DxcCompletionChunk_ResultType == (int)CXCompletionChunk_ResultType); C_ASSERT((int)DxcCompletionChunk_Colon == (int)CXCompletionChunk_Colon); C_ASSERT((int)DxcCompletionChunk_SemiColon == (int)CXCompletionChunk_SemiColon); C_ASSERT((int)DxcCompletionChunk_Equal == (int)CXCompletionChunk_Equal); C_ASSERT((int)DxcCompletionChunk_HorizontalSpace == (int)CXCompletionChunk_HorizontalSpace); C_ASSERT((int)DxcCompletionChunk_VerticalSpace == (int)CXCompletionChunk_VerticalSpace);
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXLoadedDiagnostic.cpp
//===-- CXLoadedDiagnostic.cpp - Handling of persisent diags ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements handling of persisent diagnostics. // //===----------------------------------------------------------------------===// #include "CXLoadedDiagnostic.h" #include "CXString.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LLVM.h" #include "clang/Frontend/SerializedDiagnosticReader.h" #include "clang/Frontend/SerializedDiagnostics.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" using namespace clang; //===----------------------------------------------------------------------===// // Extend CXDiagnosticSetImpl which contains strings for diagnostics. //===----------------------------------------------------------------------===// typedef llvm::DenseMap<unsigned, const char *> Strings; namespace { class CXLoadedDiagnosticSetImpl : public CXDiagnosticSetImpl { public: CXLoadedDiagnosticSetImpl() : CXDiagnosticSetImpl(true), FakeFiles(FO) {} ~CXLoadedDiagnosticSetImpl() override {} llvm::BumpPtrAllocator Alloc; Strings Categories; Strings WarningFlags; Strings FileNames; FileSystemOptions FO; FileManager FakeFiles; llvm::DenseMap<unsigned, const FileEntry *> Files; /// \brief Copy the string into our own allocator. const char *copyString(StringRef Blob) { char *mem = Alloc.Allocate<char>(Blob.size() + 1); memcpy(mem, Blob.data(), Blob.size()); mem[Blob.size()] = '\0'; return mem; } }; } //===----------------------------------------------------------------------===// // Cleanup. //===----------------------------------------------------------------------===// CXLoadedDiagnostic::~CXLoadedDiagnostic() {} //===----------------------------------------------------------------------===// // Public CXLoadedDiagnostic methods. //===----------------------------------------------------------------------===// CXDiagnosticSeverity CXLoadedDiagnostic::getSeverity() const { // FIXME: Fail more softly if the diagnostic level is unknown? auto severityAsLevel = static_cast<serialized_diags::Level>(severity); assert(severity == static_cast<unsigned>(severityAsLevel) && "unknown serialized diagnostic level"); switch (severityAsLevel) { #define CASE(X) case serialized_diags::X: return CXDiagnostic_##X; CASE(Ignored) CASE(Note) CASE(Warning) CASE(Error) CASE(Fatal) #undef CASE // The 'Remark' level isn't represented in the stable API. case serialized_diags::Remark: return CXDiagnostic_Warning; } llvm_unreachable("Invalid diagnostic level"); } static CXSourceLocation makeLocation(const CXLoadedDiagnostic::Location *DLoc) { // The lowest bit of ptr_data[0] is always set to 1 to indicate this // is a persistent diagnostic. uintptr_t V = (uintptr_t) DLoc; V |= 0x1; CXSourceLocation Loc = { { (void*) V, nullptr }, 0 }; return Loc; } CXSourceLocation CXLoadedDiagnostic::getLocation() const { // The lowest bit of ptr_data[0] is always set to 1 to indicate this // is a persistent diagnostic. return makeLocation(&DiagLoc); } CXString CXLoadedDiagnostic::getSpelling() const { return cxstring::createRef(Spelling); } CXString CXLoadedDiagnostic::getDiagnosticOption(CXString *Disable) const { if (DiagOption.empty()) return cxstring::createEmpty(); // FIXME: possibly refactor with logic in CXStoredDiagnostic. if (Disable) *Disable = cxstring::createDup((Twine("-Wno-") + DiagOption).str()); return cxstring::createDup((Twine("-W") + DiagOption).str()); } unsigned CXLoadedDiagnostic::getCategory() const { return category; } CXString CXLoadedDiagnostic::getCategoryText() const { return cxstring::createDup(CategoryText); } unsigned CXLoadedDiagnostic::getNumRanges() const { return Ranges.size(); } CXSourceRange CXLoadedDiagnostic::getRange(unsigned Range) const { assert(Range < Ranges.size()); return Ranges[Range]; } unsigned CXLoadedDiagnostic::getNumFixIts() const { return FixIts.size(); } CXString CXLoadedDiagnostic::getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const { assert(FixIt < FixIts.size()); if (ReplacementRange) *ReplacementRange = FixIts[FixIt].first; return cxstring::createRef(FixIts[FixIt].second); } void CXLoadedDiagnostic::decodeLocation(CXSourceLocation location, CXFile *file, unsigned int *line, unsigned int *column, unsigned int *offset) { // CXSourceLocation consists of the following fields: // // void *ptr_data[2]; // unsigned int_data; // // The lowest bit of ptr_data[0] is always set to 1 to indicate this // is a persistent diagnostic. // // For now, do the unoptimized approach and store the data in a side // data structure. We can optimize this case later. uintptr_t V = (uintptr_t) location.ptr_data[0]; assert((V & 0x1) == 1); V &= ~(uintptr_t)1; const Location &Loc = *((Location*)V); if (file) *file = Loc.file; if (line) *line = Loc.line; if (column) *column = Loc.column; if (offset) *offset = Loc.offset; } //===----------------------------------------------------------------------===// // Deserialize diagnostics. //===----------------------------------------------------------------------===// namespace { class DiagLoader : serialized_diags::SerializedDiagnosticReader { enum CXLoadDiag_Error *error; CXString *errorString; std::unique_ptr<CXLoadedDiagnosticSetImpl> TopDiags; SmallVector<std::unique_ptr<CXLoadedDiagnostic>, 8> CurrentDiags; std::error_code reportBad(enum CXLoadDiag_Error code, llvm::StringRef err) { if (error) *error = code; if (errorString) *errorString = cxstring::createDup(err); return serialized_diags::SDError::HandlerFailed; } std::error_code reportInvalidFile(llvm::StringRef err) { return reportBad(CXLoadDiag_InvalidFile, err); } std::error_code readRange(const serialized_diags::Location &SDStart, const serialized_diags::Location &SDEnd, CXSourceRange &SR); std::error_code readLocation(const serialized_diags::Location &SDLoc, CXLoadedDiagnostic::Location &LoadedLoc); protected: std::error_code visitStartOfDiagnostic() override; std::error_code visitEndOfDiagnostic() override; std::error_code visitCategoryRecord(unsigned ID, StringRef Name) override; std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) override; std::error_code visitDiagnosticRecord( unsigned Severity, const serialized_diags::Location &Location, unsigned Category, unsigned Flag, StringRef Message) override; std::error_code visitFilenameRecord(unsigned ID, unsigned Size, unsigned Timestamp, StringRef Name) override; std::error_code visitFixitRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End, StringRef CodeToInsert) override; std::error_code visitSourceRangeRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End) override; public: DiagLoader(enum CXLoadDiag_Error *e, CXString *es) : SerializedDiagnosticReader(), error(e), errorString(es) { if (error) *error = CXLoadDiag_None; if (errorString) *errorString = cxstring::createEmpty(); } CXDiagnosticSet load(const char *file); }; } CXDiagnosticSet DiagLoader::load(const char *file) { TopDiags = llvm::make_unique<CXLoadedDiagnosticSetImpl>(); std::error_code EC = readDiagnostics(file); if (EC) { switch (EC.value()) { case static_cast<int>(serialized_diags::SDError::HandlerFailed): // We've already reported the problem. break; case static_cast<int>(serialized_diags::SDError::CouldNotLoad): reportBad(CXLoadDiag_CannotLoad, EC.message()); break; default: reportInvalidFile(EC.message()); break; } return 0; } return (CXDiagnosticSet)TopDiags.release(); } std::error_code DiagLoader::readLocation(const serialized_diags::Location &SDLoc, CXLoadedDiagnostic::Location &LoadedLoc) { unsigned FileID = SDLoc.FileID; if (FileID == 0) LoadedLoc.file = nullptr; else { LoadedLoc.file = const_cast<FileEntry *>(TopDiags->Files[FileID]); if (!LoadedLoc.file) return reportInvalidFile("Corrupted file entry in source location"); } LoadedLoc.line = SDLoc.Line; LoadedLoc.column = SDLoc.Col; LoadedLoc.offset = SDLoc.Offset; return std::error_code(); } std::error_code DiagLoader::readRange(const serialized_diags::Location &SDStart, const serialized_diags::Location &SDEnd, CXSourceRange &SR) { CXLoadedDiagnostic::Location *Start, *End; Start = TopDiags->Alloc.Allocate<CXLoadedDiagnostic::Location>(); End = TopDiags->Alloc.Allocate<CXLoadedDiagnostic::Location>(); std::error_code EC; if ((EC = readLocation(SDStart, *Start))) return EC; if ((EC = readLocation(SDEnd, *End))) return EC; CXSourceLocation startLoc = makeLocation(Start); CXSourceLocation endLoc = makeLocation(End); SR = clang_getRange(startLoc, endLoc); return std::error_code(); } std::error_code DiagLoader::visitStartOfDiagnostic() { CurrentDiags.push_back(llvm::make_unique<CXLoadedDiagnostic>()); return std::error_code(); } std::error_code DiagLoader::visitEndOfDiagnostic() { auto D = CurrentDiags.pop_back_val(); if (CurrentDiags.empty()) TopDiags->appendDiagnostic(std::move(D)); else CurrentDiags.back()->getChildDiagnostics().appendDiagnostic(std::move(D)); return std::error_code(); } std::error_code DiagLoader::visitCategoryRecord(unsigned ID, StringRef Name) { // FIXME: Why do we care about long strings? if (Name.size() > 65536) return reportInvalidFile("Out-of-bounds string in category"); TopDiags->Categories[ID] = TopDiags->copyString(Name); return std::error_code(); } std::error_code DiagLoader::visitDiagFlagRecord(unsigned ID, StringRef Name) { // FIXME: Why do we care about long strings? if (Name.size() > 65536) return reportInvalidFile("Out-of-bounds string in warning flag"); TopDiags->WarningFlags[ID] = TopDiags->copyString(Name); return std::error_code(); } std::error_code DiagLoader::visitFilenameRecord(unsigned ID, unsigned Size, unsigned Timestamp, StringRef Name) { // FIXME: Why do we care about long strings? if (Name.size() > 65536) return reportInvalidFile("Out-of-bounds string in filename"); TopDiags->FileNames[ID] = TopDiags->copyString(Name); TopDiags->Files[ID] = TopDiags->FakeFiles.getVirtualFile(Name, Size, Timestamp); return std::error_code(); } std::error_code DiagLoader::visitSourceRangeRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End) { CXSourceRange SR; if (std::error_code EC = readRange(Start, End, SR)) return EC; CurrentDiags.back()->Ranges.push_back(SR); return std::error_code(); } std::error_code DiagLoader::visitFixitRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End, StringRef CodeToInsert) { CXSourceRange SR; if (std::error_code EC = readRange(Start, End, SR)) return EC; // FIXME: Why do we care about long strings? if (CodeToInsert.size() > 65536) return reportInvalidFile("Out-of-bounds string in FIXIT"); CurrentDiags.back()->FixIts.push_back( std::make_pair(SR, TopDiags->copyString(CodeToInsert))); return std::error_code(); } std::error_code DiagLoader::visitDiagnosticRecord( unsigned Severity, const serialized_diags::Location &Location, unsigned Category, unsigned Flag, StringRef Message) { CXLoadedDiagnostic &D = *CurrentDiags.back(); D.severity = Severity; if (std::error_code EC = readLocation(Location, D.DiagLoc)) return EC; D.category = Category; D.DiagOption = Flag ? TopDiags->WarningFlags[Flag] : ""; D.CategoryText = Category ? TopDiags->Categories[Category] : ""; D.Spelling = TopDiags->copyString(Message); return std::error_code(); } // extern "C" { // HLSL Change -Don't use c linkage. CXDiagnosticSet clang_loadDiagnostics(const char *file, enum CXLoadDiag_Error *error, CXString *errorString) { DiagLoader L(error, errorString); return L.load(file); } // } // end extern 'C'. // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/IndexingContext.cpp
//===- IndexingContext.cpp - Higher level API functions -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "CIndexDiagnostic.h" #include "CXTranslationUnit.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/Frontend/ASTUnit.h" using namespace clang; using namespace cxindex; using namespace cxcursor; IndexingContext::ObjCProtocolListInfo::ObjCProtocolListInfo( const ObjCProtocolList &ProtList, IndexingContext &IdxCtx, ScratchAlloc &SA) { ObjCInterfaceDecl::protocol_loc_iterator LI = ProtList.loc_begin(); for (ObjCInterfaceDecl::protocol_iterator I = ProtList.begin(), E = ProtList.end(); I != E; ++I, ++LI) { SourceLocation Loc = *LI; ObjCProtocolDecl *PD = *I; ProtEntities.push_back(EntityInfo()); IdxCtx.getEntityInfo(PD, ProtEntities.back(), SA); CXIdxObjCProtocolRefInfo ProtInfo = { nullptr, MakeCursorObjCProtocolRef(PD, Loc, IdxCtx.CXTU), IdxCtx.getIndexLoc(Loc) }; ProtInfos.push_back(ProtInfo); if (IdxCtx.shouldSuppressRefs()) IdxCtx.markEntityOccurrenceInFile(PD, Loc); } for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i) ProtInfos[i].protocol = &ProtEntities[i]; for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i) Prots.push_back(&ProtInfos[i]); } IBOutletCollectionInfo::IBOutletCollectionInfo( const IBOutletCollectionInfo &other) : AttrInfo(CXIdxAttr_IBOutletCollection, other.cursor, other.loc, other.A) { IBCollInfo.attrInfo = this; IBCollInfo.classCursor = other.IBCollInfo.classCursor; IBCollInfo.classLoc = other.IBCollInfo.classLoc; if (other.IBCollInfo.objcClass) { ClassInfo = other.ClassInfo; IBCollInfo.objcClass = &ClassInfo; } else IBCollInfo.objcClass = nullptr; } AttrListInfo::AttrListInfo(const Decl *D, IndexingContext &IdxCtx) : SA(IdxCtx), ref_cnt(0) { if (!D->hasAttrs()) return; for (const auto *A : D->attrs()) { CXCursor C = MakeCXCursor(A, D, IdxCtx.CXTU); CXIdxLoc Loc = IdxCtx.getIndexLoc(A->getLocation()); switch (C.kind) { default: Attrs.push_back(AttrInfo(CXIdxAttr_Unexposed, C, Loc, A)); break; case CXCursor_IBActionAttr: Attrs.push_back(AttrInfo(CXIdxAttr_IBAction, C, Loc, A)); break; case CXCursor_IBOutletAttr: Attrs.push_back(AttrInfo(CXIdxAttr_IBOutlet, C, Loc, A)); break; case CXCursor_IBOutletCollectionAttr: IBCollAttrs.push_back(IBOutletCollectionInfo(C, Loc, A)); break; } } for (unsigned i = 0, e = IBCollAttrs.size(); i != e; ++i) { IBOutletCollectionInfo &IBInfo = IBCollAttrs[i]; CXAttrs.push_back(&IBInfo); const IBOutletCollectionAttr * IBAttr = cast<IBOutletCollectionAttr>(IBInfo.A); SourceLocation InterfaceLocStart = IBAttr->getInterfaceLoc()->getTypeLoc().getLocStart(); IBInfo.IBCollInfo.attrInfo = &IBInfo; IBInfo.IBCollInfo.classLoc = IdxCtx.getIndexLoc(InterfaceLocStart); IBInfo.IBCollInfo.objcClass = nullptr; IBInfo.IBCollInfo.classCursor = clang_getNullCursor(); QualType Ty = IBAttr->getInterface(); if (const ObjCObjectType *ObjectTy = Ty->getAs<ObjCObjectType>()) { if (const ObjCInterfaceDecl *InterD = ObjectTy->getInterface()) { IdxCtx.getEntityInfo(InterD, IBInfo.ClassInfo, SA); IBInfo.IBCollInfo.objcClass = &IBInfo.ClassInfo; IBInfo.IBCollInfo.classCursor = MakeCursorObjCClassRef(InterD, InterfaceLocStart, IdxCtx.CXTU); } } } for (unsigned i = 0, e = Attrs.size(); i != e; ++i) CXAttrs.push_back(&Attrs[i]); } IntrusiveRefCntPtr<AttrListInfo> AttrListInfo::create(const Decl *D, IndexingContext &IdxCtx) { ScratchAlloc SA(IdxCtx); AttrListInfo *attrs = SA.allocate<AttrListInfo>(); return new (attrs) AttrListInfo(D, IdxCtx); } IndexingContext::CXXBasesListInfo::CXXBasesListInfo(const CXXRecordDecl *D, IndexingContext &IdxCtx, ScratchAlloc &SA) { for (const auto &Base : D->bases()) { BaseEntities.push_back(EntityInfo()); const NamedDecl *BaseD = nullptr; QualType T = Base.getType(); SourceLocation Loc = getBaseLoc(Base); if (const TypedefType *TDT = T->getAs<TypedefType>()) { BaseD = TDT->getDecl(); } else if (const TemplateSpecializationType * TST = T->getAs<TemplateSpecializationType>()) { BaseD = TST->getTemplateName().getAsTemplateDecl(); } else if (const RecordType *RT = T->getAs<RecordType>()) { BaseD = RT->getDecl(); } if (BaseD) IdxCtx.getEntityInfo(BaseD, BaseEntities.back(), SA); CXIdxBaseClassInfo BaseInfo = { nullptr, MakeCursorCXXBaseSpecifier(&Base, IdxCtx.CXTU), IdxCtx.getIndexLoc(Loc) }; BaseInfos.push_back(BaseInfo); } for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i) { if (BaseEntities[i].name && BaseEntities[i].USR) BaseInfos[i].base = &BaseEntities[i]; } for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i) CXBases.push_back(&BaseInfos[i]); } SourceLocation IndexingContext::CXXBasesListInfo::getBaseLoc( const CXXBaseSpecifier &Base) const { SourceLocation Loc = Base.getSourceRange().getBegin(); TypeLoc TL; if (Base.getTypeSourceInfo()) TL = Base.getTypeSourceInfo()->getTypeLoc(); if (TL.isNull()) return Loc; if (QualifiedTypeLoc QL = TL.getAs<QualifiedTypeLoc>()) TL = QL.getUnqualifiedLoc(); if (ElaboratedTypeLoc EL = TL.getAs<ElaboratedTypeLoc>()) return EL.getNamedTypeLoc().getBeginLoc(); if (DependentNameTypeLoc DL = TL.getAs<DependentNameTypeLoc>()) return DL.getNameLoc(); if (DependentTemplateSpecializationTypeLoc DTL = TL.getAs<DependentTemplateSpecializationTypeLoc>()) return DTL.getTemplateNameLoc(); return Loc; } const char *ScratchAlloc::toCStr(StringRef Str) { if (Str.empty()) return ""; if (Str.data()[Str.size()] == '\0') return Str.data(); return copyCStr(Str); } const char *ScratchAlloc::copyCStr(StringRef Str) { char *buf = IdxCtx.StrScratch.Allocate<char>(Str.size() + 1); std::uninitialized_copy(Str.begin(), Str.end(), buf); buf[Str.size()] = '\0'; return buf; } void IndexingContext::setASTContext(ASTContext &ctx) { Ctx = &ctx; cxtu::getASTUnit(CXTU)->setASTContext(&ctx); } void IndexingContext::setPreprocessor(Preprocessor &PP) { cxtu::getASTUnit(CXTU)->setPreprocessor(&PP); } bool IndexingContext::isFunctionLocalDecl(const Decl *D) { assert(D); if (!D->getParentFunctionOrMethod()) return false; if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) { switch (ND->getFormalLinkage()) { case NoLinkage: case VisibleNoLinkage: case InternalLinkage: return true; case UniqueExternalLinkage: llvm_unreachable("Not a sema linkage"); case ExternalLinkage: return false; } } return true; } bool IndexingContext::shouldAbort() { if (!CB.abortQuery) return false; return CB.abortQuery(ClientData, nullptr); } void IndexingContext::enteredMainFile(const FileEntry *File) { if (File && CB.enteredMainFile) { CXIdxClientFile idxFile = CB.enteredMainFile(ClientData, static_cast<CXFile>(const_cast<FileEntry *>(File)), nullptr); FileMap[File] = idxFile; } } void IndexingContext::ppIncludedFile(SourceLocation hashLoc, StringRef filename, const FileEntry *File, bool isImport, bool isAngled, bool isModuleImport) { if (!CB.ppIncludedFile) return; ScratchAlloc SA(*this); CXIdxIncludedFileInfo Info = { getIndexLoc(hashLoc), SA.toCStr(filename), static_cast<CXFile>( const_cast<FileEntry *>(File)), isImport, isAngled, isModuleImport }; CXIdxClientFile idxFile = CB.ppIncludedFile(ClientData, &Info); FileMap[File] = idxFile; } void IndexingContext::importedModule(const ImportDecl *ImportD) { if (!CB.importedASTFile) return; Module *Mod = ImportD->getImportedModule(); if (!Mod) return; CXIdxImportedASTFileInfo Info = { static_cast<CXFile>( const_cast<FileEntry *>(Mod->getASTFile())), Mod, getIndexLoc(ImportD->getLocation()), ImportD->isImplicit() }; CXIdxClientASTFile astFile = CB.importedASTFile(ClientData, &Info); (void)astFile; } void IndexingContext::importedPCH(const FileEntry *File) { if (!CB.importedASTFile) return; CXIdxImportedASTFileInfo Info = { static_cast<CXFile>( const_cast<FileEntry *>(File)), /*module=*/nullptr, getIndexLoc(SourceLocation()), /*isImplicit=*/false }; CXIdxClientASTFile astFile = CB.importedASTFile(ClientData, &Info); (void)astFile; } void IndexingContext::startedTranslationUnit() { CXIdxClientContainer idxCont = nullptr; if (CB.startedTranslationUnit) idxCont = CB.startedTranslationUnit(ClientData, nullptr); addContainerInMap(Ctx->getTranslationUnitDecl(), idxCont); } void IndexingContext::handleDiagnosticSet(CXDiagnostic CXDiagSet) { if (!CB.diagnostic) return; CB.diagnostic(ClientData, CXDiagSet, nullptr); } bool IndexingContext::handleDecl(const NamedDecl *D, SourceLocation Loc, CXCursor Cursor, DeclInfo &DInfo, const DeclContext *LexicalDC) { if (!CB.indexDeclaration || !D) return false; if (D->isImplicit() && shouldIgnoreIfImplicit(D)) return false; ScratchAlloc SA(*this); getEntityInfo(D, DInfo.EntInfo, SA); if ((!shouldIndexFunctionLocalSymbols() && !DInfo.EntInfo.USR) || Loc.isInvalid()) return false; if (!LexicalDC) LexicalDC = D->getLexicalDeclContext(); if (shouldSuppressRefs()) markEntityOccurrenceInFile(D, Loc); DInfo.entityInfo = &DInfo.EntInfo; DInfo.cursor = Cursor; DInfo.loc = getIndexLoc(Loc); DInfo.isImplicit = D->isImplicit(); DInfo.attributes = DInfo.EntInfo.attributes; DInfo.numAttributes = DInfo.EntInfo.numAttributes; getContainerInfo(D->getDeclContext(), DInfo.SemanticContainer); DInfo.semanticContainer = &DInfo.SemanticContainer; if (LexicalDC == D->getDeclContext()) { DInfo.lexicalContainer = &DInfo.SemanticContainer; } else if (isTemplateImplicitInstantiation(D)) { // Implicit instantiations have the lexical context of where they were // instantiated first. We choose instead the semantic context because: // 1) at the time that we see the instantiation we have not seen the // function where it occurred yet. // 2) the lexical context of the first instantiation is not useful // information anyway. DInfo.lexicalContainer = &DInfo.SemanticContainer; } else { getContainerInfo(LexicalDC, DInfo.LexicalContainer); DInfo.lexicalContainer = &DInfo.LexicalContainer; } if (DInfo.isContainer) { getContainerInfo(getEntityContainer(D), DInfo.DeclAsContainer); DInfo.declAsContainer = &DInfo.DeclAsContainer; } CB.indexDeclaration(ClientData, &DInfo); return true; } bool IndexingContext::handleObjCContainer(const ObjCContainerDecl *D, SourceLocation Loc, CXCursor Cursor, ObjCContainerDeclInfo &ContDInfo) { ContDInfo.ObjCContDeclInfo.declInfo = &ContDInfo; return handleDecl(D, Loc, Cursor, ContDInfo); } bool IndexingContext::handleFunction(const FunctionDecl *D) { bool isDef = D->isThisDeclarationADefinition(); bool isContainer = isDef; bool isSkipped = false; if (D->hasSkippedBody()) { isSkipped = true; isDef = true; isContainer = false; } DeclInfo DInfo(!D->isFirstDecl(), isDef, isContainer); if (isSkipped) DInfo.flags |= CXIdxDeclFlag_Skipped; return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleVar(const VarDecl *D) { DeclInfo DInfo(!D->isFirstDecl(), D->isThisDeclarationADefinition(), /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleField(const FieldDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleMSProperty(const MSPropertyDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleEnumerator(const EnumConstantDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleTagDecl(const TagDecl *D) { if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D)) return handleCXXRecordDecl(CXXRD, D); DeclInfo DInfo(!D->isFirstDecl(), D->isThisDeclarationADefinition(), D->isThisDeclarationADefinition()); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleTypedefName(const TypedefNameDecl *D) { DeclInfo DInfo(!D->isFirstDecl(), /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleObjCInterface(const ObjCInterfaceDecl *D) { // For @class forward declarations, suppress them the same way as references. if (!D->isThisDeclarationADefinition()) { if (shouldSuppressRefs() && markEntityOccurrenceInFile(D, D->getLocation())) return false; // already occurred. // FIXME: This seems like the wrong definition for redeclaration. bool isRedeclaration = D->hasDefinition() || D->getPreviousDecl(); ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true, isRedeclaration, /*isImplementation=*/false); return handleObjCContainer(D, D->getLocation(), MakeCursorObjCClassRef(D, D->getLocation(), CXTU), ContDInfo); } ScratchAlloc SA(*this); CXIdxBaseClassInfo BaseClass; EntityInfo BaseEntity; BaseClass.cursor = clang_getNullCursor(); if (ObjCInterfaceDecl *SuperD = D->getSuperClass()) { getEntityInfo(SuperD, BaseEntity, SA); SourceLocation SuperLoc = D->getSuperClassLoc(); BaseClass.base = &BaseEntity; BaseClass.cursor = MakeCursorObjCSuperClassRef(SuperD, SuperLoc, CXTU); BaseClass.loc = getIndexLoc(SuperLoc); if (shouldSuppressRefs()) markEntityOccurrenceInFile(SuperD, SuperLoc); } ObjCProtocolList EmptyProtoList; ObjCProtocolListInfo ProtInfo(D->isThisDeclarationADefinition() ? D->getReferencedProtocols() : EmptyProtoList, *this, SA); ObjCInterfaceDeclInfo InterInfo(D); InterInfo.ObjCProtoListInfo = ProtInfo.getListInfo(); InterInfo.ObjCInterDeclInfo.containerInfo = &InterInfo.ObjCContDeclInfo; InterInfo.ObjCInterDeclInfo.superInfo = D->getSuperClass() ? &BaseClass : nullptr; InterInfo.ObjCInterDeclInfo.protocols = &InterInfo.ObjCProtoListInfo; return handleObjCContainer(D, D->getLocation(), getCursor(D), InterInfo); } bool IndexingContext::handleObjCImplementation( const ObjCImplementationDecl *D) { ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/false, /*isRedeclaration=*/true, /*isImplementation=*/true); return handleObjCContainer(D, D->getLocation(), getCursor(D), ContDInfo); } bool IndexingContext::handleObjCProtocol(const ObjCProtocolDecl *D) { if (!D->isThisDeclarationADefinition()) { if (shouldSuppressRefs() && markEntityOccurrenceInFile(D, D->getLocation())) return false; // already occurred. // FIXME: This seems like the wrong definition for redeclaration. bool isRedeclaration = D->hasDefinition() || D->getPreviousDecl(); ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true, isRedeclaration, /*isImplementation=*/false); return handleObjCContainer(D, D->getLocation(), MakeCursorObjCProtocolRef(D, D->getLocation(), CXTU), ContDInfo); } ScratchAlloc SA(*this); ObjCProtocolList EmptyProtoList; ObjCProtocolListInfo ProtListInfo(D->isThisDeclarationADefinition() ? D->getReferencedProtocols() : EmptyProtoList, *this, SA); ObjCProtocolDeclInfo ProtInfo(D); ProtInfo.ObjCProtoRefListInfo = ProtListInfo.getListInfo(); return handleObjCContainer(D, D->getLocation(), getCursor(D), ProtInfo); } bool IndexingContext::handleObjCCategory(const ObjCCategoryDecl *D) { ScratchAlloc SA(*this); ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/false); EntityInfo ClassEntity; const ObjCInterfaceDecl *IFaceD = D->getClassInterface(); SourceLocation ClassLoc = D->getLocation(); SourceLocation CategoryLoc = D->IsClassExtension() ? ClassLoc : D->getCategoryNameLoc(); getEntityInfo(IFaceD, ClassEntity, SA); if (shouldSuppressRefs()) markEntityOccurrenceInFile(IFaceD, ClassLoc); ObjCProtocolListInfo ProtInfo(D->getReferencedProtocols(), *this, SA); CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo; if (IFaceD) { CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity; CatDInfo.ObjCCatDeclInfo.classCursor = MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU); } else { CatDInfo.ObjCCatDeclInfo.objcClass = nullptr; CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor(); } CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc); CatDInfo.ObjCProtoListInfo = ProtInfo.getListInfo(); CatDInfo.ObjCCatDeclInfo.protocols = &CatDInfo.ObjCProtoListInfo; return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo); } bool IndexingContext::handleObjCCategoryImpl(const ObjCCategoryImplDecl *D) { ScratchAlloc SA(*this); const ObjCCategoryDecl *CatD = D->getCategoryDecl(); ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/true); EntityInfo ClassEntity; const ObjCInterfaceDecl *IFaceD = CatD->getClassInterface(); SourceLocation ClassLoc = D->getLocation(); SourceLocation CategoryLoc = D->getCategoryNameLoc(); getEntityInfo(IFaceD, ClassEntity, SA); if (shouldSuppressRefs()) markEntityOccurrenceInFile(IFaceD, ClassLoc); CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo; if (IFaceD) { CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity; CatDInfo.ObjCCatDeclInfo.classCursor = MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU); } else { CatDInfo.ObjCCatDeclInfo.objcClass = nullptr; CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor(); } CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc); CatDInfo.ObjCCatDeclInfo.protocols = nullptr; return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo); } bool IndexingContext::handleObjCMethod(const ObjCMethodDecl *D) { bool isDef = D->isThisDeclarationADefinition(); bool isContainer = isDef; bool isSkipped = false; if (D->hasSkippedBody()) { isSkipped = true; isDef = true; isContainer = false; } DeclInfo DInfo(!D->isCanonicalDecl(), isDef, isContainer); if (isSkipped) DInfo.flags |= CXIdxDeclFlag_Skipped; return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleSynthesizedObjCProperty( const ObjCPropertyImplDecl *D) { ObjCPropertyDecl *PD = D->getPropertyDecl(); return handleReference(PD, D->getLocation(), getCursor(D), nullptr, D->getDeclContext()); } bool IndexingContext::handleSynthesizedObjCMethod(const ObjCMethodDecl *D, SourceLocation Loc, const DeclContext *LexicalDC) { DeclInfo DInfo(/*isRedeclaration=*/true, /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, Loc, getCursor(D), DInfo, LexicalDC); } bool IndexingContext::handleObjCProperty(const ObjCPropertyDecl *D) { ScratchAlloc SA(*this); ObjCPropertyDeclInfo DInfo; EntityInfo GetterEntity; EntityInfo SetterEntity; DInfo.ObjCPropDeclInfo.declInfo = &DInfo; if (ObjCMethodDecl *Getter = D->getGetterMethodDecl()) { getEntityInfo(Getter, GetterEntity, SA); DInfo.ObjCPropDeclInfo.getter = &GetterEntity; } else { DInfo.ObjCPropDeclInfo.getter = nullptr; } if (ObjCMethodDecl *Setter = D->getSetterMethodDecl()) { getEntityInfo(Setter, SetterEntity, SA); DInfo.ObjCPropDeclInfo.setter = &SetterEntity; } else { DInfo.ObjCPropDeclInfo.setter = nullptr; } return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleNamespace(const NamespaceDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/!D->isOriginalNamespace(), /*isDefinition=*/true, /*isContainer=*/true); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleClassTemplate(const ClassTemplateDecl *D) { return handleCXXRecordDecl(D->getTemplatedDecl(), D); } bool IndexingContext::handleFunctionTemplate(const FunctionTemplateDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(), /*isDefinition=*/D->isThisDeclarationADefinition(), /*isContainer=*/D->isThisDeclarationADefinition()); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleTypeAliasTemplate(const TypeAliasTemplateDecl *D) { DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(), /*isDefinition=*/true, /*isContainer=*/false); return handleDecl(D, D->getLocation(), getCursor(D), DInfo); } bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc, const NamedDecl *Parent, const DeclContext *DC, const Expr *E, CXIdxEntityRefKind Kind) { if (!D) return false; CXCursor Cursor = E ? MakeCXCursor(E, cast<Decl>(DC), CXTU) : getRefCursor(D, Loc); return handleReference(D, Loc, Cursor, Parent, DC, E, Kind); } bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc, CXCursor Cursor, const NamedDecl *Parent, const DeclContext *DC, const Expr *E, CXIdxEntityRefKind Kind) { if (!CB.indexEntityReference) return false; if (!D) return false; if (Loc.isInvalid()) return false; if (!shouldIndexFunctionLocalSymbols() && isFunctionLocalDecl(D)) return false; if (isNotFromSourceFile(D->getLocation())) return false; if (D->isImplicit() && shouldIgnoreIfImplicit(D)) return false; if (shouldSuppressRefs()) { if (markEntityOccurrenceInFile(D, Loc)) return false; // already occurred. } ScratchAlloc SA(*this); EntityInfo RefEntity, ParentEntity; getEntityInfo(D, RefEntity, SA); if (!RefEntity.USR) return false; getEntityInfo(Parent, ParentEntity, SA); ContainerInfo Container; getContainerInfo(DC, Container); CXIdxEntityRefInfo Info = { Kind, Cursor, getIndexLoc(Loc), &RefEntity, Parent ? &ParentEntity : nullptr, &Container }; CB.indexEntityReference(ClientData, &Info); return true; } bool IndexingContext::isNotFromSourceFile(SourceLocation Loc) const { if (Loc.isInvalid()) return true; SourceManager &SM = Ctx->getSourceManager(); SourceLocation FileLoc = SM.getFileLoc(Loc); FileID FID = SM.getFileID(FileLoc); return SM.getFileEntryForID(FID) == nullptr; } void IndexingContext::addContainerInMap(const DeclContext *DC, CXIdxClientContainer container) { if (!DC) return; ContainerMapTy::iterator I = ContainerMap.find(DC); if (I == ContainerMap.end()) { if (container) ContainerMap[DC] = container; return; } // Allow changing the container of a previously seen DeclContext so we // can handle invalid user code, like a function re-definition. if (container) I->second = container; else ContainerMap.erase(I); } CXIdxClientEntity IndexingContext::getClientEntity(const Decl *D) const { if (!D) return nullptr; EntityMapTy::const_iterator I = EntityMap.find(D); if (I == EntityMap.end()) return nullptr; return I->second; } void IndexingContext::setClientEntity(const Decl *D, CXIdxClientEntity client) { if (!D) return; EntityMap[D] = client; } bool IndexingContext::handleCXXRecordDecl(const CXXRecordDecl *RD, const NamedDecl *OrigD) { if (RD->isThisDeclarationADefinition()) { ScratchAlloc SA(*this); CXXClassDeclInfo CXXDInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(), /*isDefinition=*/RD->isThisDeclarationADefinition()); CXXBasesListInfo BaseList(RD, *this, SA); CXXDInfo.CXXClassInfo.declInfo = &CXXDInfo; CXXDInfo.CXXClassInfo.bases = BaseList.getBases(); CXXDInfo.CXXClassInfo.numBases = BaseList.getNumBases(); if (shouldSuppressRefs()) { // Go through bases and mark them as referenced. for (unsigned i = 0, e = BaseList.getNumBases(); i != e; ++i) { const CXIdxBaseClassInfo *baseInfo = BaseList.getBases()[i]; if (baseInfo->base) { const NamedDecl *BaseD = BaseList.BaseEntities[i].Dcl; SourceLocation Loc = SourceLocation::getFromRawEncoding(baseInfo->loc.int_data); markEntityOccurrenceInFile(BaseD, Loc); } } } return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), CXXDInfo); } DeclInfo DInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(), /*isDefinition=*/RD->isThisDeclarationADefinition(), /*isContainer=*/RD->isThisDeclarationADefinition()); return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), DInfo); } bool IndexingContext::markEntityOccurrenceInFile(const NamedDecl *D, SourceLocation Loc) { if (!D || Loc.isInvalid()) return true; SourceManager &SM = Ctx->getSourceManager(); D = getEntityDecl(D); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SM.getFileLoc(Loc)); FileID FID = LocInfo.first; if (FID.isInvalid()) return true; const FileEntry *FE = SM.getFileEntryForID(FID); if (!FE) return true; RefFileOccurrence RefOccur(FE, D); std::pair<llvm::DenseSet<RefFileOccurrence>::iterator, bool> res = RefFileOccurrences.insert(RefOccur); if (!res.second) return true; // already in map. return false; } const NamedDecl *IndexingContext::getEntityDecl(const NamedDecl *D) const { assert(D); D = cast<NamedDecl>(D->getCanonicalDecl()); if (const ObjCImplementationDecl * ImplD = dyn_cast<ObjCImplementationDecl>(D)) { return getEntityDecl(ImplD->getClassInterface()); } else if (const ObjCCategoryImplDecl * CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) { return getEntityDecl(CatImplD->getCategoryDecl()); } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FunctionTemplateDecl *TemplD = FD->getDescribedFunctionTemplate()) return getEntityDecl(TemplD); } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { if (ClassTemplateDecl *TemplD = RD->getDescribedClassTemplate()) return getEntityDecl(TemplD); } return D; } const DeclContext * IndexingContext::getEntityContainer(const Decl *D) const { const DeclContext *DC = dyn_cast<DeclContext>(D); if (DC) return DC; if (const ClassTemplateDecl *ClassTempl = dyn_cast<ClassTemplateDecl>(D)) { DC = ClassTempl->getTemplatedDecl(); } else if (const FunctionTemplateDecl * FuncTempl = dyn_cast<FunctionTemplateDecl>(D)) { DC = FuncTempl->getTemplatedDecl(); } return DC; } CXIdxClientContainer IndexingContext::getClientContainerForDC(const DeclContext *DC) const { if (!DC) return nullptr; ContainerMapTy::const_iterator I = ContainerMap.find(DC); if (I == ContainerMap.end()) return nullptr; return I->second; } CXIdxClientFile IndexingContext::getIndexFile(const FileEntry *File) { if (!File) return nullptr; FileMapTy::iterator FI = FileMap.find(File); if (FI != FileMap.end()) return FI->second; return nullptr; } CXIdxLoc IndexingContext::getIndexLoc(SourceLocation Loc) const { CXIdxLoc idxLoc = { {nullptr, nullptr}, 0 }; if (Loc.isInvalid()) return idxLoc; idxLoc.ptr_data[0] = const_cast<IndexingContext *>(this); idxLoc.int_data = Loc.getRawEncoding(); return idxLoc; } void IndexingContext::translateLoc(SourceLocation Loc, CXIdxClientFile *indexFile, CXFile *file, unsigned *line, unsigned *column, unsigned *offset) { if (Loc.isInvalid()) return; SourceManager &SM = Ctx->getSourceManager(); Loc = SM.getFileLoc(Loc); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; if (FID.isInvalid()) return; const FileEntry *FE = SM.getFileEntryForID(FID); if (indexFile) *indexFile = getIndexFile(FE); if (file) *file = const_cast<FileEntry *>(FE); if (line) *line = SM.getLineNumber(FID, FileOffset); if (column) *column = SM.getColumnNumber(FID, FileOffset); if (offset) *offset = FileOffset; } void IndexingContext::getEntityInfo(const NamedDecl *D, EntityInfo &EntityInfo, ScratchAlloc &SA) { if (!D) return; D = getEntityDecl(D); EntityInfo.cursor = getCursor(D); EntityInfo.Dcl = D; EntityInfo.IndexCtx = this; EntityInfo.kind = CXIdxEntity_Unexposed; EntityInfo.templateKind = CXIdxEntity_NonTemplate; EntityInfo.lang = CXIdxEntityLang_C; if (D->hasAttrs()) { EntityInfo.AttrList = AttrListInfo::create(D, *this); EntityInfo.attributes = EntityInfo.AttrList->getAttrs(); EntityInfo.numAttributes = EntityInfo.AttrList->getNumAttrs(); } if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { switch (TD->getTagKind()) { case TTK_Struct: EntityInfo.kind = CXIdxEntity_Struct; break; case TTK_Union: EntityInfo.kind = CXIdxEntity_Union; break; case TTK_Class: EntityInfo.kind = CXIdxEntity_CXXClass; EntityInfo.lang = CXIdxEntityLang_CXX; break; case TTK_Interface: EntityInfo.kind = CXIdxEntity_CXXInterface; EntityInfo.lang = CXIdxEntityLang_CXX; break; case TTK_Enum: EntityInfo.kind = CXIdxEntity_Enum; break; } if (const CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(D)) if (!CXXRec->isCLike()) EntityInfo.lang = CXIdxEntityLang_CXX; if (isa<ClassTemplatePartialSpecializationDecl>(D)) { EntityInfo.templateKind = CXIdxEntity_TemplatePartialSpecialization; } else if (isa<ClassTemplateSpecializationDecl>(D)) { EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization; } } else { switch (D->getKind()) { case Decl::Typedef: EntityInfo.kind = CXIdxEntity_Typedef; break; case Decl::Function: EntityInfo.kind = CXIdxEntity_Function; break; case Decl::ParmVar: EntityInfo.kind = CXIdxEntity_Variable; break; case Decl::Var: EntityInfo.kind = CXIdxEntity_Variable; if (isa<CXXRecordDecl>(D->getDeclContext())) { EntityInfo.kind = CXIdxEntity_CXXStaticVariable; EntityInfo.lang = CXIdxEntityLang_CXX; } break; case Decl::Field: EntityInfo.kind = CXIdxEntity_Field; if (const CXXRecordDecl * CXXRec = dyn_cast<CXXRecordDecl>(D->getDeclContext())) { // FIXME: isPOD check is not sufficient, a POD can contain methods, // we want a isCStructLike check. if (!CXXRec->isPOD()) EntityInfo.lang = CXIdxEntityLang_CXX; } break; case Decl::EnumConstant: EntityInfo.kind = CXIdxEntity_EnumConstant; break; case Decl::ObjCInterface: EntityInfo.kind = CXIdxEntity_ObjCClass; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::ObjCProtocol: EntityInfo.kind = CXIdxEntity_ObjCProtocol; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::ObjCCategory: EntityInfo.kind = CXIdxEntity_ObjCCategory; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::ObjCMethod: if (cast<ObjCMethodDecl>(D)->isInstanceMethod()) EntityInfo.kind = CXIdxEntity_ObjCInstanceMethod; else EntityInfo.kind = CXIdxEntity_ObjCClassMethod; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::ObjCProperty: EntityInfo.kind = CXIdxEntity_ObjCProperty; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::ObjCIvar: EntityInfo.kind = CXIdxEntity_ObjCIvar; EntityInfo.lang = CXIdxEntityLang_ObjC; break; case Decl::Namespace: EntityInfo.kind = CXIdxEntity_CXXNamespace; EntityInfo.lang = CXIdxEntityLang_CXX; break; case Decl::NamespaceAlias: EntityInfo.kind = CXIdxEntity_CXXNamespaceAlias; EntityInfo.lang = CXIdxEntityLang_CXX; break; case Decl::CXXConstructor: EntityInfo.kind = CXIdxEntity_CXXConstructor; EntityInfo.lang = CXIdxEntityLang_CXX; break; case Decl::CXXDestructor: EntityInfo.kind = CXIdxEntity_CXXDestructor; EntityInfo.lang = CXIdxEntityLang_CXX; break; case Decl::CXXConversion: EntityInfo.kind = CXIdxEntity_CXXConversionFunction; EntityInfo.lang = CXIdxEntityLang_CXX; break; case Decl::CXXMethod: { const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); if (MD->isStatic()) EntityInfo.kind = CXIdxEntity_CXXStaticMethod; else EntityInfo.kind = CXIdxEntity_CXXInstanceMethod; EntityInfo.lang = CXIdxEntityLang_CXX; break; } case Decl::ClassTemplate: EntityInfo.kind = CXIdxEntity_CXXClass; EntityInfo.templateKind = CXIdxEntity_Template; break; case Decl::FunctionTemplate: EntityInfo.kind = CXIdxEntity_Function; EntityInfo.templateKind = CXIdxEntity_Template; if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>( cast<FunctionTemplateDecl>(D)->getTemplatedDecl())) { if (isa<CXXConstructorDecl>(MD)) EntityInfo.kind = CXIdxEntity_CXXConstructor; else if (isa<CXXDestructorDecl>(MD)) EntityInfo.kind = CXIdxEntity_CXXDestructor; else if (isa<CXXConversionDecl>(MD)) EntityInfo.kind = CXIdxEntity_CXXConversionFunction; else { if (MD->isStatic()) EntityInfo.kind = CXIdxEntity_CXXStaticMethod; else EntityInfo.kind = CXIdxEntity_CXXInstanceMethod; } } break; case Decl::TypeAliasTemplate: EntityInfo.kind = CXIdxEntity_CXXTypeAlias; EntityInfo.templateKind = CXIdxEntity_Template; break; case Decl::TypeAlias: EntityInfo.kind = CXIdxEntity_CXXTypeAlias; EntityInfo.lang = CXIdxEntityLang_CXX; break; default: break; } } if (EntityInfo.kind == CXIdxEntity_Unexposed) return; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization) EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization; } if (EntityInfo.templateKind != CXIdxEntity_NonTemplate) EntityInfo.lang = CXIdxEntityLang_CXX; if (IdentifierInfo *II = D->getIdentifier()) { EntityInfo.name = SA.toCStr(II->getName()); } else if (isa<TagDecl>(D) || isa<FieldDecl>(D) || isa<NamespaceDecl>(D)) { EntityInfo.name = nullptr; // anonymous tag/field/namespace. } else { SmallString<256> StrBuf; { llvm::raw_svector_ostream OS(StrBuf); D->printName(OS); } EntityInfo.name = SA.copyCStr(StrBuf.str()); } { SmallString<512> StrBuf; bool Ignore = getDeclCursorUSR(D, StrBuf); if (Ignore) { EntityInfo.USR = nullptr; } else { EntityInfo.USR = SA.copyCStr(StrBuf.str()); } } } void IndexingContext::getContainerInfo(const DeclContext *DC, ContainerInfo &ContInfo) { ContInfo.cursor = getCursor(cast<Decl>(DC)); ContInfo.DC = DC; ContInfo.IndexCtx = this; } CXCursor IndexingContext::getRefCursor(const NamedDecl *D, SourceLocation Loc) { if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) return MakeCursorTypeRef(TD, Loc, CXTU); if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) return MakeCursorObjCClassRef(ID, Loc, CXTU); if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) return MakeCursorObjCProtocolRef(PD, Loc, CXTU); if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) return MakeCursorTemplateRef(Template, Loc, CXTU); if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(D)) return MakeCursorNamespaceRef(Namespace, Loc, CXTU); if (const NamespaceAliasDecl *Namespace = dyn_cast<NamespaceAliasDecl>(D)) return MakeCursorNamespaceRef(Namespace, Loc, CXTU); if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) return MakeCursorMemberRef(Field, Loc, CXTU); if (const VarDecl *Var = dyn_cast<VarDecl>(D)) return MakeCursorVariableRef(Var, Loc, CXTU); return clang_getNullCursor(); } bool IndexingContext::shouldIgnoreIfImplicit(const Decl *D) { if (isa<ObjCInterfaceDecl>(D)) return false; if (isa<ObjCCategoryDecl>(D)) return false; if (isa<ObjCIvarDecl>(D)) return false; if (isa<ObjCMethodDecl>(D)) return false; if (isa<ImportDecl>(D)) return false; return true; } bool IndexingContext::isTemplateImplicitInstantiation(const Decl *D) { if (const ClassTemplateSpecializationDecl * SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { return SD->getSpecializationKind() == TSK_ImplicitInstantiation; } if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation; } return false; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexDiagnostic.cpp
/*===-- CIndexDiagnostics.cpp - Diagnostics C Interface ---------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* Implements the diagnostic functions of the Clang C interface. *| |* *| \*===----------------------------------------------------------------------===*/ #include "CIndexDiagnostic.h" #include "CIndexer.h" #include "CXTranslationUnit.h" #include "CXSourceLocation.h" #include "CXString.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/DiagnosticRenderer.h" #include "clang/Basic/DiagnosticOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::cxloc; using namespace clang::cxdiag; using namespace llvm; CXDiagnosticSetImpl::~CXDiagnosticSetImpl() {} void CXDiagnosticSetImpl::appendDiagnostic(std::unique_ptr<CXDiagnosticImpl> D) { Diagnostics.push_back(std::move(D)); } CXDiagnosticImpl::~CXDiagnosticImpl() {} namespace { class CXDiagnosticCustomNoteImpl : public CXDiagnosticImpl { std::string Message; CXSourceLocation Loc; public: CXDiagnosticCustomNoteImpl(StringRef Msg, CXSourceLocation L) : CXDiagnosticImpl(CustomNoteDiagnosticKind), Message(Msg), Loc(L) {} ~CXDiagnosticCustomNoteImpl() override {} CXDiagnosticSeverity getSeverity() const override { return CXDiagnostic_Note; } CXSourceLocation getLocation() const override { return Loc; } CXString getSpelling() const override { return cxstring::createRef(Message.c_str()); } CXString getDiagnosticOption(CXString *Disable) const override { if (Disable) *Disable = cxstring::createEmpty(); return cxstring::createEmpty(); } unsigned getCategory() const override { return 0; } CXString getCategoryText() const override { return cxstring::createEmpty(); } unsigned getNumRanges() const override { return 0; } CXSourceRange getRange(unsigned Range) const override { return clang_getNullRange(); } unsigned getNumFixIts() const override { return 0; } CXString getFixIt(unsigned FixIt, CXSourceRange *ReplacementRange) const override { if (ReplacementRange) *ReplacementRange = clang_getNullRange(); return cxstring::createEmpty(); } }; class CXDiagnosticRenderer : public DiagnosticNoteRenderer { public: CXDiagnosticRenderer(const LangOptions &LangOpts, DiagnosticOptions *DiagOpts, CXDiagnosticSetImpl *mainSet) : DiagnosticNoteRenderer(LangOpts, DiagOpts), CurrentSet(mainSet), MainSet(mainSet) {} ~CXDiagnosticRenderer() override {} void beginDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) override { const StoredDiagnostic *SD = D.dyn_cast<const StoredDiagnostic*>(); if (!SD) return; if (Level != DiagnosticsEngine::Note) CurrentSet = MainSet; auto Owner = llvm::make_unique<CXStoredDiagnostic>(*SD, LangOpts); CXStoredDiagnostic &CD = *Owner; CurrentSet->appendDiagnostic(std::move(Owner)); if (Level != DiagnosticsEngine::Note) CurrentSet = &CD.getChildDiagnostics(); } void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, const SourceManager *SM, DiagOrStoredDiag D) override { if (!D.isNull()) return; CXSourceLocation L; if (SM) L = translateSourceLocation(*SM, LangOpts, Loc); else L = clang_getNullLocation(); CurrentSet->appendDiagnostic( llvm::make_unique<CXDiagnosticCustomNoteImpl>(Message, L)); } void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, ArrayRef<CharSourceRange> Ranges, const SourceManager &SM) override {} void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level, SmallVectorImpl<CharSourceRange>& Ranges, ArrayRef<FixItHint> Hints, const SourceManager &SM) override {} void emitNote(SourceLocation Loc, StringRef Message, const SourceManager *SM) override { CXSourceLocation L; if (SM) L = translateSourceLocation(*SM, LangOpts, Loc); else L = clang_getNullLocation(); CurrentSet->appendDiagnostic( llvm::make_unique<CXDiagnosticCustomNoteImpl>(Message, L)); } CXDiagnosticSetImpl *CurrentSet; CXDiagnosticSetImpl *MainSet; }; } CXDiagnosticSetImpl *cxdiag::lazyCreateDiags(CXTranslationUnit TU, bool checkIfChanged) { ASTUnit *AU = cxtu::getASTUnit(TU); if (TU->Diagnostics && checkIfChanged) { // In normal use, ASTUnit's diagnostics should not change unless we reparse. // Currently they can only change by using the internal testing flag // '-error-on-deserialized-decl' which will error during deserialization of // a declaration. What will happen is: // // -c-index-test gets a CXTranslationUnit // -checks the diagnostics, the diagnostics set is lazily created, // no errors are reported // -later does an operation, like annotation of tokens, that triggers // -error-on-deserialized-decl, that will emit a diagnostic error, // that ASTUnit will catch and add to its stored diagnostics vector. // -c-index-test wants to check whether an error occurred after performing // the operation but can only query the lazily created set. // // We check here if a new diagnostic was appended since the last time the // diagnostic set was created, in which case we reset it. CXDiagnosticSetImpl * Set = static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); if (AU->stored_diag_size() != Set->getNumDiagnostics()) { // Diagnostics in the ASTUnit were updated, reset the associated // diagnostics. delete Set; TU->Diagnostics = nullptr; } } if (!TU->Diagnostics) { CXDiagnosticSetImpl *Set = new CXDiagnosticSetImpl(); TU->Diagnostics = Set; IntrusiveRefCntPtr<DiagnosticOptions> DOpts = new DiagnosticOptions; CXDiagnosticRenderer Renderer(AU->getASTContext().getLangOpts(), &*DOpts, Set); for (ASTUnit::stored_diag_iterator it = AU->stored_diag_begin(), ei = AU->stored_diag_end(); it != ei; ++it) { Renderer.emitStoredDiagnostic(*it); } } return static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); } //----------------------------------------------------------------------------- // C Interface Routines //----------------------------------------------------------------------------- // extern "C" { // HLSL Change -Don't use c linkage. unsigned clang_getNumDiagnostics(CXTranslationUnit Unit) { if (cxtu::isNotUsableTU(Unit)) { LOG_BAD_TU(Unit); return 0; } if (!cxtu::getASTUnit(Unit)) return 0; return lazyCreateDiags(Unit, /*checkIfChanged=*/true)->getNumDiagnostics(); } CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index) { if (cxtu::isNotUsableTU(Unit)) { LOG_BAD_TU(Unit); return nullptr; } CXDiagnosticSet D = clang_getDiagnosticSetFromTU(Unit); if (!D) return nullptr; CXDiagnosticSetImpl *Diags = static_cast<CXDiagnosticSetImpl*>(D); if (Index >= Diags->getNumDiagnostics()) return nullptr; return Diags->getDiagnostic(Index); } CXDiagnosticSet clang_getDiagnosticSetFromTU(CXTranslationUnit Unit) { if (cxtu::isNotUsableTU(Unit)) { LOG_BAD_TU(Unit); return nullptr; } if (!cxtu::getASTUnit(Unit)) return nullptr; return static_cast<CXDiagnostic>(lazyCreateDiags(Unit)); } void clang_disposeDiagnostic(CXDiagnostic Diagnostic) { // No-op. Kept as a legacy API. CXDiagnostics are now managed // by the enclosing CXDiagnosticSet. } CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options) { if (!Diagnostic) return cxstring::createEmpty(); CXDiagnosticSeverity Severity = clang_getDiagnosticSeverity(Diagnostic); SmallString<256> Str; llvm::raw_svector_ostream Out(Str); if (Options & CXDiagnostic_DisplaySourceLocation) { // Print source location (file:line), along with optional column // and source ranges. CXFile File; unsigned Line, Column; clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic), &File, &Line, &Column, nullptr); if (File) { CXString FName = clang_getFileName(File); Out << clang_getCString(FName) << ":" << Line << ":"; clang_disposeString(FName); if (Options & CXDiagnostic_DisplayColumn) Out << Column << ":"; if (Options & CXDiagnostic_DisplaySourceRanges) { unsigned N = clang_getDiagnosticNumRanges(Diagnostic); bool PrintedRange = false; for (unsigned I = 0; I != N; ++I) { CXFile StartFile, EndFile; CXSourceRange Range = clang_getDiagnosticRange(Diagnostic, I); unsigned StartLine, StartColumn, EndLine, EndColumn; clang_getSpellingLocation(clang_getRangeStart(Range), &StartFile, &StartLine, &StartColumn, nullptr); clang_getSpellingLocation(clang_getRangeEnd(Range), &EndFile, &EndLine, &EndColumn, nullptr); if (StartFile != EndFile || StartFile != File) continue; Out << "{" << StartLine << ":" << StartColumn << "-" << EndLine << ":" << EndColumn << "}"; PrintedRange = true; } if (PrintedRange) Out << ":"; } Out << " "; } } /* Print warning/error/etc. */ if (Options & CXDiagnostic_DisplaySeverity) { // HLSL Change switch (Severity) { case CXDiagnostic_Ignored: llvm_unreachable("impossible"); case CXDiagnostic_Note: Out << "note: "; break; case CXDiagnostic_Warning: Out << "warning: "; break; case CXDiagnostic_Error: Out << "error: "; break; case CXDiagnostic_Fatal: Out << "fatal error: "; break; } } // HLSL Change CXString Text = clang_getDiagnosticSpelling(Diagnostic); if (clang_getCString(Text)) Out << clang_getCString(Text); else Out << "<no diagnostic text>"; clang_disposeString(Text); if (Options & (CXDiagnostic_DisplayOption | CXDiagnostic_DisplayCategoryId | CXDiagnostic_DisplayCategoryName)) { bool NeedBracket = true; bool NeedComma = false; if (Options & CXDiagnostic_DisplayOption) { CXString OptionName = clang_getDiagnosticOption(Diagnostic, nullptr); if (const char *OptionText = clang_getCString(OptionName)) { if (OptionText[0]) { Out << " [" << OptionText; NeedBracket = false; NeedComma = true; } } clang_disposeString(OptionName); } if (Options & (CXDiagnostic_DisplayCategoryId | CXDiagnostic_DisplayCategoryName)) { if (unsigned CategoryID = clang_getDiagnosticCategory(Diagnostic)) { if (Options & CXDiagnostic_DisplayCategoryId) { if (NeedBracket) Out << " ["; if (NeedComma) Out << ", "; Out << CategoryID; NeedBracket = false; NeedComma = true; } if (Options & CXDiagnostic_DisplayCategoryName) { CXString CategoryName = clang_getDiagnosticCategoryText(Diagnostic); if (NeedBracket) Out << " ["; if (NeedComma) Out << ", "; Out << clang_getCString(CategoryName); NeedBracket = false; NeedComma = true; clang_disposeString(CategoryName); } } } (void) NeedComma; // Silence dead store warning. if (!NeedBracket) Out << "]"; } return cxstring::createDup(Out.str()); } unsigned clang_defaultDiagnosticDisplayOptions() { return CXDiagnostic_DisplaySourceLocation | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplayOption; } enum CXDiagnosticSeverity clang_getDiagnosticSeverity(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl*>(Diag)) return D->getSeverity(); return CXDiagnostic_Ignored; } CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl*>(Diag)) return D->getLocation(); return clang_getNullLocation(); } CXString clang_getDiagnosticSpelling(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getSpelling(); return cxstring::createEmpty(); } CXString clang_getDiagnosticOption(CXDiagnostic Diag, CXString *Disable) { if (Disable) *Disable = cxstring::createEmpty(); if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getDiagnosticOption(Disable); return cxstring::createEmpty(); } unsigned clang_getDiagnosticCategory(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getCategory(); return 0; } CXString clang_getDiagnosticCategoryName(unsigned Category) { // Kept for backward compatibility. return cxstring::createRef(DiagnosticIDs::getCategoryNameFromID(Category)); } CXString clang_getDiagnosticCategoryText(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getCategoryText(); return cxstring::createEmpty(); } unsigned clang_getDiagnosticNumRanges(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getNumRanges(); return 0; } CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diag, unsigned Range) { CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag); if (!D || Range >= D->getNumRanges()) return clang_getNullRange(); return D->getRange(Range); } unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) return D->getNumFixIts(); return 0; } CXString clang_getDiagnosticFixIt(CXDiagnostic Diag, unsigned FixIt, CXSourceRange *ReplacementRange) { CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag); if (!D || FixIt >= D->getNumFixIts()) { if (ReplacementRange) *ReplacementRange = clang_getNullRange(); return cxstring::createEmpty(); } return D->getFixIt(FixIt, ReplacementRange); } void clang_disposeDiagnosticSet(CXDiagnosticSet Diags) { if (CXDiagnosticSetImpl *D = static_cast<CXDiagnosticSetImpl *>(Diags)) { if (D->isExternallyManaged()) delete D; } } CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, unsigned Index) { if (CXDiagnosticSetImpl *D = static_cast<CXDiagnosticSetImpl*>(Diags)) if (Index < D->getNumDiagnostics()) return D->getDiagnostic(Index); return nullptr; } CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic Diag) { if (CXDiagnosticImpl *D = static_cast<CXDiagnosticImpl *>(Diag)) { CXDiagnosticSetImpl &ChildDiags = D->getChildDiagnostics(); return ChildDiags.empty() ? nullptr : (CXDiagnosticSet) &ChildDiags; } return nullptr; } unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags) { if (CXDiagnosticSetImpl *D = static_cast<CXDiagnosticSetImpl*>(Diags)) return D->getNumDiagnostics(); return 0; } // } // end extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXType.h
//===- CXTypes.h - Routines for manipulating CXTypes ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXCursors. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXTYPE_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXTYPE_H #include "clang-c/Index.h" #include "clang/AST/Type.h" namespace clang { class ASTUnit; namespace cxtype { CXType MakeCXType(QualType T, CXTranslationUnit TU); }} // end namespace clang::cxtype #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXTranslationUnit.h
//===- CXTranslationUnit.h - Routines for manipulating CXTranslationUnits -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXTranslationUnits. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXTRANSLATIONUNIT_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXTRANSLATIONUNIT_H #include "CLog.h" #include "CXString.h" #include "clang-c/Index.h" namespace clang { class ASTUnit; class CIndexer; namespace index { class CommentToXMLConverter; } // namespace index } // namespace clang struct CXTranslationUnitImpl { clang::CIndexer *CIdx; clang::ASTUnit *TheASTUnit; clang::cxstring::CXStringPool *StringPool; void *Diagnostics; void *OverridenCursorsPool; clang::index::CommentToXMLConverter *CommentToXML; }; namespace clang { namespace cxtu { CXTranslationUnitImpl *MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU); static inline ASTUnit *getASTUnit(CXTranslationUnit TU) { if (!TU) return nullptr; return TU->TheASTUnit; } /// \returns true if the ASTUnit has a diagnostic about the AST file being /// corrupted. bool isASTReadError(ASTUnit *AU); static inline bool isNotUsableTU(CXTranslationUnit TU) { return !TU; } #define LOG_BAD_TU(TU) \ do { \ LOG_FUNC_SECTION { \ *Log << "called with a bad TU: " << TU; \ } \ } while(false) class CXTUOwner { CXTranslationUnitImpl *TU; public: CXTUOwner(CXTranslationUnitImpl *tu) : TU(tu) { } ~CXTUOwner(); CXTranslationUnitImpl *getTU() const { return TU; } CXTranslationUnitImpl *takeTU() { CXTranslationUnitImpl *retTU = TU; TU = nullptr; return retTU; } }; }} // end namespace clang::cxtu #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/libclang.rc
// // Copyright (c) Microsoft Corporation. All rights reserved. // #include <windows.h> #include <ntverp.h> #define VER_FILETYPE VFT_DLL #define VER_FILESUBTYPE VFT_UNKNOWN #define VER_FILEDESCRIPTION_STR "libclang for HLSL DLL" #define VER_INTERNALNAME_STR "libclang for HLSL DLL" #define VER_ORIGINALFILENAME_STR "libclang.dll" #include <common.ver>
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXCursor.cpp
//===- CXCursor.cpp - Routines for manipulating CXCursors -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXCursors. It should be the // only file that has internal knowledge of the encoding of the data in // CXCursor. // //===----------------------------------------------------------------------===// #include "CXTranslationUnit.h" #include "CXCursor.h" #include "CXString.h" #include "CXType.h" #include "clang-c/Index.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; using namespace cxcursor; CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K, CXTranslationUnit TU) { assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid); CXCursor C = { K, 0, { nullptr, nullptr, TU } }; return C; } static CXCursorKind GetCursorKind(const Attr *A) { assert(A && "Invalid arguments!"); switch (A->getKind()) { default: break; case attr::IBAction: return CXCursor_IBActionAttr; case attr::IBOutlet: return CXCursor_IBOutletAttr; case attr::IBOutletCollection: return CXCursor_IBOutletCollectionAttr; case attr::Final: return CXCursor_CXXFinalAttr; case attr::Override: return CXCursor_CXXOverrideAttr; case attr::Annotate: return CXCursor_AnnotateAttr; case attr::AsmLabel: return CXCursor_AsmLabelAttr; case attr::Packed: return CXCursor_PackedAttr; case attr::Pure: return CXCursor_PureAttr; case attr::Const: return CXCursor_ConstAttr; case attr::NoDuplicate: return CXCursor_NoDuplicateAttr; case attr::CUDAConstant: return CXCursor_CUDAConstantAttr; case attr::CUDADevice: return CXCursor_CUDADeviceAttr; case attr::CUDAGlobal: return CXCursor_CUDAGlobalAttr; case attr::CUDAHost: return CXCursor_CUDAHostAttr; case attr::CUDAShared: return CXCursor_CUDASharedAttr; } return CXCursor_UnexposedAttr; } CXCursor cxcursor::MakeCXCursor(const Attr *A, const Decl *Parent, CXTranslationUnit TU) { assert(A && Parent && TU && "Invalid arguments!"); CXCursor C = { GetCursorKind(A), 0, { Parent, A, TU } }; return C; } CXCursor cxcursor::MakeCXCursor(const Decl *D, CXTranslationUnit TU, SourceRange RegionOfInterest, bool FirstInDeclGroup) { assert(D && TU && "Invalid arguments!"); CXCursorKind K = getCursorKindForDecl(D); if (K == CXCursor_ObjCClassMethodDecl || K == CXCursor_ObjCInstanceMethodDecl) { int SelectorIdIndex = -1; // Check if cursor points to a selector id. if (RegionOfInterest.isValid() && RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) { SmallVector<SourceLocation, 16> SelLocs; cast<ObjCMethodDecl>(D)->getSelectorLocs(SelLocs); SmallVectorImpl<SourceLocation>::iterator I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin()); if (I != SelLocs.end()) SelectorIdIndex = I - SelLocs.begin(); } CXCursor C = { K, SelectorIdIndex, { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }}; return C; } CXCursor C = { K, 0, { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }}; return C; } CXCursor cxcursor::MakeCXCursor(const Stmt *S, const Decl *Parent, CXTranslationUnit TU, SourceRange RegionOfInterest) { assert(S && TU && "Invalid arguments!"); CXCursorKind K = CXCursor_NotImplemented; switch (S->getStmtClass()) { case Stmt::NoStmtClass: case Stmt::DiscardStmtClass: // HLSL Change break; case Stmt::CaseStmtClass: K = CXCursor_CaseStmt; break; case Stmt::DefaultStmtClass: K = CXCursor_DefaultStmt; break; case Stmt::IfStmtClass: K = CXCursor_IfStmt; break; case Stmt::SwitchStmtClass: K = CXCursor_SwitchStmt; break; case Stmt::WhileStmtClass: K = CXCursor_WhileStmt; break; case Stmt::DoStmtClass: K = CXCursor_DoStmt; break; case Stmt::ForStmtClass: K = CXCursor_ForStmt; break; case Stmt::GotoStmtClass: K = CXCursor_GotoStmt; break; case Stmt::IndirectGotoStmtClass: K = CXCursor_IndirectGotoStmt; break; case Stmt::ContinueStmtClass: K = CXCursor_ContinueStmt; break; case Stmt::BreakStmtClass: K = CXCursor_BreakStmt; break; case Stmt::ReturnStmtClass: K = CXCursor_ReturnStmt; break; case Stmt::GCCAsmStmtClass: K = CXCursor_GCCAsmStmt; break; case Stmt::MSAsmStmtClass: K = CXCursor_MSAsmStmt; break; case Stmt::ObjCAtTryStmtClass: K = CXCursor_ObjCAtTryStmt; break; case Stmt::ObjCAtCatchStmtClass: K = CXCursor_ObjCAtCatchStmt; break; case Stmt::ObjCAtFinallyStmtClass: K = CXCursor_ObjCAtFinallyStmt; break; case Stmt::ObjCAtThrowStmtClass: K = CXCursor_ObjCAtThrowStmt; break; case Stmt::ObjCAtSynchronizedStmtClass: K = CXCursor_ObjCAtSynchronizedStmt; break; case Stmt::ObjCAutoreleasePoolStmtClass: K = CXCursor_ObjCAutoreleasePoolStmt; break; case Stmt::ObjCForCollectionStmtClass: K = CXCursor_ObjCForCollectionStmt; break; case Stmt::CXXCatchStmtClass: K = CXCursor_CXXCatchStmt; break; case Stmt::CXXTryStmtClass: K = CXCursor_CXXTryStmt; break; case Stmt::CXXForRangeStmtClass: K = CXCursor_CXXForRangeStmt; break; case Stmt::SEHTryStmtClass: K = CXCursor_SEHTryStmt; break; case Stmt::SEHExceptStmtClass: K = CXCursor_SEHExceptStmt; break; case Stmt::SEHFinallyStmtClass: K = CXCursor_SEHFinallyStmt; break; case Stmt::SEHLeaveStmtClass: K = CXCursor_SEHLeaveStmt; break; case Stmt::ArrayTypeTraitExprClass: case Stmt::AsTypeExprClass: case Stmt::AtomicExprClass: case Stmt::BinaryConditionalOperatorClass: case Stmt::TypeTraitExprClass: case Stmt::CXXBindTemporaryExprClass: case Stmt::CXXDefaultArgExprClass: case Stmt::CXXDefaultInitExprClass: case Stmt::CXXFoldExprClass: case Stmt::CXXStdInitializerListExprClass: case Stmt::CXXScalarValueInitExprClass: case Stmt::CXXUuidofExprClass: case Stmt::ChooseExprClass: case Stmt::DesignatedInitExprClass: case Stmt::DesignatedInitUpdateExprClass: case Stmt::ExprWithCleanupsClass: case Stmt::ExpressionTraitExprClass: case Stmt::ExtVectorElementExprClass: case Stmt::ExtMatrixElementExprClass: // HLSL Change case Stmt::HLSLVectorElementExprClass: // HLSL Change case Stmt::ImplicitCastExprClass: case Stmt::ImplicitValueInitExprClass: case Stmt::NoInitExprClass: case Stmt::MaterializeTemporaryExprClass: case Stmt::ObjCIndirectCopyRestoreExprClass: case Stmt::OffsetOfExprClass: case Stmt::ParenListExprClass: case Stmt::PredefinedExprClass: case Stmt::ShuffleVectorExprClass: case Stmt::ConvertVectorExprClass: case Stmt::UnaryExprOrTypeTraitExprClass: case Stmt::VAArgExprClass: case Stmt::ObjCArrayLiteralClass: case Stmt::ObjCDictionaryLiteralClass: case Stmt::ObjCBoxedExprClass: case Stmt::ObjCSubscriptRefExprClass: K = CXCursor_UnexposedExpr; break; case Stmt::OpaqueValueExprClass: if (Expr *Src = cast<OpaqueValueExpr>(S)->getSourceExpr()) return MakeCXCursor(Src, Parent, TU, RegionOfInterest); K = CXCursor_UnexposedExpr; break; case Stmt::PseudoObjectExprClass: return MakeCXCursor(cast<PseudoObjectExpr>(S)->getSyntacticForm(), Parent, TU, RegionOfInterest); case Stmt::CompoundStmtClass: K = CXCursor_CompoundStmt; break; case Stmt::NullStmtClass: K = CXCursor_NullStmt; break; case Stmt::LabelStmtClass: K = CXCursor_LabelStmt; break; case Stmt::AttributedStmtClass: K = CXCursor_UnexposedStmt; break; case Stmt::DeclStmtClass: K = CXCursor_DeclStmt; break; case Stmt::CapturedStmtClass: K = CXCursor_UnexposedStmt; break; case Stmt::IntegerLiteralClass: K = CXCursor_IntegerLiteral; break; case Stmt::FloatingLiteralClass: K = CXCursor_FloatingLiteral; break; case Stmt::ImaginaryLiteralClass: K = CXCursor_ImaginaryLiteral; break; case Stmt::StringLiteralClass: K = CXCursor_StringLiteral; break; case Stmt::CharacterLiteralClass: K = CXCursor_CharacterLiteral; break; case Stmt::ParenExprClass: K = CXCursor_ParenExpr; break; case Stmt::UnaryOperatorClass: K = CXCursor_UnaryOperator; break; case Stmt::CXXNoexceptExprClass: K = CXCursor_UnaryExpr; break; case Stmt::ArraySubscriptExprClass: K = CXCursor_ArraySubscriptExpr; break; case Stmt::BinaryOperatorClass: K = CXCursor_BinaryOperator; break; case Stmt::CompoundAssignOperatorClass: K = CXCursor_CompoundAssignOperator; break; case Stmt::ConditionalOperatorClass: K = CXCursor_ConditionalOperator; break; case Stmt::CStyleCastExprClass: K = CXCursor_CStyleCastExpr; break; case Stmt::CompoundLiteralExprClass: K = CXCursor_CompoundLiteralExpr; break; case Stmt::InitListExprClass: K = CXCursor_InitListExpr; break; case Stmt::AddrLabelExprClass: K = CXCursor_AddrLabelExpr; break; case Stmt::StmtExprClass: K = CXCursor_StmtExpr; break; case Stmt::GenericSelectionExprClass: K = CXCursor_GenericSelectionExpr; break; case Stmt::GNUNullExprClass: K = CXCursor_GNUNullExpr; break; case Stmt::CXXStaticCastExprClass: K = CXCursor_CXXStaticCastExpr; break; case Stmt::CXXDynamicCastExprClass: K = CXCursor_CXXDynamicCastExpr; break; case Stmt::CXXReinterpretCastExprClass: K = CXCursor_CXXReinterpretCastExpr; break; case Stmt::CXXConstCastExprClass: K = CXCursor_CXXConstCastExpr; break; case Stmt::CXXFunctionalCastExprClass: K = CXCursor_CXXFunctionalCastExpr; break; case Stmt::CXXTypeidExprClass: K = CXCursor_CXXTypeidExpr; break; case Stmt::CXXBoolLiteralExprClass: K = CXCursor_CXXBoolLiteralExpr; break; case Stmt::CXXNullPtrLiteralExprClass: K = CXCursor_CXXNullPtrLiteralExpr; break; case Stmt::CXXThisExprClass: K = CXCursor_CXXThisExpr; break; case Stmt::CXXThrowExprClass: K = CXCursor_CXXThrowExpr; break; case Stmt::CXXNewExprClass: K = CXCursor_CXXNewExpr; break; case Stmt::CXXDeleteExprClass: K = CXCursor_CXXDeleteExpr; break; case Stmt::ObjCStringLiteralClass: K = CXCursor_ObjCStringLiteral; break; case Stmt::ObjCEncodeExprClass: K = CXCursor_ObjCEncodeExpr; break; case Stmt::ObjCSelectorExprClass: K = CXCursor_ObjCSelectorExpr; break; case Stmt::ObjCProtocolExprClass: K = CXCursor_ObjCProtocolExpr; break; case Stmt::ObjCBoolLiteralExprClass: K = CXCursor_ObjCBoolLiteralExpr; break; case Stmt::ObjCBridgedCastExprClass: K = CXCursor_ObjCBridgedCastExpr; break; case Stmt::BlockExprClass: K = CXCursor_BlockExpr; break; case Stmt::PackExpansionExprClass: K = CXCursor_PackExpansionExpr; break; case Stmt::SizeOfPackExprClass: K = CXCursor_SizeOfPackExpr; break; case Stmt::DeclRefExprClass: if (const ImplicitParamDecl *IPD = dyn_cast_or_null<ImplicitParamDecl>(cast<DeclRefExpr>(S)->getDecl())) { if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(IPD->getDeclContext())) { if (MD->getSelfDecl() == IPD) { K = CXCursor_ObjCSelfExpr; break; } } } K = CXCursor_DeclRefExpr; break; case Stmt::DependentScopeDeclRefExprClass: case Stmt::SubstNonTypeTemplateParmExprClass: case Stmt::SubstNonTypeTemplateParmPackExprClass: case Stmt::FunctionParmPackExprClass: case Stmt::UnresolvedLookupExprClass: case Stmt::TypoExprClass: // A typo could actually be a DeclRef or a MemberRef K = CXCursor_DeclRefExpr; break; case Stmt::CXXDependentScopeMemberExprClass: case Stmt::CXXPseudoDestructorExprClass: case Stmt::MemberExprClass: case Stmt::MSPropertyRefExprClass: case Stmt::ObjCIsaExprClass: case Stmt::ObjCIvarRefExprClass: case Stmt::ObjCPropertyRefExprClass: case Stmt::UnresolvedMemberExprClass: K = CXCursor_MemberRefExpr; break; case Stmt::CallExprClass: case Stmt::CXXOperatorCallExprClass: case Stmt::CXXMemberCallExprClass: case Stmt::CUDAKernelCallExprClass: case Stmt::CXXConstructExprClass: case Stmt::CXXTemporaryObjectExprClass: case Stmt::CXXUnresolvedConstructExprClass: case Stmt::UserDefinedLiteralClass: K = CXCursor_CallExpr; break; case Stmt::LambdaExprClass: K = CXCursor_LambdaExpr; break; case Stmt::ObjCMessageExprClass: { K = CXCursor_ObjCMessageExpr; int SelectorIdIndex = -1; // Check if cursor points to a selector id. if (RegionOfInterest.isValid() && RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) { SmallVector<SourceLocation, 16> SelLocs; cast<ObjCMessageExpr>(S)->getSelectorLocs(SelLocs); SmallVectorImpl<SourceLocation>::iterator I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin()); if (I != SelLocs.end()) SelectorIdIndex = I - SelLocs.begin(); } CXCursor C = { K, 0, { Parent, S, TU } }; return getSelectorIdentifierCursor(SelectorIdIndex, C); } case Stmt::MSDependentExistsStmtClass: K = CXCursor_UnexposedStmt; break; case Stmt::OMPParallelDirectiveClass: K = CXCursor_OMPParallelDirective; break; case Stmt::OMPSimdDirectiveClass: K = CXCursor_OMPSimdDirective; break; case Stmt::OMPForDirectiveClass: K = CXCursor_OMPForDirective; break; case Stmt::OMPForSimdDirectiveClass: K = CXCursor_OMPForSimdDirective; break; case Stmt::OMPSectionsDirectiveClass: K = CXCursor_OMPSectionsDirective; break; case Stmt::OMPSectionDirectiveClass: K = CXCursor_OMPSectionDirective; break; case Stmt::OMPSingleDirectiveClass: K = CXCursor_OMPSingleDirective; break; case Stmt::OMPMasterDirectiveClass: K = CXCursor_OMPMasterDirective; break; case Stmt::OMPCriticalDirectiveClass: K = CXCursor_OMPCriticalDirective; break; case Stmt::OMPParallelForDirectiveClass: K = CXCursor_OMPParallelForDirective; break; case Stmt::OMPParallelForSimdDirectiveClass: K = CXCursor_OMPParallelForSimdDirective; break; case Stmt::OMPParallelSectionsDirectiveClass: K = CXCursor_OMPParallelSectionsDirective; break; case Stmt::OMPTaskDirectiveClass: K = CXCursor_OMPTaskDirective; break; case Stmt::OMPTaskyieldDirectiveClass: K = CXCursor_OMPTaskyieldDirective; break; case Stmt::OMPBarrierDirectiveClass: K = CXCursor_OMPBarrierDirective; break; case Stmt::OMPTaskwaitDirectiveClass: K = CXCursor_OMPTaskwaitDirective; break; case Stmt::OMPTaskgroupDirectiveClass: K = CXCursor_OMPTaskgroupDirective; break; case Stmt::OMPFlushDirectiveClass: K = CXCursor_OMPFlushDirective; break; case Stmt::OMPOrderedDirectiveClass: K = CXCursor_OMPOrderedDirective; break; case Stmt::OMPAtomicDirectiveClass: K = CXCursor_OMPAtomicDirective; break; case Stmt::OMPTargetDirectiveClass: K = CXCursor_OMPTargetDirective; break; case Stmt::OMPTeamsDirectiveClass: K = CXCursor_OMPTeamsDirective; break; case Stmt::OMPCancellationPointDirectiveClass: K = CXCursor_OMPCancellationPointDirective; break; case Stmt::OMPCancelDirectiveClass: K = CXCursor_OMPCancelDirective; break; } CXCursor C = { K, 0, { Parent, S, TU } }; return C; } CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, SourceLocation Loc, CXTranslationUnit TU) { assert(Super && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_ObjCSuperClassRef, 0, { Super, RawLoc, TU } }; return C; } std::pair<const ObjCInterfaceDecl *, SourceLocation> cxcursor::getCursorObjCSuperClassRef(CXCursor C) { assert(C.kind == CXCursor_ObjCSuperClassRef); return std::make_pair(static_cast<const ObjCInterfaceDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto, SourceLocation Loc, CXTranslationUnit TU) { assert(Proto && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_ObjCProtocolRef, 0, { Proto, RawLoc, TU } }; return C; } std::pair<const ObjCProtocolDecl *, SourceLocation> cxcursor::getCursorObjCProtocolRef(CXCursor C) { assert(C.kind == CXCursor_ObjCProtocolRef); return std::make_pair(static_cast<const ObjCProtocolDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class, SourceLocation Loc, CXTranslationUnit TU) { // 'Class' can be null for invalid code. if (!Class) return MakeCXCursorInvalid(CXCursor_InvalidCode); assert(TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_ObjCClassRef, 0, { Class, RawLoc, TU } }; return C; } std::pair<const ObjCInterfaceDecl *, SourceLocation> cxcursor::getCursorObjCClassRef(CXCursor C) { assert(C.kind == CXCursor_ObjCClassRef); return std::make_pair(static_cast<const ObjCInterfaceDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc, CXTranslationUnit TU) { assert(Type && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_TypeRef, 0, { Type, RawLoc, TU } }; return C; } std::pair<const TypeDecl *, SourceLocation> cxcursor::getCursorTypeRef(CXCursor C) { assert(C.kind == CXCursor_TypeRef); return std::make_pair(static_cast<const TypeDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorTemplateRef(const TemplateDecl *Template, SourceLocation Loc, CXTranslationUnit TU) { assert(Template && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_TemplateRef, 0, { Template, RawLoc, TU } }; return C; } std::pair<const TemplateDecl *, SourceLocation> cxcursor::getCursorTemplateRef(CXCursor C) { assert(C.kind == CXCursor_TemplateRef); return std::make_pair(static_cast<const TemplateDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorNamespaceRef(const NamedDecl *NS, SourceLocation Loc, CXTranslationUnit TU) { assert(NS && (isa<NamespaceDecl>(NS) || isa<NamespaceAliasDecl>(NS)) && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_NamespaceRef, 0, { NS, RawLoc, TU } }; return C; } std::pair<const NamedDecl *, SourceLocation> cxcursor::getCursorNamespaceRef(CXCursor C) { assert(C.kind == CXCursor_NamespaceRef); return std::make_pair(static_cast<const NamedDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc, CXTranslationUnit TU) { assert(Var && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_VariableRef, 0, { Var, RawLoc, TU } }; return C; } std::pair<const VarDecl *, SourceLocation> cxcursor::getCursorVariableRef(CXCursor C) { assert(C.kind == CXCursor_VariableRef); return std::make_pair(static_cast<const VarDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc, CXTranslationUnit TU) { assert(Field && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_MemberRef, 0, { Field, RawLoc, TU } }; return C; } std::pair<const FieldDecl *, SourceLocation> cxcursor::getCursorMemberRef(CXCursor C) { assert(C.kind == CXCursor_MemberRef); return std::make_pair(static_cast<const FieldDecl *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B, CXTranslationUnit TU){ CXCursor C = { CXCursor_CXXBaseSpecifier, 0, { B, nullptr, TU } }; return C; } const CXXBaseSpecifier *cxcursor::getCursorCXXBaseSpecifier(CXCursor C) { assert(C.kind == CXCursor_CXXBaseSpecifier); return static_cast<const CXXBaseSpecifier*>(C.data[0]); } CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range, CXTranslationUnit TU) { CXCursor C = { CXCursor_PreprocessingDirective, 0, { Range.getBegin().getPtrEncoding(), Range.getEnd().getPtrEncoding(), TU } }; return C; } SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) { assert(C.kind == CXCursor_PreprocessingDirective); SourceRange Range(SourceLocation::getFromPtrEncoding(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); ASTUnit *TU = getCursorASTUnit(C); return TU->mapRangeFromPreamble(Range); } CXCursor cxcursor::MakeMacroDefinitionCursor(const MacroDefinitionRecord *MI, CXTranslationUnit TU) { CXCursor C = {CXCursor_MacroDefinition, 0, {MI, nullptr, TU}}; return C; } const MacroDefinitionRecord *cxcursor::getCursorMacroDefinition(CXCursor C) { assert(C.kind == CXCursor_MacroDefinition); return static_cast<const MacroDefinitionRecord *>(C.data[0]); } CXCursor cxcursor::MakeMacroExpansionCursor(MacroExpansion *MI, CXTranslationUnit TU) { CXCursor C = { CXCursor_MacroExpansion, 0, { MI, nullptr, TU } }; return C; } CXCursor cxcursor::MakeMacroExpansionCursor(MacroDefinitionRecord *MI, SourceLocation Loc, CXTranslationUnit TU) { assert(Loc.isValid()); CXCursor C = {CXCursor_MacroExpansion, 0, {MI, Loc.getPtrEncoding(), TU}}; return C; } const IdentifierInfo *cxcursor::MacroExpansionCursor::getName() const { if (isPseudo()) return getAsMacroDefinition()->getName(); return getAsMacroExpansion()->getName(); } const MacroDefinitionRecord * cxcursor::MacroExpansionCursor::getDefinition() const { if (isPseudo()) return getAsMacroDefinition(); return getAsMacroExpansion()->getDefinition(); } SourceRange cxcursor::MacroExpansionCursor::getSourceRange() const { if (isPseudo()) return getPseudoLoc(); return getAsMacroExpansion()->getSourceRange(); } CXCursor cxcursor::MakeInclusionDirectiveCursor(InclusionDirective *ID, CXTranslationUnit TU) { CXCursor C = { CXCursor_InclusionDirective, 0, { ID, nullptr, TU } }; return C; } const InclusionDirective *cxcursor::getCursorInclusionDirective(CXCursor C) { assert(C.kind == CXCursor_InclusionDirective); return static_cast<const InclusionDirective *>(C.data[0]); } CXCursor cxcursor::MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc, CXTranslationUnit TU) { assert(Label && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); CXCursor C = { CXCursor_LabelRef, 0, { Label, RawLoc, TU } }; return C; } std::pair<const LabelStmt *, SourceLocation> cxcursor::getCursorLabelRef(CXCursor C) { assert(C.kind == CXCursor_LabelRef); return std::make_pair(static_cast<const LabelStmt *>(C.data[0]), SourceLocation::getFromPtrEncoding(C.data[1])); } CXCursor cxcursor::MakeCursorOverloadedDeclRef(const OverloadExpr *E, CXTranslationUnit TU) { assert(E && TU && "Invalid arguments!"); OverloadedDeclRefStorage Storage(E); void *RawLoc = E->getNameLoc().getPtrEncoding(); CXCursor C = { CXCursor_OverloadedDeclRef, 0, { Storage.getOpaqueValue(), RawLoc, TU } }; return C; } CXCursor cxcursor::MakeCursorOverloadedDeclRef(const Decl *D, SourceLocation Loc, CXTranslationUnit TU) { assert(D && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); OverloadedDeclRefStorage Storage(D); CXCursor C = { CXCursor_OverloadedDeclRef, 0, { Storage.getOpaqueValue(), RawLoc, TU } }; return C; } CXCursor cxcursor::MakeCursorOverloadedDeclRef(TemplateName Name, SourceLocation Loc, CXTranslationUnit TU) { assert(Name.getAsOverloadedTemplate() && TU && "Invalid arguments!"); void *RawLoc = Loc.getPtrEncoding(); OverloadedDeclRefStorage Storage(Name.getAsOverloadedTemplate()); CXCursor C = { CXCursor_OverloadedDeclRef, 0, { Storage.getOpaqueValue(), RawLoc, TU } }; return C; } std::pair<cxcursor::OverloadedDeclRefStorage, SourceLocation> cxcursor::getCursorOverloadedDeclRef(CXCursor C) { assert(C.kind == CXCursor_OverloadedDeclRef); return std::make_pair(OverloadedDeclRefStorage::getFromOpaqueValue( const_cast<void *>(C.data[0])), SourceLocation::getFromPtrEncoding(C.data[1])); } const Decl *cxcursor::getCursorDecl(CXCursor Cursor) { return static_cast<const Decl *>(Cursor.data[0]); } const Expr *cxcursor::getCursorExpr(CXCursor Cursor) { return dyn_cast_or_null<Expr>(getCursorStmt(Cursor)); } const Stmt *cxcursor::getCursorStmt(CXCursor Cursor) { if (Cursor.kind == CXCursor_ObjCSuperClassRef || Cursor.kind == CXCursor_ObjCProtocolRef || Cursor.kind == CXCursor_ObjCClassRef) return nullptr; return static_cast<const Stmt *>(Cursor.data[1]); } const Attr *cxcursor::getCursorAttr(CXCursor Cursor) { return static_cast<const Attr *>(Cursor.data[1]); } const Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) { return static_cast<const Decl *>(Cursor.data[0]); } ASTContext &cxcursor::getCursorContext(CXCursor Cursor) { return getCursorASTUnit(Cursor)->getASTContext(); } ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) { CXTranslationUnit TU = getCursorTU(Cursor); if (!TU) return nullptr; return cxtu::getASTUnit(TU); } CXTranslationUnit cxcursor::getCursorTU(CXCursor Cursor) { return static_cast<CXTranslationUnit>(const_cast<void*>(Cursor.data[2])); } void cxcursor::getOverriddenCursors(CXCursor cursor, SmallVectorImpl<CXCursor> &overridden) { assert(clang_isDeclaration(cursor.kind)); const NamedDecl *D = dyn_cast_or_null<NamedDecl>(getCursorDecl(cursor)); if (!D) return; CXTranslationUnit TU = getCursorTU(cursor); SmallVector<const NamedDecl *, 8> OverDecls; D->getASTContext().getOverriddenMethods(D, OverDecls); for (SmallVectorImpl<const NamedDecl *>::iterator I = OverDecls.begin(), E = OverDecls.end(); I != E; ++I) { overridden.push_back(MakeCXCursor(*I, TU)); } } std::pair<int, SourceLocation> cxcursor::getSelectorIdentifierIndexAndLoc(CXCursor cursor) { if (cursor.kind == CXCursor_ObjCMessageExpr) { if (cursor.xdata != -1) return std::make_pair(cursor.xdata, cast<ObjCMessageExpr>(getCursorExpr(cursor)) ->getSelectorLoc(cursor.xdata)); } else if (cursor.kind == CXCursor_ObjCClassMethodDecl || cursor.kind == CXCursor_ObjCInstanceMethodDecl) { if (cursor.xdata != -1) return std::make_pair(cursor.xdata, cast<ObjCMethodDecl>(getCursorDecl(cursor)) ->getSelectorLoc(cursor.xdata)); } return std::make_pair(-1, SourceLocation()); } CXCursor cxcursor::getSelectorIdentifierCursor(int SelIdx, CXCursor cursor) { CXCursor newCursor = cursor; if (cursor.kind == CXCursor_ObjCMessageExpr) { if (SelIdx == -1 || unsigned(SelIdx) >= cast<ObjCMessageExpr>(getCursorExpr(cursor)) ->getNumSelectorLocs()) newCursor.xdata = -1; else newCursor.xdata = SelIdx; } else if (cursor.kind == CXCursor_ObjCClassMethodDecl || cursor.kind == CXCursor_ObjCInstanceMethodDecl) { if (SelIdx == -1 || unsigned(SelIdx) >= cast<ObjCMethodDecl>(getCursorDecl(cursor)) ->getNumSelectorLocs()) newCursor.xdata = -1; else newCursor.xdata = SelIdx; } return newCursor; } CXCursor cxcursor::getTypeRefCursor(CXCursor cursor) { if (cursor.kind != CXCursor_CallExpr) return cursor; if (cursor.xdata == 0) return cursor; const Expr *E = getCursorExpr(cursor); TypeSourceInfo *Type = nullptr; if (const CXXUnresolvedConstructExpr * UnCtor = dyn_cast<CXXUnresolvedConstructExpr>(E)) { Type = UnCtor->getTypeSourceInfo(); } else if (const CXXTemporaryObjectExpr *Tmp = dyn_cast<CXXTemporaryObjectExpr>(E)){ Type = Tmp->getTypeSourceInfo(); } if (!Type) return cursor; CXTranslationUnit TU = getCursorTU(cursor); QualType Ty = Type->getType(); TypeLoc TL = Type->getTypeLoc(); SourceLocation Loc = TL.getBeginLoc(); if (const ElaboratedType *ElabT = Ty->getAs<ElaboratedType>()) { Ty = ElabT->getNamedType(); ElaboratedTypeLoc ElabTL = TL.castAs<ElaboratedTypeLoc>(); Loc = ElabTL.getNamedTypeLoc().getBeginLoc(); } if (const TypedefType *Typedef = Ty->getAs<TypedefType>()) return MakeCursorTypeRef(Typedef->getDecl(), Loc, TU); if (const TagType *Tag = Ty->getAs<TagType>()) return MakeCursorTypeRef(Tag->getDecl(), Loc, TU); if (const TemplateTypeParmType *TemplP = Ty->getAs<TemplateTypeParmType>()) return MakeCursorTypeRef(TemplP->getDecl(), Loc, TU); return cursor; } bool cxcursor::operator==(CXCursor X, CXCursor Y) { return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] && X.data[2] == Y.data[2]; } // FIXME: Remove once we can model DeclGroups and their appropriate ranges // properly in the ASTs. bool cxcursor::isFirstInDeclGroup(CXCursor C) { assert(clang_isDeclaration(C.kind)); return ((uintptr_t) (C.data[1])) != 0; } //===----------------------------------------------------------------------===// // libclang CXCursor APIs //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. int clang_Cursor_isNull(CXCursor cursor) { return clang_equalCursors(cursor, clang_getNullCursor()); } CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor cursor) { return getCursorTU(cursor); } int clang_Cursor_getNumArguments(CXCursor C) { if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) return MD->param_size(); if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) return FD->param_size(); } if (clang_isExpression(C.kind)) { const Expr *E = cxcursor::getCursorExpr(C); if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { return CE->getNumArgs(); } } return -1; } CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i) { if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) { if (i < MD->param_size()) return cxcursor::MakeCXCursor(MD->parameters()[i], cxcursor::getCursorTU(C)); } else if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { if (i < FD->param_size()) return cxcursor::MakeCXCursor(FD->parameters()[i], cxcursor::getCursorTU(C)); } } if (clang_isExpression(C.kind)) { const Expr *E = cxcursor::getCursorExpr(C); if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { if (i < CE->getNumArgs()) { return cxcursor::MakeCXCursor(CE->getArg(i), getCursorDecl(C), cxcursor::getCursorTU(C)); } } } return clang_getNullCursor(); } int clang_Cursor_getNumTemplateArguments(CXCursor C) { if (clang_getCursorKind(C) != CXCursor_FunctionDecl) { return -1; } const FunctionDecl *FD = llvm::dyn_cast_or_null<clang::FunctionDecl>( getCursorDecl(C)); if (!FD) { return -1; } const FunctionTemplateSpecializationInfo* SpecInfo = FD->getTemplateSpecializationInfo(); if (!SpecInfo) { return -1; } return SpecInfo->TemplateArguments->size(); } enum CXGetTemplateArgumentStatus { /** \brief The operation completed successfully */ CXGetTemplateArgumentStatus_Success = 0, /** \brief The specified cursor did not represent a FunctionDecl. */ CXGetTemplateArgumentStatus_CursorNotFunctionDecl = -1, /** \brief The specified cursor was not castable to a FunctionDecl. */ CXGetTemplateArgumentStatus_BadFunctionDeclCast = -2, /** \brief A NULL FunctionTemplateSpecializationInfo was retrieved. */ CXGetTemplateArgumentStatus_NullTemplSpecInfo = -3, /** \brief An invalid (OOB) argument index was specified */ CXGetTemplateArgumentStatus_InvalidIndex = -4 }; static int clang_Cursor_getTemplateArgument( CXCursor C, unsigned I, TemplateArgument *TA) { if (clang_getCursorKind(C) != CXCursor_FunctionDecl) { return CXGetTemplateArgumentStatus_CursorNotFunctionDecl; } const FunctionDecl *FD = llvm::dyn_cast_or_null<clang::FunctionDecl>( getCursorDecl(C)); if (!FD) { return CXGetTemplateArgumentStatus_BadFunctionDeclCast; } const FunctionTemplateSpecializationInfo* SpecInfo = FD->getTemplateSpecializationInfo(); if (!SpecInfo) { return CXGetTemplateArgumentStatus_NullTemplSpecInfo; } if (I >= SpecInfo->TemplateArguments->size()) { return CXGetTemplateArgumentStatus_InvalidIndex; } *TA = SpecInfo->TemplateArguments->get(I); return 0; } enum CXTemplateArgumentKind clang_Cursor_getTemplateArgumentKind(CXCursor C, unsigned I) { TemplateArgument TA; if (clang_Cursor_getTemplateArgument(C, I, &TA)) { return CXTemplateArgumentKind_Invalid; } switch (TA.getKind()) { case TemplateArgument::Null: return CXTemplateArgumentKind_Null; case TemplateArgument::Type: return CXTemplateArgumentKind_Type; case TemplateArgument::Declaration: return CXTemplateArgumentKind_Declaration; case TemplateArgument::NullPtr: return CXTemplateArgumentKind_NullPtr; case TemplateArgument::Integral: return CXTemplateArgumentKind_Integral; case TemplateArgument::Template: return CXTemplateArgumentKind_Template; case TemplateArgument::TemplateExpansion: return CXTemplateArgumentKind_TemplateExpansion; case TemplateArgument::Expression: return CXTemplateArgumentKind_Expression; case TemplateArgument::Pack: return CXTemplateArgumentKind_Pack; } return CXTemplateArgumentKind_Invalid; } CXType clang_Cursor_getTemplateArgumentType(CXCursor C, unsigned I) { TemplateArgument TA; if (clang_Cursor_getTemplateArgument(C, I, &TA) != CXGetTemplateArgumentStatus_Success) { return cxtype::MakeCXType(QualType(), getCursorTU(C)); } if (TA.getKind() != TemplateArgument::Type) { return cxtype::MakeCXType(QualType(), getCursorTU(C)); } return cxtype::MakeCXType(TA.getAsType(), getCursorTU(C)); } long long clang_Cursor_getTemplateArgumentValue(CXCursor C, unsigned I) { TemplateArgument TA; if (clang_Cursor_getTemplateArgument(C, I, &TA) != CXGetTemplateArgumentStatus_Success) { assert(0 && "Unable to retrieve TemplateArgument"); return 0; } if (TA.getKind() != TemplateArgument::Integral) { assert(0 && "Passed template argument is not Integral"); return 0; } return TA.getAsIntegral().getSExtValue(); } unsigned long long clang_Cursor_getTemplateArgumentUnsignedValue(CXCursor C, unsigned I) { TemplateArgument TA; if (clang_Cursor_getTemplateArgument(C, I, &TA) != CXGetTemplateArgumentStatus_Success) { assert(0 && "Unable to retrieve TemplateArgument"); return 0; } if (TA.getKind() != TemplateArgument::Integral) { assert(0 && "Passed template argument is not Integral"); return 0; } return TA.getAsIntegral().getZExtValue(); } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // CXCursorSet. //===----------------------------------------------------------------------===// typedef llvm::DenseMap<CXCursor, unsigned> CXCursorSet_Impl; static inline CXCursorSet packCXCursorSet(CXCursorSet_Impl *setImpl) { return (CXCursorSet) setImpl; } static inline CXCursorSet_Impl *unpackCXCursorSet(CXCursorSet set) { return (CXCursorSet_Impl*) set; } namespace llvm { template<> struct DenseMapInfo<CXCursor> { public: static inline CXCursor getEmptyKey() { return MakeCXCursorInvalid(CXCursor_InvalidFile); } static inline CXCursor getTombstoneKey() { return MakeCXCursorInvalid(CXCursor_NoDeclFound); } static inline unsigned getHashValue(const CXCursor &cursor) { return llvm::DenseMapInfo<std::pair<const void *, const void *> > ::getHashValue(std::make_pair(cursor.data[0], cursor.data[1])); } static inline bool isEqual(const CXCursor &x, const CXCursor &y) { return x.kind == y.kind && x.data[0] == y.data[0] && x.data[1] == y.data[1]; } }; } // extern "C" { // HLSL Change -Don't use c linkage. CXCursorSet clang_createCXCursorSet() { return packCXCursorSet(new CXCursorSet_Impl()); } void clang_disposeCXCursorSet(CXCursorSet set) { delete unpackCXCursorSet(set); } unsigned clang_CXCursorSet_contains(CXCursorSet set, CXCursor cursor) { CXCursorSet_Impl *setImpl = unpackCXCursorSet(set); if (!setImpl) return 0; return setImpl->find(cursor) != setImpl->end(); } unsigned clang_CXCursorSet_insert(CXCursorSet set, CXCursor cursor) { // Do not insert invalid cursors into the set. if (cursor.kind >= CXCursor_FirstInvalid && cursor.kind <= CXCursor_LastInvalid) return 1; CXCursorSet_Impl *setImpl = unpackCXCursorSet(set); if (!setImpl) return 1; unsigned &entry = (*setImpl)[cursor]; unsigned flag = entry == 0 ? 1 : 0; entry = 1; return flag; } CXCompletionString clang_getCursorCompletionString(CXCursor cursor) { enum CXCursorKind kind = clang_getCursorKind(cursor); if (clang_isDeclaration(kind)) { const Decl *decl = getCursorDecl(cursor); if (const NamedDecl *namedDecl = dyn_cast_or_null<NamedDecl>(decl)) { ASTUnit *unit = getCursorASTUnit(cursor); CodeCompletionResult Result(namedDecl, CCP_Declaration); CodeCompletionString *String = Result.CreateCodeCompletionString(unit->getASTContext(), unit->getPreprocessor(), CodeCompletionContext::CCC_Other, unit->getCodeCompletionTUInfo().getAllocator(), unit->getCodeCompletionTUInfo(), true); return String; } } else if (kind == CXCursor_MacroDefinition) { const MacroDefinitionRecord *definition = getCursorMacroDefinition(cursor); const IdentifierInfo *MacroInfo = definition->getName(); ASTUnit *unit = getCursorASTUnit(cursor); CodeCompletionResult Result(MacroInfo); CodeCompletionString *String = Result.CreateCodeCompletionString(unit->getASTContext(), unit->getPreprocessor(), CodeCompletionContext::CCC_Other, unit->getCodeCompletionTUInfo().getAllocator(), unit->getCodeCompletionTUInfo(), false); return String; } return nullptr; } // } // end: extern C. // HLSL Change -Don't use c linkage. namespace { struct OverridenCursorsPool { typedef SmallVector<CXCursor, 2> CursorVec; std::vector<CursorVec*> AllCursors; std::vector<CursorVec*> AvailableCursors; ~OverridenCursorsPool() { for (std::vector<CursorVec*>::iterator I = AllCursors.begin(), E = AllCursors.end(); I != E; ++I) { delete *I; } } }; } void *cxcursor::createOverridenCXCursorsPool() { return new OverridenCursorsPool(); } void cxcursor::disposeOverridenCXCursorsPool(void *pool) { delete static_cast<OverridenCursorsPool*>(pool); } // extern "C" { // HLSL Change -Don't use c linkage. void clang_getOverriddenCursors(CXCursor cursor, CXCursor **overridden, unsigned *num_overridden) { if (overridden) *overridden = nullptr; if (num_overridden) *num_overridden = 0; CXTranslationUnit TU = cxcursor::getCursorTU(cursor); if (!overridden || !num_overridden || !TU) return; if (!clang_isDeclaration(cursor.kind)) return; OverridenCursorsPool &pool = *static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool); OverridenCursorsPool::CursorVec *Vec = nullptr; if (!pool.AvailableCursors.empty()) { Vec = pool.AvailableCursors.back(); pool.AvailableCursors.pop_back(); } else { Vec = new OverridenCursorsPool::CursorVec(); pool.AllCursors.push_back(Vec); } // Clear out the vector, but don't free the memory contents. This // reduces malloc() traffic. Vec->clear(); // Use the first entry to contain a back reference to the vector. // This is a complete hack. CXCursor backRefCursor = MakeCXCursorInvalid(CXCursor_InvalidFile, TU); backRefCursor.data[0] = Vec; assert(cxcursor::getCursorTU(backRefCursor) == TU); Vec->push_back(backRefCursor); // Get the overriden cursors. cxcursor::getOverriddenCursors(cursor, *Vec); // Did we get any overriden cursors? If not, return Vec to the pool // of available cursor vectors. if (Vec->size() == 1) { pool.AvailableCursors.push_back(Vec); return; } // Now tell the caller about the overriden cursors. assert(Vec->size() > 1); *overridden = &((*Vec)[1]); *num_overridden = Vec->size() - 1; } void clang_disposeOverriddenCursors(CXCursor *overridden) { if (!overridden) return; // Use pointer arithmetic to get back the first faux entry // which has a back-reference to the TU and the vector. --overridden; OverridenCursorsPool::CursorVec *Vec = static_cast<OverridenCursorsPool::CursorVec *>( const_cast<void *>(overridden->data[0])); CXTranslationUnit TU = getCursorTU(*overridden); assert(Vec && TU); OverridenCursorsPool &pool = *static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool); pool.AvailableCursors.push_back(Vec); } int clang_Cursor_isDynamicCall(CXCursor C) { const Expr *E = nullptr; if (clang_isExpression(C.kind)) E = getCursorExpr(C); if (!E) return 0; if (const ObjCMessageExpr *MsgE = dyn_cast<ObjCMessageExpr>(E)) { if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance) return false; if (auto *RecE = dyn_cast<ObjCMessageExpr>( MsgE->getInstanceReceiver()->IgnoreParenCasts())) { if (RecE->getMethodFamily() == OMF_alloc) return false; } return true; } const MemberExpr *ME = nullptr; if (isa<MemberExpr>(E)) ME = cast<MemberExpr>(E); else if (const CallExpr *CE = dyn_cast<CallExpr>(E)) ME = dyn_cast_or_null<MemberExpr>(CE->getCallee()); if (ME) { if (const CXXMethodDecl * MD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl())) return MD->isVirtual() && !ME->hasQualifier(); } return 0; } CXType clang_Cursor_getReceiverType(CXCursor C) { CXTranslationUnit TU = cxcursor::getCursorTU(C); const Expr *E = nullptr; if (clang_isExpression(C.kind)) E = getCursorExpr(C); if (const ObjCMessageExpr *MsgE = dyn_cast_or_null<ObjCMessageExpr>(E)) return cxtype::MakeCXType(MsgE->getReceiverType(), TU); return cxtype::MakeCXType(QualType(), TU); } // } // end: extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexer.cpp
//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Clang-C Source Indexing library. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Version.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Program.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> #include <sstream> #include <vector> #ifdef __CYGWIN__ #include <cygwin/version.h> #include <sys/cygwin.h> #define LLVM_ON_WIN32 1 #endif #ifdef LLVM_ON_WIN32 #include <windows.h> #else #include <dlfcn.h> #endif using namespace clang; const std::string &CIndexer::getClangResourcesPath() { // HLSL Change Starts - never have a DLL-relative path #if 1 return ResourcesPath; #else // Did we already compute the path? if (!ResourcesPath.empty()) return ResourcesPath; SmallString<128> LibClangPath; // Find the location where this library lives (libclang.dylib). #ifdef LLVM_ON_WIN32 MEMORY_BASIC_INFORMATION mbi; char path[MAX_PATH]; VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi, sizeof(mbi)); GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH); #ifdef __CYGWIN__ char w32path[MAX_PATH]; strcpy(w32path, path); #if CYGWIN_VERSION_API_MAJOR > 0 || CYGWIN_VERSION_API_MINOR >= 181 cygwin_conv_path(CCP_WIN_A_TO_POSIX, w32path, path, MAX_PATH); #else cygwin_conv_to_full_posix_path(w32path, path); #endif #endif LibClangPath += llvm::sys::path::parent_path(path); #else // This silly cast below avoids a C++ warning. Dl_info info; if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0) llvm_unreachable("Call to dladdr() failed"); // We now have the CIndex directory, locate clang relative to it. LibClangPath += llvm::sys::path::parent_path(info.dli_fname); #endif llvm::sys::path::append(LibClangPath, "clang", CLANG_VERSION_STRING); // Cache our result. ResourcesPath = LibClangPath.str(); return ResourcesPath; #endif // HLSL Change Ends }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexer.h
//===- CIndexer.h - Clang-C Source Indexing Library -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines CIndexer, a subclass of Indexer that provides extra // functionality needed by the CIndex library. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CINDEXER_H #define LLVM_CLANG_TOOLS_LIBCLANG_CINDEXER_H #include "clang-c/Index.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Lex/ModuleLoader.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" #include <vector> // HLSL Change Starts namespace hlsl { class DxcLangExtensionsHelperApply; } // HLSL Change Ends namespace llvm { class CrashRecoveryContext; } namespace clang { class ASTUnit; class MacroInfo; class MacroDefinitionRecord; class SourceLocation; class Token; class IdentifierInfo; class CIndexer { bool OnlyLocalDecls; bool DisplayDiagnostics; unsigned Options; // CXGlobalOptFlags. std::string ResourcesPath; std::shared_ptr<PCHContainerOperations> PCHContainerOps; public: CIndexer(std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()) : OnlyLocalDecls(false), DisplayDiagnostics(false), Options(CXGlobalOpt_None), PCHContainerOps(PCHContainerOps) {} hlsl::DxcLangExtensionsHelperApply *HlslLangExtensions = nullptr; // HLSL Change /// \brief Whether we only want to see "local" declarations (that did not /// come from a previous precompiled header). If false, we want to see all /// declarations. bool getOnlyLocalDecls() const { return OnlyLocalDecls; } void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; } bool getDisplayDiagnostics() const { return DisplayDiagnostics; } void setDisplayDiagnostics(bool Display = true) { DisplayDiagnostics = Display; } std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const { return PCHContainerOps; } unsigned getCXGlobalOptFlags() const { return Options; } void setCXGlobalOptFlags(unsigned options) { Options = options; } bool isOptEnabled(CXGlobalOptFlags opt) const { return Options & opt; } /// \brief Get the path of the clang resource files. const std::string &getClangResourcesPath(); }; /// \brief Return the current size to request for "safety". unsigned GetSafetyThreadStackSize(); /// \brief Set the current size to request for "safety" (or 0, if safety /// threads should not be used). void SetSafetyThreadStackSize(unsigned Value); /// \brief Execution the given code "safely", using crash recovery or safety /// threads when possible. /// /// \return False if a crash was detected. bool RunSafely(llvm::CrashRecoveryContext &CRC, void (*Fn)(void*), void *UserData, unsigned Size = 0); /// \brief Set the thread priority to background. /// FIXME: Move to llvm/Support. void setThreadBackgroundPriority(); /// \brief Print libclang's resource usage to standard error. void PrintLibclangResourceUsage(CXTranslationUnit TU); namespace cxindex { void printDiagsToStderr(ASTUnit *Unit); /// \brief If \c MacroDefLoc points at a macro definition with \c II as /// its name, this retrieves its MacroInfo. MacroInfo *getMacroInfo(const IdentifierInfo &II, SourceLocation MacroDefLoc, CXTranslationUnit TU); /// \brief Retrieves the corresponding MacroInfo of a MacroDefinitionRecord. const MacroInfo *getMacroInfo(const MacroDefinitionRecord *MacroDef, CXTranslationUnit TU); /// \brief If \c Loc resides inside the definition of \c MI and it points at /// an identifier that has ever been a macro name, this returns the latest /// MacroDefinitionRecord for that name, otherwise it returns NULL. MacroDefinitionRecord *checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, CXTranslationUnit TU); /// \brief If \c Tok resides inside the definition of \c MI and it points at /// an identifier that has ever been a macro name, this returns the latest /// MacroDefinitionRecord for that name, otherwise it returns NULL. MacroDefinitionRecord *checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, CXTranslationUnit TU); } } #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXString.h
//===- CXString.h - Routines for manipulating CXStrings -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXStrings. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXSTRING_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXSTRING_H #include "clang-c/Index.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include <string> #include <vector> namespace clang { namespace cxstring { struct CXStringBuf; /// \brief Create a CXString object for an empty "" string. CXString createEmpty(); /// \brief Create a CXString object for an NULL string. /// /// A NULL string should be used as an "invalid" value in case of errors. CXString createNull(); /// \brief Create a CXString object from a nul-terminated C string. New /// CXString may contain a pointer to \p String. /// /// \p String should not be changed by the caller afterwards. CXString createRef(const char *String); /// \brief Create a CXString object from a nul-terminated C string. New /// CXString will contain a copy of \p String. /// /// \p String can be changed or freed by the caller. CXString createDup(const char *String); /// \brief Create a CXString object from a StringRef. New CXString may /// contain a pointer to the undrelying data of \p String. /// /// \p String should not be changed by the caller afterwards. CXString createRef(StringRef String); /// \brief Create a CXString object from a StringRef. New CXString will /// contain a copy of \p String. /// /// \p String can be changed or freed by the caller. CXString createDup(StringRef String); // Usually std::string is intended to be used as backing storage for CXString. // In this case, call \c createRef(String.c_str()). // // If you need to make a copy, call \c createDup(StringRef(String)). CXString createRef(std::string String) = delete; /// \brief Create a CXString object that is backed by a string buffer. CXString createCXString(CXStringBuf *buf); /// \brief A string pool used for fast allocation/deallocation of strings. class CXStringPool { public: ~CXStringPool(); CXStringBuf *getCXStringBuf(CXTranslationUnit TU); private: std::vector<CXStringBuf *> Pool; friend struct CXStringBuf; }; struct CXStringBuf { SmallString<128> Data; CXTranslationUnit TU; CXStringBuf(CXTranslationUnit TU) : TU(TU) {} /// \brief Return this buffer to the pool. void dispose(); }; CXStringBuf *getCXStringBuf(CXTranslationUnit TU); /// \brief Returns true if the CXString data is managed by a pool. bool isManagedByPool(CXString str); } static inline StringRef getContents(const CXUnsavedFile &UF) { return StringRef(UF.Contents, UF.Length); } } #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndex.cpp
//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the main API hooks in the Clang-C Source Indexing // library. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CIndexDiagnostic.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXString.h" #include "CXTranslationUnit.h" #include "CXType.h" #include "CursorVisitor.h" #include "clang/AST/Attr.h" #include "clang/AST/Mangle.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticCategories.h" #include "clang/Basic/DiagnosticIDs.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Version.h" #include "clang/CodeGen/ObjectFilePCHContainerOperations.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Index/CommentToXML.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" #include "clang/Serialization/SerializationDiagnostic.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Mangler.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Program.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Threading.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/HlslTypes.h" // HLSL Change #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) #define USE_DARWIN_THREADS #endif #ifdef USE_DARWIN_THREADS #include <pthread.h> #endif using namespace clang; using namespace clang::cxcursor; using namespace clang::cxtu; using namespace clang::cxindex; CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) { if (!AU) return nullptr; assert(CIdx); CXTranslationUnit D = new CXTranslationUnitImpl(); D->CIdx = CIdx; D->TheASTUnit = AU; D->StringPool = new cxstring::CXStringPool(); D->Diagnostics = nullptr; D->OverridenCursorsPool = createOverridenCXCursorsPool(); D->CommentToXML = nullptr; return D; } bool cxtu::isASTReadError(ASTUnit *AU) { for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), DEnd = AU->stored_diag_end(); D != DEnd; ++D) { if (D->getLevel() >= DiagnosticsEngine::Error && DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == diag::DiagCat_AST_Deserialization_Issue) return true; } return false; } cxtu::CXTUOwner::~CXTUOwner() { if (TU) clang_disposeTranslationUnit(TU); } /// \brief Compare two source ranges to determine their relative position in /// the translation unit. static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1, SourceRange R2) { assert(R1.isValid() && "First range is invalid?"); assert(R2.isValid() && "Second range is invalid?"); if (R1.getEnd() != R2.getBegin() && SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) return RangeBefore; if (R2.getEnd() != R1.getBegin() && SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) return RangeAfter; return RangeOverlap; } /// \brief Determine if a source location falls within, before, or after a /// a given source range. static RangeComparisonResult LocationCompare(SourceManager &SM, SourceLocation L, SourceRange R) { assert(R.isValid() && "First range is invalid?"); assert(L.isValid() && "Second range is invalid?"); if (L == R.getBegin() || L == R.getEnd()) return RangeOverlap; if (SM.isBeforeInTranslationUnit(L, R.getBegin())) return RangeBefore; if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) return RangeAfter; return RangeOverlap; } /// \brief Translate a Clang source range into a CIndex source range. /// /// Clang internally represents ranges where the end location points to the /// start of the token at the end. However, for external clients it is more /// useful to have a CXSourceRange be a proper half-open interval. This routine /// does the appropriate translation. CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, const LangOptions &LangOpts, const CharSourceRange &R) { // We want the last character in this location, so we will adjust the // location accordingly. SourceLocation EndLoc = R.getEnd(); if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) EndLoc = SM.getExpansionRange(EndLoc).second; if (R.isTokenRange() && !EndLoc.isInvalid()) { unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts); EndLoc = EndLoc.getLocWithOffset(Length); } CXSourceRange Result = { { &SM, &LangOpts }, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding() }; return Result; } //===----------------------------------------------------------------------===// // Cursor visitor. //===----------------------------------------------------------------------===// static SourceRange getRawCursorExtent(CXCursor C); static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); } /// \brief Visit the given cursor and, if requested by the visitor, /// its children. /// /// \param Cursor the cursor to visit. /// /// \param CheckedRegionOfInterest if true, then the caller already checked /// that this cursor is within the region of interest. /// /// \returns true if the visitation should be aborted, false if it /// should continue. bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { if (clang_isInvalid(Cursor.kind)) return false; if (clang_isDeclaration(Cursor.kind)) { const Decl *D = getCursorDecl(Cursor); if (!D) { assert(0 && "Invalid declaration cursor"); return true; // abort. } // Ignore implicit declarations, unless it's an objc method because // currently we should report implicit methods for properties when indexing. if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) return false; } // If we have a range of interest, and this cursor doesn't intersect with it, // we're done. if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { SourceRange Range = getRawCursorExtent(Cursor); if (Range.isInvalid() || CompareRegionOfInterest(Range)) return false; } switch (Visitor(Cursor, Parent, ClientData)) { case CXChildVisit_Break: return true; case CXChildVisit_Continue: return false; case CXChildVisit_Recurse: { bool ret = VisitChildren(Cursor); if (PostChildrenVisitor) if (PostChildrenVisitor(Cursor, ClientData)) return true; return ret; } } llvm_unreachable("Invalid CXChildVisitResult!"); } static bool visitPreprocessedEntitiesInRange(SourceRange R, PreprocessingRecord &PPRec, CursorVisitor &Visitor) { SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); FileID FID; if (!Visitor.shouldVisitIncludedEntities()) { // If the begin/end of the range lie in the same FileID, do the optimization // where we skip preprocessed entities that do not come from the same FileID. FID = SM.getFileID(SM.getFileLoc(R.getBegin())); if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) FID = FileID(); } const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), PPRec, FID); } bool CursorVisitor::visitFileRegion() { if (RegionOfInterest.isInvalid()) return false; ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); if (End.first != Begin.first) { // If the end does not reside in the same file, try to recover by // picking the end of the file of begin location. End.first = Begin.first; End.second = SM.getFileIDSize(Begin.first); } assert(Begin.first == End.first); if (Begin.second > End.second) return false; FileID File = Begin.first; unsigned Offset = Begin.second; unsigned Length = End.second - Begin.second; if (!VisitDeclsOnly && !VisitPreprocessorLast) if (visitPreprocessedEntitiesInRegion()) return true; // visitation break. if (visitDeclsFromFileRegion(File, Offset, Length)) return true; // visitation break. if (!VisitDeclsOnly && VisitPreprocessorLast) return visitPreprocessedEntitiesInRegion(); return false; } static bool isInLexicalContext(Decl *D, DeclContext *DC) { if (!DC) return false; for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC; DeclDC = DeclDC->getLexicalParent()) { if (DeclDC == DC) return true; } return false; } bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset, unsigned Length) { ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); SourceRange Range = RegionOfInterest; SmallVector<Decl *, 16> Decls; Unit->findFileRegionDecls(File, Offset, Length, Decls); // If we didn't find any file level decls for the file, try looking at the // file that it was included from. while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { bool Invalid = false; const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); if (Invalid) return false; SourceLocation Outer; if (SLEntry.isFile()) Outer = SLEntry.getFile().getIncludeLoc(); else Outer = SLEntry.getExpansion().getExpansionLocStart(); if (Outer.isInvalid()) return false; std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); Length = 0; Unit->findFileRegionDecls(File, Offset, Length, Decls); } assert(!Decls.empty()); bool VisitedAtLeastOnce = false; DeclContext *CurDC = nullptr; SmallVectorImpl<Decl *>::iterator DIt = Decls.begin(); for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) { Decl *D = *DIt; if (D->getSourceRange().isInvalid()) continue; if (isInLexicalContext(D, CurDC)) continue; CurDC = dyn_cast<DeclContext>(D); if (TagDecl *TD = dyn_cast<TagDecl>(D)) if (!TD->isFreeStanding()) continue; RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); if (CompRes == RangeBefore) continue; if (CompRes == RangeAfter) break; assert(CompRes == RangeOverlap); VisitedAtLeastOnce = true; if (isa<ObjCContainerDecl>(D)) { FileDI_current = &DIt; FileDE_current = DE; } else { FileDI_current = nullptr; } if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) return true; // visitation break. } if (VisitedAtLeastOnce) return false; // No Decls overlapped with the range. Move up the lexical context until there // is a context that contains the range or we reach the translation unit // level. DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() : (*(DIt-1))->getLexicalDeclContext(); while (DC && !DC->isTranslationUnit()) { Decl *D = cast<Decl>(DC); SourceRange CurDeclRange = D->getSourceRange(); if (CurDeclRange.isInvalid()) break; if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) return true; // visitation break. } DC = D->getLexicalDeclContext(); } return false; } bool CursorVisitor::visitPreprocessedEntitiesInRegion() { if (!AU->getPreprocessor().getPreprocessingRecord()) return false; PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord(); SourceManager &SM = AU->getSourceManager(); if (RegionOfInterest.isValid()) { SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); SourceLocation B = MappedRange.getBegin(); SourceLocation E = MappedRange.getEnd(); if (AU->isInPreambleFileID(B)) { if (SM.isLoadedSourceLocation(E)) return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); // Beginning of range lies in the preamble but it also extends beyond // it into the main file. Split the range into 2 parts, one covering // the preamble and another covering the main file. This allows subsequent // calls to visitPreprocessedEntitiesInRange to accept a source range that // lies in the same FileID, allowing it to skip preprocessed entities that // do not come from the same FileID. bool breaked = visitPreprocessedEntitiesInRange( SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this); if (breaked) return true; return visitPreprocessedEntitiesInRange( SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this); } return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); } bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); if (OnlyLocalDecls) return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), PPRec); return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); } template<typename InputIterator> bool CursorVisitor::visitPreprocessedEntities(InputIterator First, InputIterator Last, PreprocessingRecord &PPRec, FileID FID) { for (; First != Last; ++First) { if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) continue; PreprocessedEntity *PPE = *First; if (!PPE) continue; if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { if (Visit(MakeMacroExpansionCursor(ME, TU))) return true; continue; } if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) { if (Visit(MakeMacroDefinitionCursor(MD, TU))) return true; continue; } if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { if (Visit(MakeInclusionDirectiveCursor(ID, TU))) return true; continue; } } return false; } /// \brief Visit the children of the given cursor. /// /// \returns true if the visitation should be aborted, false if it /// should continue. bool CursorVisitor::VisitChildren(CXCursor Cursor) { if (clang_isReference(Cursor.kind) && Cursor.kind != CXCursor_CXXBaseSpecifier) { // By definition, references have no children. return false; } // Set the Parent field to Cursor, then back to its old value once we're // done. SetParentRAII SetParent(Parent, StmtParent, Cursor); if (clang_isDeclaration(Cursor.kind)) { Decl *D = const_cast<Decl *>(getCursorDecl(Cursor)); if (!D) return false; return VisitAttributes(D) || Visit(D); } if (clang_isStatement(Cursor.kind)) { if (const Stmt *S = getCursorStmt(Cursor)) return Visit(S); return false; } if (clang_isExpression(Cursor.kind)) { if (const Expr *E = getCursorExpr(Cursor)) return Visit(E); return false; } if (clang_isTranslationUnit(Cursor.kind)) { CXTranslationUnit TU = getCursorTU(Cursor); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; for (unsigned I = 0; I != 2; ++I) { if (VisitOrder[I]) { if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && RegionOfInterest.isInvalid()) { for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), TLEnd = CXXUnit->top_level_end(); TL != TLEnd; ++TL) { if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true)) return true; } } else if (VisitDeclContext( CXXUnit->getASTContext().getTranslationUnitDecl())) return true; continue; } // Walk the preprocessing record. if (CXXUnit->getPreprocessor().getPreprocessingRecord()) visitPreprocessedEntitiesInRegion(); } return false; } if (Cursor.kind == CXCursor_CXXBaseSpecifier) { if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { return Visit(BaseTSInfo->getTypeLoc()); } } } if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { const IBOutletCollectionAttr *A = cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>()) return Visit(cxcursor::MakeCursorObjCClassRef( ObjT->getInterface(), A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU)); } // If pointing inside a macro definition, check if the token is an identifier // that was ever defined as a macro. In such a case, create a "pseudo" macro // expansion cursor for that token. SourceLocation BeginLoc = RegionOfInterest.getBegin(); if (Cursor.kind == CXCursor_MacroDefinition && BeginLoc == RegionOfInterest.getEnd()) { SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); const MacroInfo *MI = getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); if (MacroDefinitionRecord *MacroDef = checkForMacroInMacroDefinition(MI, Loc, TU)) return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); } // Nothing to visit at the moment. return false; } bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) if (Visit(TSInfo->getTypeLoc())) return true; if (Stmt *Body = B->getBody()) return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); return false; } Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { if (RegionOfInterest.isValid()) { SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); if (Range.isInvalid()) return None; switch (CompareRegionOfInterest(Range)) { case RangeBefore: // This declaration comes before the region of interest; skip it. return None; case RangeAfter: // This declaration comes after the region of interest; we're done. return false; case RangeOverlap: // This declaration overlaps the region of interest; visit it. break; } } return true; } bool CursorVisitor::VisitDeclContext(DeclContext *DC) { DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); // FIXME: Eventually remove. This part of a hack to support proper // iteration over all Decls contained lexically within an ObjC container. SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); for ( ; I != E; ++I) { Decl *D = *I; if (D->getLexicalDeclContext() != DC) continue; CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); // Ignore synthesized ivars here, otherwise if we have something like: // @synthesize prop = _prop; // and '_prop' is not declared, we will encounter a '_prop' ivar before // encountering the 'prop' synthesize declaration and we will think that // we passed the region-of-interest. if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) { if (ivarD->getSynthesize()) continue; } // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol // declarations is a mismatch with the compiler semantics. if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D); if (!ID->isThisDeclarationADefinition()) Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D); if (!PD->isThisDeclarationADefinition()) Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); } const Optional<bool> &V = shouldVisitCursor(Cursor); if (!V.hasValue()) continue; if (!V.getValue()) return false; if (Visit(Cursor, true)) return true; } return false; } bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { llvm_unreachable("Translation units are visited directly by Visit()"); } bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitClassTemplateSpecializationDecl( ClassTemplateSpecializationDecl *D) { bool ShouldVisitBody = false; switch (D->getSpecializationKind()) { case TSK_Undeclared: case TSK_ImplicitInstantiation: // Nothing to visit return false; case TSK_ExplicitInstantiationDeclaration: case TSK_ExplicitInstantiationDefinition: break; case TSK_ExplicitSpecialization: ShouldVisitBody = true; break; } // Visit the template arguments used in the specialization. if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { TypeLoc TL = SpecType->getTypeLoc(); if (TemplateSpecializationTypeLoc TSTLoc = TL.getAs<TemplateSpecializationTypeLoc>()) { for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) return true; } } if (ShouldVisitBody && VisitCXXRecordDecl(D)) return true; return false; } bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( ClassTemplatePartialSpecializationDecl *D) { // FIXME: Visit the "outer" template parameter lists on the TagDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; // Visit the partial specialization arguments. const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) if (VisitTemplateArgumentLoc(TemplateArgs[I])) return true; return VisitCXXRecordDecl(D); } bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { // Visit the default argument. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) if (Visit(DefArg->getTypeLoc())) return true; return false; } bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { if (Expr *Init = D->getInitExpr()) return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { unsigned NumParamList = DD->getNumTemplateParameterLists(); for (unsigned i = 0; i < NumParamList; i++) { TemplateParameterList* Params = DD->getTemplateParameterList(i); if (VisitTemplateParameters(Params)) return true; } if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) if (Visit(TSInfo->getTypeLoc())) return true; // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return false; } /// \brief Compare two base or member initializers based on their source order. static int __cdecl CompareCXXCtorInitializers(CXXCtorInitializer *const *X, // HLSL Change - __cdecl CXXCtorInitializer *const *Y) { return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); } bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { unsigned NumParamList = ND->getNumTemplateParameterLists(); for (unsigned i = 0; i < NumParamList; i++) { TemplateParameterList* Params = ND->getTemplateParameterList(i); if (VisitTemplateParameters(Params)) return true; } if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { // Visit the function declaration's syntactic components in the order // written. This requires a bit of work. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>(); // If we have a function declared directly (without the use of a typedef), // visit just the return type. Otherwise, just visit the function's type // now. if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) || (!FTL && Visit(TL))) return true; // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (!isa<CXXDestructorDecl>(ND)) if (VisitDeclarationNameInfo(ND->getNameInfo())) return true; // FIXME: Visit explicitly-specified template arguments! // Visit the function parameters, if we have a function type. if (FTL && VisitFunctionTypeLoc(FTL, true)) return true; // FIXME: Attributes? } if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { // Find the initializers that were written in the source. SmallVector<CXXCtorInitializer *, 4> WrittenInits; for (auto *I : Constructor->inits()) { if (!I->isWritten()) continue; WrittenInits.push_back(I); } // Sort the initializers in source order llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), &CompareCXXCtorInitializers); // Visit the initializers in source order for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { CXXCtorInitializer *Init = WrittenInits[I]; if (Init->isAnyMemberInitializer()) { if (Visit(MakeCursorMemberRef(Init->getAnyMember(), Init->getMemberLocation(), TU))) return true; } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { if (Visit(TInfo->getTypeLoc())) return true; } // Visit the initializer value. if (Expr *Initializer = Init->getInit()) if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) return true; } } if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (Expr *BitWidth = D->getBitWidth()) return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitVarDecl(VarDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (Expr *Init = D->getInit()) return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { if (VisitDeclaratorDecl(D)) return true; if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) if (Expr *DefArg = D->getDefaultArgument()) return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { // FIXME: Visit the "outer" template parameter lists on the FunctionDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; return VisitFunctionDecl(D->getTemplatedDecl()); } bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { // FIXME: Visit the "outer" template parameter lists on the TagDecl // before visiting these template parameters. if (VisitTemplateParameters(D->getTemplateParameters())) return true; return VisitCXXRecordDecl(D->getTemplatedDecl()); } bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { if (VisitTemplateParameters(D->getTemplateParameters())) return true; if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && VisitTemplateArgumentLoc(D->getDefaultArgument())) return true; return false; } bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { // Visit the bound, if it's explicit. if (D->hasExplicitBound()) { if (auto TInfo = D->getTypeSourceInfo()) { if (Visit(TInfo->getTypeLoc())) return true; } } return false; } bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) if (Visit(TSInfo->getTypeLoc())) return true; for (const auto *P : ND->params()) { if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) return true; } if (ND->isThisDeclarationADefinition() && Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) return true; return false; } template <typename DeclIt> static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, SourceManager &SM, SourceLocation EndLoc, SmallVectorImpl<Decl *> &Decls) { DeclIt next = *DI_current; while (++next != DE_current) { Decl *D_next = *next; if (!D_next) break; SourceLocation L = D_next->getLocStart(); if (!L.isValid()) break; if (SM.isBeforeInTranslationUnit(L, EndLoc)) { *DI_current = next; Decls.push_back(D_next); continue; } break; } } bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially // an @implementation can lexically contain Decls that are not properly // nested in the AST. When we identify such cases, we need to retrofit // this nesting here. if (!DI_current && !FileDI_current) return VisitDeclContext(D); // Scan the Decls that immediately come after the container // in the current DeclContext. If any fall within the // container's lexical region, stash them into a vector // for later processing. SmallVector<Decl *, 24> DeclsInContainer; SourceLocation EndLoc = D->getSourceRange().getEnd(); SourceManager &SM = AU->getSourceManager(); if (EndLoc.isValid()) { if (DI_current) { addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, DeclsInContainer); } else { addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, DeclsInContainer); } } // The common case. if (DeclsInContainer.empty()) return VisitDeclContext(D); // Get all the Decls in the DeclContext, and sort them with the // additional ones we've collected. Then visit them. for (auto *SubDecl : D->decls()) { if (!SubDecl || SubDecl->getLexicalDeclContext() != D || SubDecl->getLocStart().isInvalid()) continue; DeclsInContainer.push_back(SubDecl); } // Now sort the Decls so that they appear in lexical order. std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), [&SM](Decl *A, Decl *B) { SourceLocation L_A = A->getLocStart(); SourceLocation L_B = B->getLocStart(); assert(L_A.isValid() && L_B.isValid()); return SM.isBeforeInTranslationUnit(L_A, L_B); }); // Now visit the decls. for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), E = DeclsInContainer.end(); I != E; ++I) { CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); const Optional<bool> &V = shouldVisitCursor(Cursor); if (!V.hasValue()) continue; if (!V.getValue()) return false; if (Visit(Cursor, true)) return true; } return false; } bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), TU))) return true; if (VisitObjCTypeParamList(ND->getTypeParamList())) return true; ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), E = ND->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(ND); } bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { if (!PID->isThisDeclarationADefinition()) return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), E = PID->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(PID); } bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) return true; // FIXME: This implements a workaround with @property declarations also being // installed in the DeclContext for the @interface. Eventually this code // should be removed. ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); if (!CDecl || !CDecl->IsClassExtension()) return false; ObjCInterfaceDecl *ID = CDecl->getClassInterface(); if (!ID) return false; IdentifierInfo *PropertyId = PD->getIdentifier(); ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId); if (!prevDecl) return false; // Visit synthesized methods since they will be skipped when visiting // the @interface. if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) return true; if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) return true; return false; } bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { if (!typeParamList) return false; for (auto *typeParam : *typeParamList) { // Visit the type parameter. if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { if (!D->isThisDeclarationADefinition()) { // Forward declaration is treated like a reference. return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); } // Objective-C type parameters. if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) return true; // Issue callbacks for super class. if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), D->getSuperClassLoc(), TU))) return true; if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) if (Visit(SuperClassTInfo->getTypeLoc())) return true; ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), E = D->protocol_end(); I != E; ++I, ++PL) if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) return true; return VisitObjCContainerDecl(D); } bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { return VisitObjCContainerDecl(D); } bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { // 'ID' could be null when dealing with invalid code. if (ObjCInterfaceDecl *ID = D->getClassInterface()) if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) return true; return VisitObjCImplDecl(D); } bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { #if 0 // Issue callbacks for super class. // FIXME: No source location information! if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), D->getSuperClassLoc(), TU))) return true; #endif return VisitObjCImplDecl(D); } bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) if (PD->isIvarNameSpecified()) return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); return false; } bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), D->getTargetNameLoc(), TU)); } bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; } if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) return true; return VisitDeclarationNameInfo(D->getNameInfo()); } bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), D->getIdentLocation(), TU)); } bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; } return VisitDeclarationNameInfo(D->getNameInfo()); } bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( UnresolvedUsingTypenameDecl *D) { // Visit nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; return false; } bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { switch (Name.getName().getNameKind()) { case clang::DeclarationName::Identifier: case clang::DeclarationName::CXXLiteralOperatorName: case clang::DeclarationName::CXXOperatorName: case clang::DeclarationName::CXXUsingDirective: return false; case clang::DeclarationName::CXXConstructorName: case clang::DeclarationName::CXXDestructorName: case clang::DeclarationName::CXXConversionFunctionName: if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) return Visit(TSInfo->getTypeLoc()); return false; case clang::DeclarationName::ObjCZeroArgSelector: case clang::DeclarationName::ObjCOneArgSelector: case clang::DeclarationName::ObjCMultiArgSelector: // FIXME: Per-identifier location info? return false; } llvm_unreachable("Invalid DeclarationName::Kind!"); } bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range) { // FIXME: This whole routine is a hack to work around the lack of proper // source information in nested-name-specifiers (PR5791). Since we do have // a beginning source location, we can visit the first component of the // nested-name-specifier, if it's a single-token component. if (!NNS) return false; // Get the first component in the nested-name-specifier. while (NestedNameSpecifier *Prefix = NNS->getPrefix()) NNS = Prefix; switch (NNS->getKind()) { case NestedNameSpecifier::Namespace: return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU)); case NestedNameSpecifier::NamespaceAlias: return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), Range.getBegin(), TU)); case NestedNameSpecifier::TypeSpec: { // If the type has a form where we know that the beginning of the source // range matches up with a reference cursor. Visit the appropriate reference // cursor. const Type *T = NNS->getAsType(); if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); if (const TagType *Tag = dyn_cast<TagType>(T)) return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); break; } case NestedNameSpecifier::TypeSpecWithTemplate: case NestedNameSpecifier::Global: case NestedNameSpecifier::Identifier: case NestedNameSpecifier::Super: break; } return false; } bool CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; for (; Qualifier; Qualifier = Qualifier.getPrefix()) Qualifiers.push_back(Qualifier); while (!Qualifiers.empty()) { NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); switch (NNS->getKind()) { case NestedNameSpecifier::Namespace: if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Q.getLocalBeginLoc(), TU))) return true; break; case NestedNameSpecifier::NamespaceAlias: if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), Q.getLocalBeginLoc(), TU))) return true; break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: if (Visit(Q.getTypeLoc())) return true; break; case NestedNameSpecifier::Global: case NestedNameSpecifier::Identifier: case NestedNameSpecifier::Super: break; } } return false; } bool CursorVisitor::VisitTemplateParameters( const TemplateParameterList *Params) { if (!Params) return false; for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) return true; } return false; } bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { switch (Name.getKind()) { case TemplateName::Template: return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); case TemplateName::OverloadedTemplate: // Visit the overloaded template set. if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) return true; return false; case TemplateName::DependentTemplate: // FIXME: Visit nested-name-specifier. return false; case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier. return Visit(MakeCursorTemplateRef( Name.getAsQualifiedTemplateName()->getDecl(), Loc, TU)); case TemplateName::SubstTemplateTemplateParm: return Visit(MakeCursorTemplateRef( Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU)); case TemplateName::SubstTemplateTemplateParmPack: return Visit(MakeCursorTemplateRef( Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc, TU)); } llvm_unreachable("Invalid TemplateName::Kind!"); } bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { switch (TAL.getArgument().getKind()) { case TemplateArgument::Null: case TemplateArgument::Integral: case TemplateArgument::Pack: return false; case TemplateArgument::Type: if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) return Visit(TSInfo->getTypeLoc()); return false; case TemplateArgument::Declaration: if (Expr *E = TAL.getSourceDeclExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::NullPtr: if (Expr *E = TAL.getSourceNullPtrExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::Expression: if (Expr *E = TAL.getSourceExpression()) return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); return false; case TemplateArgument::Template: case TemplateArgument::TemplateExpansion: if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) return true; return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), TAL.getTemplateNameLoc()); } llvm_unreachable("Invalid TemplateArgument::Kind!"); } bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { return VisitDeclContext(D); } bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return Visit(TL.getUnqualifiedLoc()); } bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { ASTContext &Context = AU->getASTContext(); // Some builtin types (such as Objective-C's "id", "sel", and // "Class") have associated declarations. Create cursors for those. QualType VisitType; switch (TL.getTypePtr()->getKind()) { case BuiltinType::Void: case BuiltinType::NullPtr: case BuiltinType::Dependent: case BuiltinType::OCLImage1d: case BuiltinType::OCLImage1dArray: case BuiltinType::OCLImage1dBuffer: case BuiltinType::OCLImage2d: case BuiltinType::OCLImage2dArray: case BuiltinType::OCLImage3d: case BuiltinType::OCLSampler: case BuiltinType::OCLEvent: #define BUILTIN_TYPE(Id, SingletonId) #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: #include "clang/AST/BuiltinTypes.def" break; case BuiltinType::ObjCId: VisitType = Context.getObjCIdType(); break; case BuiltinType::ObjCClass: VisitType = Context.getObjCClassType(); break; case BuiltinType::ObjCSel: VisitType = Context.getObjCSelType(); break; } if (!VisitType.isNull()) { if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU)); } return false; } bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { if (TL.isDefinition()) return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) return true; return false; } bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) return true; for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) { if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc())) return true; } for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), TU))) return true; } return false; } bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { return Visit(TL.getInnerLoc()); } bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { return Visit(TL.getPointeeLoc()); } bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { return Visit(TL.getModifiedLoc()); } bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType) { if (!SkipResultType && Visit(TL.getReturnLoc())) return true; for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I) if (Decl *D = TL.getParam(I)) if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) return true; return false; } bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { if (Visit(TL.getElementLoc())) return true; if (Expr *Size = TL.getSizeExpr()) return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); return false; } bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) { return Visit(TL.getOriginalLoc()); } bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { return Visit(TL.getOriginalLoc()); } bool CursorVisitor::VisitTemplateSpecializationTypeLoc( TemplateSpecializationTypeLoc TL) { // Visit the template name. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), TL.getTemplateNameLoc())) return true; // Visit the template arguments. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) return true; return false; } bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); } bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) return Visit(TSInfo->getTypeLoc()); return false; } bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) return true; return false; } bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( DependentTemplateSpecializationTypeLoc TL) { // Visit the nested-name-specifier, if there is one. if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) return true; // Visit the template arguments. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) return true; return false; } bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) return true; return Visit(TL.getNamedTypeLoc()); } bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { return Visit(TL.getPatternLoc()); } bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { if (Expr *E = TL.getUnderlyingExpr()) return Visit(MakeCXCursor(E, StmtParent, TU)); return false; } bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); } bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { return Visit(TL.getValueLoc()); } #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ return Visit##PARENT##Loc(TL); \ } DEFAULT_TYPELOC_IMPL(Complex, Type) DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) DEFAULT_TYPELOC_IMPL(Vector, Type) DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) DEFAULT_TYPELOC_IMPL(Record, TagType) DEFAULT_TYPELOC_IMPL(Enum, TagType) DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) DEFAULT_TYPELOC_IMPL(Auto, Type) bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { // Visit the nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; if (D->isCompleteDefinition()) { for (const auto &I : D->bases()) { if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU))) return true; } } return VisitTagDecl(D); } bool CursorVisitor::VisitAttributes(Decl *D) { for (const auto *I : D->attrs()) if (Visit(MakeCXCursor(I, D, TU))) return true; return false; } // HLSL Change Starts bool CursorVisitor::VisitHLSLBufferDecl(HLSLBufferDecl *D) { return VisitDeclContext(D); } // HLSL Change Ends //===----------------------------------------------------------------------===// // Data-recursive visitor methods. //===----------------------------------------------------------------------===// namespace { #define DEF_JOB(NAME, DATA, KIND)\ class NAME : public VisitorJob {\ public:\ NAME(const DATA *d, CXCursor parent) : \ VisitorJob(parent, VisitorJob::KIND, d) {} \ static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ const DATA *get() const { return static_cast<const DATA*>(data[0]); }\ }; DEF_JOB(StmtVisit, Stmt, StmtVisitKind) DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo, ExplicitTemplateArgsVisitKind) DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) #undef DEF_JOB class DeclVisit : public VisitorJob { public: DeclVisit(const Decl *D, CXCursor parent, bool isFirst) : VisitorJob(parent, VisitorJob::DeclVisitKind, D, isFirst ? (void*) 1 : (void*) nullptr) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == DeclVisitKind; } const Decl *get() const { return static_cast<const Decl *>(data[0]); } bool isFirst() const { return data[1] != nullptr; } }; class TypeLocVisit : public VisitorJob { public: TypeLocVisit(TypeLoc tl, CXCursor parent) : VisitorJob(parent, VisitorJob::TypeLocVisitKind, tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == TypeLocVisitKind; } TypeLoc get() const { QualType T = QualType::getFromOpaquePtr(data[0]); return TypeLoc(T, const_cast<void *>(data[1])); } }; class LabelRefVisit : public VisitorJob { public: LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, labelLoc.getPtrEncoding()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::LabelRefVisitKind; } const LabelDecl *get() const { return static_cast<const LabelDecl *>(data[0]); } SourceLocation getLoc() const { return SourceLocation::getFromPtrEncoding(data[1]); } }; class NestedNameSpecifierLocVisit : public VisitorJob { public: NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, Qualifier.getNestedNameSpecifier(), Qualifier.getOpaqueData()) { } static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; } NestedNameSpecifierLoc get() const { return NestedNameSpecifierLoc( const_cast<NestedNameSpecifier *>( static_cast<const NestedNameSpecifier *>(data[0])), const_cast<void *>(data[1])); } }; class DeclarationNameInfoVisit : public VisitorJob { public: DeclarationNameInfoVisit(const Stmt *S, CXCursor parent) : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; } DeclarationNameInfo get() const { const Stmt *S = static_cast<const Stmt *>(data[0]); switch (S->getStmtClass()) { default: llvm_unreachable("Unhandled Stmt"); case clang::Stmt::MSDependentExistsStmtClass: return cast<MSDependentExistsStmt>(S)->getNameInfo(); case Stmt::CXXDependentScopeMemberExprClass: return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); case Stmt::DependentScopeDeclRefExprClass: return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); case Stmt::OMPCriticalDirectiveClass: return cast<OMPCriticalDirective>(S)->getDirectiveName(); } } }; class MemberRefVisit : public VisitorJob { public: MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent) : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, L.getPtrEncoding()) {} static bool classof(const VisitorJob *VJ) { return VJ->getKind() == VisitorJob::MemberRefVisitKind; } const FieldDecl *get() const { return static_cast<const FieldDecl *>(data[0]); } SourceLocation getLoc() const { return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); } }; class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> { friend class OMPClauseEnqueue; VisitorWorkList &WL; CXCursor Parent; public: EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) : WL(wl), Parent(parent) {} void VisitAddrLabelExpr(const AddrLabelExpr *E); void VisitBlockExpr(const BlockExpr *B); void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); void VisitCompoundStmt(const CompoundStmt *S); void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ } void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S); void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E); void VisitCXXNewExpr(const CXXNewExpr *E); void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E); void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E); void VisitCXXTypeidExpr(const CXXTypeidExpr *E); void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E); void VisitCXXUuidofExpr(const CXXUuidofExpr *E); void VisitCXXCatchStmt(const CXXCatchStmt *S); void VisitCXXForRangeStmt(const CXXForRangeStmt *S); void VisitDeclRefExpr(const DeclRefExpr *D); void VisitDeclStmt(const DeclStmt *S); void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E); void VisitDesignatedInitExpr(const DesignatedInitExpr *E); void VisitExplicitCastExpr(const ExplicitCastExpr *E); void VisitForStmt(const ForStmt *FS); void VisitGotoStmt(const GotoStmt *GS); void VisitIfStmt(const IfStmt *If); void VisitInitListExpr(const InitListExpr *IE); void VisitMemberExpr(const MemberExpr *M); void VisitOffsetOfExpr(const OffsetOfExpr *E); void VisitObjCEncodeExpr(const ObjCEncodeExpr *E); void VisitObjCMessageExpr(const ObjCMessageExpr *M); void VisitOverloadExpr(const OverloadExpr *E); void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); void VisitStmt(const Stmt *S); void VisitSwitchStmt(const SwitchStmt *S); void VisitWhileStmt(const WhileStmt *W); void VisitTypeTraitExpr(const TypeTraitExpr *E); void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E); void VisitExpressionTraitExpr(const ExpressionTraitExpr *E); void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U); void VisitVAArgExpr(const VAArgExpr *E); void VisitSizeOfPackExpr(const SizeOfPackExpr *E); void VisitPseudoObjectExpr(const PseudoObjectExpr *E); void VisitOpaqueValueExpr(const OpaqueValueExpr *E); void VisitLambdaExpr(const LambdaExpr *E); void VisitOMPExecutableDirective(const OMPExecutableDirective *D); void VisitOMPLoopDirective(const OMPLoopDirective *D); void VisitOMPParallelDirective(const OMPParallelDirective *D); void VisitOMPSimdDirective(const OMPSimdDirective *D); void VisitOMPForDirective(const OMPForDirective *D); void VisitOMPForSimdDirective(const OMPForSimdDirective *D); void VisitOMPSectionsDirective(const OMPSectionsDirective *D); void VisitOMPSectionDirective(const OMPSectionDirective *D); void VisitOMPSingleDirective(const OMPSingleDirective *D); void VisitOMPMasterDirective(const OMPMasterDirective *D); void VisitOMPCriticalDirective(const OMPCriticalDirective *D); void VisitOMPParallelForDirective(const OMPParallelForDirective *D); void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D); void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D); void VisitOMPTaskDirective(const OMPTaskDirective *D); void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D); void VisitOMPBarrierDirective(const OMPBarrierDirective *D); void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D); void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D); void VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D); void VisitOMPCancelDirective(const OMPCancelDirective *D); void VisitOMPFlushDirective(const OMPFlushDirective *D); void VisitOMPOrderedDirective(const OMPOrderedDirective *D); void VisitOMPAtomicDirective(const OMPAtomicDirective *D); void VisitOMPTargetDirective(const OMPTargetDirective *D); void VisitOMPTeamsDirective(const OMPTeamsDirective *D); private: void AddDeclarationNameInfo(const Stmt *S); void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A); void AddMemberRef(const FieldDecl *D, SourceLocation L); void AddStmt(const Stmt *S); void AddDecl(const Decl *D, bool isFirst = true); void AddTypeLoc(TypeSourceInfo *TI); void EnqueueChildren(const Stmt *S); void EnqueueChildren(const OMPClause *S); }; } // end anonyous namespace void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) { // 'S' should always be non-null, since it comes from the // statement we are visiting. WL.push_back(DeclarationNameInfoVisit(S, Parent)); } void EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { if (Qualifier) WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); } void EnqueueVisitor::AddStmt(const Stmt *S) { if (S) WL.push_back(StmtVisit(S, Parent)); } void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) { if (D) WL.push_back(DeclVisit(D, Parent, isFirst)); } void EnqueueVisitor:: AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) { if (A) WL.push_back(ExplicitTemplateArgsVisit(A, Parent)); } void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) { if (D) WL.push_back(MemberRefVisit(D, L, Parent)); } void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { if (TI) WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); } void EnqueueVisitor::EnqueueChildren(const Stmt *S) { unsigned size = WL.size(); for (const Stmt *SubStmt : S->children()) { AddStmt(SubStmt); } if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } namespace { class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> { EnqueueVisitor *Visitor; /// \brief Process clauses with list of variables. template <typename T> void VisitOMPClauseList(T *Node); public: OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { } #define OPENMP_CLAUSE(Name, Class) \ void Visit##Class(const Class *C); #include "clang/Basic/OpenMPKinds.def" }; void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) { Visitor->AddStmt(C->getCondition()); } void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) { Visitor->AddStmt(C->getCondition()); } void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) { Visitor->AddStmt(C->getNumThreads()); } void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) { Visitor->AddStmt(C->getSafelen()); } void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) { Visitor->AddStmt(C->getNumForLoops()); } void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { } void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { } void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { Visitor->AddStmt(C->getChunkSize()); Visitor->AddStmt(C->getHelperChunkSize()); } void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *) {} void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} template<typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { for (const auto *I : Node->varlists()) { Visitor->AddStmt(I); } } void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { VisitOMPClauseList(C); for (const auto *E : C->private_copies()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPFirstprivateClause( const OMPFirstprivateClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPLastprivateClause( const OMPLastprivateClause *C) { VisitOMPClauseList(C); for (auto *E : C->private_copies()) { Visitor->AddStmt(E); } for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { VisitOMPClauseList(C); for (auto *E : C->lhs_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->rhs_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->reduction_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { VisitOMPClauseList(C); for (const auto *E : C->inits()) { Visitor->AddStmt(E); } for (const auto *E : C->updates()) { Visitor->AddStmt(E); } for (const auto *E : C->finals()) { Visitor->AddStmt(E); } Visitor->AddStmt(C->getStep()); Visitor->AddStmt(C->getCalcStep()); } void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { VisitOMPClauseList(C); Visitor->AddStmt(C->getAlignment()); } void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { VisitOMPClauseList(C); for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) { VisitOMPClauseList(C); for (auto *E : C->source_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->destination_exprs()) { Visitor->AddStmt(E); } for (auto *E : C->assignment_ops()) { Visitor->AddStmt(E); } } void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { VisitOMPClauseList(C); } void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { VisitOMPClauseList(C); } } void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { unsigned size = WL.size(); OMPClauseEnqueue Visitor(this); Visitor.Visit(S); if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); } void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { AddDecl(B->getBlockDecl()); } void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { for (CompoundStmt::const_reverse_body_iterator I = S->body_rbegin(), E = S->body_rend(); I != E; ++I) { AddStmt(*I); } } void EnqueueVisitor:: VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) { AddStmt(S->getSubStmt()); AddDeclarationNameInfo(S); if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); } void EnqueueVisitor:: VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); AddDeclarationNameInfo(E); if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); if (!E->isImplicitAccess()) AddStmt(E->getBase()); } void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { // Enqueue the initializer , if any. AddStmt(E->getInitializer()); // Enqueue the array size, if any. AddStmt(E->getArraySize()); // Enqueue the allocated type. AddTypeLoc(E->getAllocatedTypeSourceInfo()); // Enqueue the placement arguments. for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) AddStmt(E->getPlacementArg(I-1)); } void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) AddStmt(CE->getArg(I-1)); AddStmt(CE->getCallee()); AddStmt(CE->getArg(0)); } void EnqueueVisitor::VisitCXXPseudoDestructorExpr( const CXXPseudoDestructorExpr *E) { // Visit the name of the type being destroyed. AddTypeLoc(E->getDestroyedTypeInfo()); // Visit the scope type that looks disturbingly like the nested-name-specifier // but isn't. AddTypeLoc(E->getScopeTypeInfo()); // Visit the nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) AddNestedNameSpecifierLoc(QualifierLoc); // Visit base expression. AddStmt(E->getBase()); } void EnqueueVisitor::VisitCXXScalarValueInitExpr( const CXXScalarValueInitExpr *E) { AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXTemporaryObjectExpr( const CXXTemporaryObjectExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { EnqueueChildren(E); if (E->isTypeOperand()) AddTypeLoc(E->getTypeOperandSourceInfo()); } void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( const CXXUnresolvedConstructExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { EnqueueChildren(E); if (E->isTypeOperand()) AddTypeLoc(E->getTypeOperandSourceInfo()); } void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { EnqueueChildren(S); AddDecl(S->getExceptionDecl()); } void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { AddStmt(S->getBody()); AddStmt(S->getRangeInit()); AddDecl(S->getLoopVariable()); } void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { if (DR->hasExplicitTemplateArgs()) { AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs()); } WL.push_back(DeclRefExprParts(DR, Parent)); } void EnqueueVisitor::VisitDependentScopeDeclRefExpr( const DependentScopeDeclRefExpr *E) { AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); AddDeclarationNameInfo(E); AddNestedNameSpecifierLoc(E->getQualifierLoc()); } void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { unsigned size = WL.size(); bool isFirst = true; for (const auto *D : S->decls()) { AddDecl(D, isFirst); isFirst = false; } if (size == WL.size()) return; // Now reverse the entries we just added. This will match the DFS // ordering performed by the worklist. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); std::reverse(I, E); } void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { AddStmt(E->getInit()); for (DesignatedInitExpr::const_reverse_designators_iterator D = E->designators_rbegin(), DEnd = E->designators_rend(); D != DEnd; ++D) { if (D->isFieldDesignator()) { if (FieldDecl *Field = D->getField()) AddMemberRef(Field, D->getFieldLoc()); continue; } if (D->isArrayDesignator()) { AddStmt(E->getArrayIndex(*D)); continue; } assert(D->isArrayRangeDesignator() && "Unknown designator kind"); AddStmt(E->getArrayRangeEnd(*D)); AddStmt(E->getArrayRangeStart(*D)); } } void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { EnqueueChildren(E); AddTypeLoc(E->getTypeInfoAsWritten()); } void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { AddStmt(FS->getBody()); AddStmt(FS->getInc()); AddStmt(FS->getCond()); AddDecl(FS->getConditionVariable()); AddStmt(FS->getInit()); } void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); } void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { AddStmt(If->getElse()); AddStmt(If->getThen()); AddStmt(If->getCond()); AddDecl(If->getConditionVariable()); } void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { // We care about the syntactic form of the initializer list, only. if (InitListExpr *Syntactic = IE->getSyntacticForm()) IE = Syntactic; EnqueueChildren(IE); } void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { WL.push_back(MemberExprParts(M, Parent)); // If the base of the member access expression is an implicit 'this', don't // visit it. // FIXME: If we ever want to show these implicit accesses, this will be // unfortunate. However, clang_getCursor() relies on this behavior. if (M->isImplicitAccess()) return; // Ignore base anonymous struct/union fields, otherwise they will shadow the // real field that that we are interested in. if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) { if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) { if (FD->isAnonymousStructOrUnion()) { AddStmt(SubME->getBase()); return; } } } AddStmt(M->getBase()); } void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { AddTypeLoc(E->getEncodedTypeSourceInfo()); } void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { EnqueueChildren(M); AddTypeLoc(M->getClassReceiverTypeInfo()); } void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { // Visit the components of the offsetof expression. for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; const OffsetOfNode &Node = E->getComponent(I-1); switch (Node.getKind()) { case OffsetOfNode::Array: AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); break; case OffsetOfNode::Field: AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); break; case OffsetOfNode::Identifier: case OffsetOfNode::Base: continue; } } // Visit the type into which we're computing the offset. AddTypeLoc(E->getTypeSourceInfo()); } void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); WL.push_back(OverloadExprParts(E, Parent)); } void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( const UnaryExprOrTypeTraitExpr *E) { EnqueueChildren(E); if (E->isArgumentType()) AddTypeLoc(E->getArgumentTypeInfo()); } void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); } void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { AddStmt(S->getBody()); AddStmt(S->getCond()); AddDecl(S->getConditionVariable()); } void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { AddStmt(W->getBody()); AddStmt(W->getCond()); AddDecl(W->getConditionVariable()); } void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { for (unsigned I = E->getNumArgs(); I > 0; --I) AddTypeLoc(E->getArg(I-1)); } void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { AddTypeLoc(E->getQueriedTypeSourceInfo()); } void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { EnqueueChildren(E); } void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { VisitOverloadExpr(U); if (!U->isImplicitAccess()) AddStmt(U->getBase()); } void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { AddStmt(E->getSubExpr()); AddTypeLoc(E->getWrittenTypeInfo()); } void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { WL.push_back(SizeOfPackExprParts(E, Parent)); } void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { // If the opaque value has a source expression, just transparently // visit that. This is useful for (e.g.) pseudo-object expressions. if (Expr *SourceExpr = E->getSourceExpr()) return Visit(SourceExpr); } void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { AddStmt(E->getBody()); WL.push_back(LambdaExprParts(E, Parent)); } void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { // Treat the expression like its syntactic form. Visit(E->getSyntacticForm()); } void EnqueueVisitor::VisitOMPExecutableDirective( const OMPExecutableDirective *D) { EnqueueChildren(D); for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(), E = D->clauses().end(); I != E; ++I) EnqueueChildren(*I); } void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { VisitOMPExecutableDirective(D); AddDeclarationNameInfo(D); } void EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPParallelForSimdDirective( const OMPParallelForSimdDirective *D) { VisitOMPLoopDirective(D); } void EnqueueVisitor::VisitOMPParallelSectionsDirective( const OMPParallelSectionsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTaskgroupDirective( const OMPTaskgroupDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCancellationPointDirective( const OMPCancellationPointDirective *D) { VisitOMPExecutableDirective(D); } void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { VisitOMPExecutableDirective(D); } void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); } bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { if (RegionOfInterest.isValid()) { SourceRange Range = getRawCursorExtent(C); if (Range.isInvalid() || CompareRegionOfInterest(Range)) return false; } return true; } bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { while (!WL.empty()) { // Dequeue the worklist item. VisitorJob LI = WL.pop_back_val(); // Set the Parent field, then back to its old value once we're done. SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); switch (LI.getKind()) { case VisitorJob::DeclVisitKind: { const Decl *D = cast<DeclVisit>(&LI)->get(); if (!D) continue; // For now, perform default visitation for Decls. if (Visit(MakeCXCursor(D, TU, RegionOfInterest, cast<DeclVisit>(&LI)->isFirst()))) return true; continue; } case VisitorJob::ExplicitTemplateArgsVisitKind: { const ASTTemplateArgumentListInfo *ArgList = cast<ExplicitTemplateArgsVisit>(&LI)->get(); for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), *ArgEnd = Arg + ArgList->NumTemplateArgs; Arg != ArgEnd; ++Arg) { if (VisitTemplateArgumentLoc(*Arg)) return true; } continue; } case VisitorJob::TypeLocVisitKind: { // Perform default visitation for TypeLocs. if (Visit(cast<TypeLocVisit>(&LI)->get())) return true; continue; } case VisitorJob::LabelRefVisitKind: { const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); if (LabelStmt *stmt = LS->getStmt()) { if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), TU))) { return true; } } continue; } case VisitorJob::NestedNameSpecifierLocVisitKind: { NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); if (VisitNestedNameSpecifierLoc(V->get())) return true; continue; } case VisitorJob::DeclarationNameInfoVisitKind: { if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) ->get())) return true; continue; } case VisitorJob::MemberRefVisitKind: { MemberRefVisit *V = cast<MemberRefVisit>(&LI); if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) return true; continue; } case VisitorJob::StmtVisitKind: { const Stmt *S = cast<StmtVisit>(&LI)->get(); if (!S) continue; // Update the current cursor. CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); if (!IsInRegionOfInterest(Cursor)) continue; switch (Visitor(Cursor, Parent, ClientData)) { case CXChildVisit_Break: return true; case CXChildVisit_Continue: break; case CXChildVisit_Recurse: if (PostChildrenVisitor) WL.push_back(PostChildrenVisit(nullptr, Cursor)); EnqueueWorkList(WL, S); break; } continue; } case VisitorJob::MemberExprPartsKind: { // Handle the other pieces in the MemberExpr besides the base. const MemberExpr *M = cast<MemberExprParts>(&LI)->get(); // Visit the nested-name-specifier if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (VisitDeclarationNameInfo(M->getMemberNameInfo())) return true; // Visit the explicitly-specified template arguments, if any. if (M->hasExplicitTemplateArgs()) { for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), *ArgEnd = Arg + M->getNumTemplateArgs(); Arg != ArgEnd; ++Arg) { if (VisitTemplateArgumentLoc(*Arg)) return true; } } continue; } case VisitorJob::DeclRefExprPartsKind: { const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); // Visit nested-name-specifier, if present. if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit declaration name. if (VisitDeclarationNameInfo(DR->getNameInfo())) return true; continue; } case VisitorJob::OverloadExprPartsKind: { const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); // Visit the nested-name-specifier. if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) if (VisitNestedNameSpecifierLoc(QualifierLoc)) return true; // Visit the declaration name. if (VisitDeclarationNameInfo(O->getNameInfo())) return true; // Visit the overloaded declaration reference. if (Visit(MakeCursorOverloadedDeclRef(O, TU))) return true; continue; } case VisitorJob::SizeOfPackExprPartsKind: { const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); NamedDecl *Pack = E->getPack(); if (isa<TemplateTypeParmDecl>(Pack)) { if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), E->getPackLoc(), TU))) return true; continue; } if (isa<TemplateTemplateParmDecl>(Pack)) { if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), E->getPackLoc(), TU))) return true; continue; } // Non-type template parameter packs and function parameter packs are // treated like DeclRefExpr cursors. continue; } case VisitorJob::LambdaExprPartsKind: { // Visit captures. const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), CEnd = E->explicit_capture_end(); C != CEnd; ++C) { // FIXME: Lambda init-captures. if (!C->capturesVariable()) continue; if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(), TU))) return true; } // Visit parameters and return type, if present. if (E->hasExplicitParameters() || E->hasExplicitResultType()) { TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); if (E->hasExplicitParameters() && E->hasExplicitResultType()) { // Visit the whole type. if (Visit(TL)) return true; } else if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) { if (E->hasExplicitParameters()) { // Visit parameters. for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) if (Visit(MakeCXCursor(Proto.getParam(I), TU))) return true; } else { // Visit result type. if (Visit(Proto.getReturnLoc())) return true; } } } break; } case VisitorJob::PostChildrenVisitKind: if (PostChildrenVisitor(Parent, ClientData)) return true; break; } } return false; } bool CursorVisitor::Visit(const Stmt *S) { VisitorWorkList *WL = nullptr; if (!WorkListFreeList.empty()) { WL = WorkListFreeList.back(); WL->clear(); WorkListFreeList.pop_back(); } else { WL = new VisitorWorkList(); WorkListCache.push_back(WL); } EnqueueWorkList(*WL, S); bool result = RunVisitorWorkList(*WL); WorkListFreeList.push_back(WL); return result; } namespace { typedef SmallVector<SourceRange, 4> RefNamePieces; RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, const DeclarationNameInfo &NI, const SourceRange &QLoc, const ASTTemplateArgumentListInfo *TemplateArgs = nullptr) { const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; const DeclarationName::NameKind Kind = NI.getName().getNameKind(); RefNamePieces Pieces; if (WantQualifier && QLoc.isValid()) Pieces.push_back(QLoc); if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) Pieces.push_back(NI.getLoc()); if (WantTemplateArgs && TemplateArgs) Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc, TemplateArgs->RAngleLoc)); if (Kind == DeclarationName::CXXOperatorName) { Pieces.push_back(SourceLocation::getFromRawEncoding( NI.getInfo().CXXOperatorName.BeginOpNameLoc)); Pieces.push_back(SourceLocation::getFromRawEncoding( NI.getInfo().CXXOperatorName.EndOpNameLoc)); } if (WantSinglePiece) { SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); Pieces.clear(); Pieces.push_back(R); } return Pieces; } } //===----------------------------------------------------------------------===// // Misc. API hooks. //===----------------------------------------------------------------------===// // HLSL Change Starts - disable crash recovery static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); ::abort(); } // HLSL Change Ends - disable crash recovery namespace { struct RegisterFatalErrorHandler { RegisterFatalErrorHandler() { llvm::install_fatal_error_handler(fatal_error_handler, nullptr); } }; } //static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce; // HLSL Change - properly scoped mechanisms should be used // extern "C" { // HLSL Change -Don't use c linkage. CXIndex clang_createIndex(int excludeDeclarationsFromPCH, int displayDiagnostics) { // We use crash recovery to make some of our APIs more reliable, implicitly // enable it. // if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) // llvm::CrashRecoveryContext::Enable(); // HLSL Change: libclang isn't cleaning this up, which will crash if vectored exception handler called after unload // Look through the managed static to trigger construction of the managed // static which registers our fatal error handler. This ensures it is only // registered once. // (void)*RegisterFatalErrorHandlerOnce; // HLSL Change - properly scoped mechanisms should be used // Initialize targets for clang module support. llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); CIndexer *CIdxr = new CIndexer(); if (excludeDeclarationsFromPCH) CIdxr->setOnlyLocalDecls(); if (displayDiagnostics) CIdxr->setDisplayDiagnostics(); if (getenv("LIBCLANG_BGPRIO_INDEX")) CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | CXGlobalOpt_ThreadBackgroundPriorityForIndexing); if (getenv("LIBCLANG_BGPRIO_EDIT")) CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | CXGlobalOpt_ThreadBackgroundPriorityForEditing); return CIdxr; } void clang_disposeIndex(CXIndex CIdx) { if (CIdx) delete static_cast<CIndexer *>(CIdx); } // HLSL Change Starts void clang_index_setLangHelper(CXIndex CIdx, void* helper) { if (CIdx) static_cast<CIndexer *>(CIdx)->HlslLangExtensions = (hlsl::DxcLangExtensionsHelperApply *)helper; } // HLSL Change Ends void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { if (CIdx) static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); } unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { if (CIdx) return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); return 0; } void clang_toggleCrashRecovery(unsigned isEnabled) { if (isEnabled) llvm::CrashRecoveryContext::Enable(); else llvm::CrashRecoveryContext::Disable(); } CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, const char *ast_filename) { CXTranslationUnit TU; enum CXErrorCode Result = clang_createTranslationUnit2(CIdx, ast_filename, &TU); (void)Result; assert((TU && Result == CXError_Success) || (!TU && Result != CXError_Success)); return TU; } enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, const char *ast_filename, CXTranslationUnit *out_TU) { #if 1 // HLSL Change Starts - no support for serialization return CXError_Failure; #else if (out_TU) *out_TU = nullptr; if (!CIdx || !ast_filename || !out_TU) return CXError_InvalidArguments; LOG_FUNC_SECTION { *Log << ast_filename; } CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); FileSystemOptions FileSystemOpts; IntrusiveRefCntPtr<DiagnosticsEngine> Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions()); std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile( ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags, FileSystemOpts, CXXIdx->getOnlyLocalDecls(), None, /*CaptureDiagnostics=*/true, /*AllowPCHWithCompilerErrors=*/true, /*UserFilesAreVolatile=*/true); *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release()); return *out_TU ? CXError_Success : CXError_Failure; #endif // HLSL Change Ends - no support for serialization } unsigned clang_defaultEditingTranslationUnitOptions() { return CXTranslationUnit_PrecompiledPreamble | CXTranslationUnit_CacheCompletionResults; } CXTranslationUnit clang_createTranslationUnitFromSourceFile(CXIndex CIdx, const char *source_filename, int num_command_line_args, const char * const *command_line_args, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files) { unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; return clang_parseTranslationUnit(CIdx, source_filename, command_line_args, num_command_line_args, unsaved_files, num_unsaved_files, Options); } struct ParseTranslationUnitInfo { CXIndex CIdx; const char *source_filename; const char *const *command_line_args; int num_command_line_args; ArrayRef<CXUnsavedFile> unsaved_files; unsigned options; CXTranslationUnit *out_TU; CXErrorCode &result; ::llvm::sys::fs::MSFileSystemRef fsr; }; static void clang_parseTranslationUnit_Impl(void *UserData) { const ParseTranslationUnitInfo *PTUI = static_cast<ParseTranslationUnitInfo *>(UserData); CXIndex CIdx = PTUI->CIdx; const char *source_filename = PTUI->source_filename; const char * const *command_line_args = PTUI->command_line_args; int num_command_line_args = PTUI->num_command_line_args; unsigned options = PTUI->options; CXTranslationUnit *out_TU = PTUI->out_TU; // Set up the initial return values. if (out_TU) *out_TU = nullptr; // Check arguments. if (!CIdx || !out_TU) { PTUI->result = CXError_InvalidArguments; return; } // HLSL Change Starts if (PTUI->fsr) { // No need to clean up in this case - this means we run in our own thread // (otherwise caller owns the thread and should set this up). ::llvm::sys::fs::SetCurrentThreadFileSystem(PTUI->fsr); } // HLSL Change Ends CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; // FIXME: Add a flag for modules. TranslationUnitKind TUKind = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete; bool CacheCodeCompletionResults = options & CXTranslationUnit_CacheCompletionResults; bool IncludeBriefCommentsInCodeCompletion = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies; bool ForSerialization = options & CXTranslationUnit_ForSerialization; // Configure the diagnostics. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > DiagCleanup(Diags.get()); std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( new std::vector<ASTUnit::RemappedFile>()); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar< std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); for (auto &UF : PTUI->unsaved_files) { std::unique_ptr<llvm::MemoryBuffer> MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); } std::unique_ptr<std::vector<const char *>> Args( new std::vector<const char *>()); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > ArgsCleanup(Args.get()); // Since the Clang C library is primarily used by batch tools dealing with // (often very broken) source code, where spell-checking can have a // significant negative impact on performance (particularly when // precompiled headers are involved), we disable it by default. // Only do this if we haven't found a spell-checking-related argument. bool FoundSpellCheckingArgument = false; for (int I = 0; I != num_command_line_args; ++I) { if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || strcmp(command_line_args[I], "-fspell-checking") == 0) { FoundSpellCheckingArgument = true; break; } } if (!FoundSpellCheckingArgument) Args->push_back("-fno-spell-checking"); Args->insert(Args->end(), command_line_args, command_line_args + num_command_line_args); // The 'source_filename' argument is optional. If the caller does not // specify it then it is assumed that the source file is specified // in the actual argument list. // Put the source file after command_line_args otherwise if '-x' flag is // present it will be unused. if (source_filename) Args->push_back(source_filename); // Do we need the detailed preprocessing record? if (options & CXTranslationUnit_DetailedPreprocessingRecord) { // Args->push_back("-Xclang"); // HLSL Change - command-line now is directly dxc compilation, no longer clang-driver-driven Args->push_back("-detailed-preprocessing-record"); } unsigned NumErrors = Diags->getClient()->getNumErrors(); std::unique_ptr<ASTUnit> ErrUnit; std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine( Args->data(), Args->data() + Args->size(), CXXIdx->getPCHContainerOperations(), Diags, CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), /*CaptureDiagnostics=*/true, *RemappedFiles.get(), /*RemappedFilesKeepOriginalName=*/true, PrecompilePreamble, TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, /*UserFilesAreVolatile=*/true, ForSerialization, &ErrUnit, CXXIdx->HlslLangExtensions)); // HLSL Change - add language extensions // Early failures in LoadFromCommandLine may return with ErrUnit unset. if (!Unit && !ErrUnit) { PTUI->result = CXError_ASTReadError; return; } if (NumErrors != Diags->getClient()->getNumErrors()) { // Make sure to check that 'Unit' is non-NULL. if (CXXIdx->getDisplayDiagnostics()) printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); } if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) { PTUI->result = CXError_ASTReadError; } else { *PTUI->out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release()); PTUI->result = *PTUI->out_TU ? CXError_Success : CXError_Failure; } } CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options) { CXTranslationUnit TU; enum CXErrorCode Result = clang_parseTranslationUnit2( CIdx, source_filename, command_line_args, num_command_line_args, unsaved_files, num_unsaved_files, options, &TU); (void)Result; assert((TU && Result == CXError_Success) || (!TU && Result != CXError_Success)); return TU; } enum CXErrorCode clang_parseTranslationUnit2( CXIndex CIdx, const char *source_filename, const char *const *command_line_args, int num_command_line_args, struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, unsigned options, CXTranslationUnit *out_TU) { LOG_FUNC_SECTION { *Log << source_filename << ": "; for (int i = 0; i != num_command_line_args; ++i) *Log << command_line_args[i] << " "; } if (num_unsaved_files && !unsaved_files) return CXError_InvalidArguments; CXErrorCode result = CXError_Failure; ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, num_command_line_args, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU, result, nullptr}; llvm::CrashRecoveryContext CRC; // HLSL Change Starts - allow an option to control this behavior. bool runSucceeded; if (options & CXTranslationUnit_UseCallerThread) { PTUI.fsr = nullptr; runSucceeded = CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI); } else { PTUI.fsr = ::llvm::sys::fs::GetCurrentThreadFileSystem(); runSucceeded = RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI); } if (!runSucceeded) { // HLSL Change Ends fprintf(stderr, "libclang: crash detected during parsing: {\n"); fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); fprintf(stderr, " 'command_line_args' : ["); for (int i = 0; i != num_command_line_args; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "'%s'", command_line_args[i]); } fprintf(stderr, "],\n"); fprintf(stderr, " 'unsaved_files' : ["); for (unsigned i = 0; i != num_unsaved_files; ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, unsaved_files[i].Length); } fprintf(stderr, "],\n"); fprintf(stderr, " 'options' : %d,\n", options); fprintf(stderr, "}\n"); return CXError_Crashed; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { if (CXTranslationUnit *TU = PTUI.out_TU) PrintLibclangResourceUsage(*TU); } return result; } unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { return CXSaveTranslationUnit_None; } namespace { struct SaveTranslationUnitInfo { CXTranslationUnit TU; const char *FileName; unsigned options; CXSaveError result; }; } static void clang_saveTranslationUnit_Impl(void *UserData) { SaveTranslationUnitInfo *STUI = static_cast<SaveTranslationUnitInfo*>(UserData); CIndexer *CXXIdx = STUI->TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); bool hadError = cxtu::getASTUnit(STUI->TU)->Save(STUI->FileName); STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None; } int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, unsigned options) { LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; } if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return CXSaveError_InvalidTU; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (!CXXUnit->hasSema()) return CXSaveError_InvalidTU; SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None }; if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() || getenv("LIBCLANG_NOTHREADS")) { clang_saveTranslationUnit_Impl(&STUI); if (getenv("LIBCLANG_RESOURCE_USAGE")) PrintLibclangResourceUsage(TU); return STUI.result; } // We have an AST that has invalid nodes due to compiler errors. // Use a crash recovery thread for protection. llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) { fprintf(stderr, "libclang: crash detected during AST saving: {\n"); fprintf(stderr, " 'filename' : '%s'\n", FileName); fprintf(stderr, " 'options' : %d,\n", options); fprintf(stderr, "}\n"); return CXSaveError_Unknown; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { PrintLibclangResourceUsage(TU); } return STUI.result; } void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { if (CTUnit) { // If the translation unit has been marked as unsafe to free, just discard // it. ASTUnit *Unit = cxtu::getASTUnit(CTUnit); if (Unit && Unit->isUnsafeToFree()) return; delete cxtu::getASTUnit(CTUnit); delete CTUnit->StringPool; delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); delete CTUnit->CommentToXML; delete CTUnit; } } unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { return CXReparse_None; } struct ReparseTranslationUnitInfo { CXTranslationUnit TU; ArrayRef<CXUnsavedFile> unsaved_files; unsigned options; CXErrorCode &result; }; static void clang_reparseTranslationUnit_Impl(void *UserData) { const ReparseTranslationUnitInfo *RTUI = static_cast<ReparseTranslationUnitInfo *>(UserData); CXTranslationUnit TU = RTUI->TU; unsigned options = RTUI->options; (void) options; // Check arguments. if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); RTUI->result = CXError_InvalidArguments; return; } // Reset the associated diagnostics. delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); TU->Diagnostics = nullptr; CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) setThreadBackgroundPriority(); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( new std::vector<ASTUnit::RemappedFile>()); // Recover resources if we crash before exiting this function. llvm::CrashRecoveryContextCleanupRegistrar< std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); for (auto &UF : RTUI->unsaved_files) { std::unique_ptr<llvm::MemoryBuffer> MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); } if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(), *RemappedFiles.get())) RTUI->result = CXError_Success; else if (isASTReadError(CXXUnit)) RTUI->result = CXError_ASTReadError; } int clang_reparseTranslationUnit(CXTranslationUnit TU, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files, unsigned options) { LOG_FUNC_SECTION { *Log << TU; } if (num_unsaved_files && !unsaved_files) return CXError_InvalidArguments; CXErrorCode result = CXError_Failure; ReparseTranslationUnitInfo RTUI = { TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, result}; if (getenv("LIBCLANG_NOTHREADS")) { clang_reparseTranslationUnit_Impl(&RTUI); return result; } llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { fprintf(stderr, "libclang: crash detected during reparsing\n"); cxtu::getASTUnit(TU)->setUnsafeToFree(true); return CXError_Crashed; } else if (getenv("LIBCLANG_RESOURCE_USAGE")) PrintLibclangResourceUsage(TU); return result; } CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { if (isNotUsableTU(CTUnit)) { LOG_BAD_TU(CTUnit); return cxstring::createEmpty(); } ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); return cxstring::createDup(CXXUnit->getOriginalSourceFileName()); } CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullCursor(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // CXFile Operations. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXString clang_getFileName(CXFile SFile) { if (!SFile) return cxstring::createNull(); FileEntry *FEnt = static_cast<FileEntry *>(SFile); return cxstring::createRef(FEnt->getName()); } time_t clang_getFileTime(CXFile SFile) { if (!SFile) return 0; FileEntry *FEnt = static_cast<FileEntry *>(SFile); return FEnt->getModificationTime(); } CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return nullptr; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); FileManager &FMgr = CXXUnit->getFileManager(); return const_cast<FileEntry *>(FMgr.getFile(file_name)); } unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return 0; } if (!file) return 0; ASTUnit *CXXUnit = cxtu::getASTUnit(TU); FileEntry *FEnt = static_cast<FileEntry *>(file); return CXXUnit->getPreprocessor().getHeaderSearchInfo() .isFileMultipleIncludeGuarded(FEnt); } int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) { if (!file || !outID) return 1; FileEntry *FEnt = static_cast<FileEntry *>(file); const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID(); outID->data[0] = ID.getDevice(); outID->data[1] = ID.getFile(); outID->data[2] = FEnt->getModificationTime(); return 0; } int clang_File_isEqual(CXFile file1, CXFile file2) { if (file1 == file2) return true; if (!file1 || !file2) return false; FileEntry *FEnt1 = static_cast<FileEntry *>(file1); FileEntry *FEnt2 = static_cast<FileEntry *>(file2); return FEnt1->getUniqueID() == FEnt2->getUniqueID(); } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // CXCursor Operations. //===----------------------------------------------------------------------===// static const Decl *getDeclFromExpr(const Stmt *E) { if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) return getDeclFromExpr(CE->getSubExpr()); if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) return RefExpr->getDecl(); if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) return ME->getMemberDecl(); if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) return RE->getDecl(); if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { if (PRE->isExplicitProperty()) return PRE->getExplicitProperty(); // It could be messaging both getter and setter as in: // ++myobj.myprop; // in which case prefer to associate the setter since it is less obvious // from inspecting the source that the setter is going to get called. if (PRE->isMessagingSetter()) return PRE->getImplicitPropertySetter(); return PRE->getImplicitPropertyGetter(); } if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) return getDeclFromExpr(POE->getSyntacticForm()); if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) if (Expr *Src = OVE->getSourceExpr()) return getDeclFromExpr(Src); if (const CallExpr *CE = dyn_cast<CallExpr>(E)) return getDeclFromExpr(CE->getCallee()); if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) if (!CE->isElidable()) return CE->getConstructor(); if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) return OME->getMethodDecl(); if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) return PE->getProtocol(); if (const SubstNonTypeTemplateParmPackExpr *NTTP = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) return NTTP->getParameterPack(); if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || isa<ParmVarDecl>(SizeOfPack->getPack())) return SizeOfPack->getPack(); return nullptr; } static SourceLocation getLocationFromExpr(const Expr *E) { if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) return getLocationFromExpr(CE->getSubExpr()); if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) return /*FIXME:*/Msg->getLeftLoc(); if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) return DRE->getLocation(); if (const MemberExpr *Member = dyn_cast<MemberExpr>(E)) return Member->getMemberLoc(); if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) return Ivar->getLocation(); if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) return SizeOfPack->getPackLoc(); if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) return PropRef->getLocation(); return E->getLocStart(); } // extern "C" { // HLSL Change -Don't use c linkage. unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor, CXClientData client_data) { CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, /*VisitPreprocessorLast=*/false); return CursorVis.VisitChildren(parent); } #ifndef __has_feature #define __has_feature(x) 0 #endif #if __has_feature(blocks) typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; return block(cursor, parent); } #else // If we are compiled with a compiler that doesn't have native blocks support, // define and call the block manually, so the typedef struct _CXChildVisitResult { void *isa; int flags; int reserved; enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, CXCursor); } *CXCursorVisitorBlock; static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; return block->invoke(block, cursor, parent); } #endif unsigned clang_visitChildrenWithBlock(CXCursor parent, CXCursorVisitorBlock block) { return clang_visitChildren(parent, visitWithBlock, block); } static CXString getDeclSpelling(const Decl *D, PrintingPolicy* declPolicy) { // HLSL Change: adds declPolicy param if (!D) return cxstring::createEmpty(); const NamedDecl *ND = dyn_cast<NamedDecl>(D); if (!ND) { if (const ObjCPropertyImplDecl *PropImpl = dyn_cast<ObjCPropertyImplDecl>(D)) if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) return cxstring::createDup(Property->getIdentifier()->getName()); if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) if (Module *Mod = ImportD->getImportedModule()) return cxstring::createDup(Mod->getFullModuleName()); return cxstring::createEmpty(); } if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) return cxstring::createDup(OMD->getSelector().getAsString()); if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) // No, this isn't the same as the code below. getIdentifier() is non-virtual // and returns different names. NamedDecl returns the class name and // ObjCCategoryImplDecl returns the category name. return cxstring::createRef(CIMP->getIdentifier()->getNameStart()); if (isa<UsingDirectiveDecl>(D)) return cxstring::createEmpty(); SmallString<1024> S; llvm::raw_svector_ostream os(S); // HLSL Change Starts - forward declPolicy if available if (declPolicy) { ND->print(os, *declPolicy); } else { ND->printName(os); } // HLSL Change Ends return cxstring::createDup(os.str()); } // HLSL Change Starts CXString clang_getCursorSpellingWithFormatting(CXCursor C, unsigned options) { if (clang_isInvalid(C.kind)) { return cxstring::createEmpty(); } LangOptions LangOpts = (options & CXCursorFormatting_UseLanguageOptions) ? getCursorContext(C).getLangOpts() : LangOptions(); PrintingPolicy P(LangOpts); P.SuppressSpecifiers = (options & CXCursorFormatting_SuppressSpecifiers); P.SuppressTagKeyword = (options & CXCursorFormatting_SuppressTagKeyword); // Apply printing policy if anything other than default is specified. PrintingPolicy* declPolicy = (options == CXCursorFormatting_Default) ? nullptr : &P; // HLSL Change Ends if (clang_isTranslationUnit(C.kind)) return clang_getTranslationUnitSpelling(getCursorTU(C)); if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: { const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; return cxstring::createRef(Super->getIdentifier()->getNameStart()); } case CXCursor_ObjCClassRef: { const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; return cxstring::createRef(Class->getIdentifier()->getNameStart()); } case CXCursor_ObjCProtocolRef: { const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; assert(OID && "getCursorSpelling(): Missing protocol decl"); return cxstring::createRef(OID->getIdentifier()->getNameStart()); } case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); return cxstring::createDup(B->getType().getAsString(P)); } case CXCursor_TypeRef: { const TypeDecl *Type = getCursorTypeRef(C).first; assert(Type && "Missing type decl"); return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type). getAsString(P)); } case CXCursor_TemplateRef: { const TemplateDecl *Template = getCursorTemplateRef(C).first; assert(Template && "Missing template decl"); return cxstring::createDup(Template->getNameAsString()); } case CXCursor_NamespaceRef: { const NamedDecl *NS = getCursorNamespaceRef(C).first; assert(NS && "Missing namespace decl"); // HLSL Change Starts if (options & CXCursorFormatting_IncludeNamespaceKeyword) { std::string s("namespace "); s.append(NS->getNameAsString()); return cxstring::createDup(StringRef(s)); } else { return cxstring::createDup(NS->getNameAsString()); } // HLSL Change Ends } case CXCursor_MemberRef: { const FieldDecl *Field = getCursorMemberRef(C).first; assert(Field && "Missing member decl"); return cxstring::createDup(Field->getNameAsString()); } case CXCursor_LabelRef: { const LabelStmt *Label = getCursorLabelRef(C).first; assert(Label && "Missing label"); return cxstring::createRef(Label->getName()); } case CXCursor_OverloadedDeclRef: { OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; if (const Decl *D = Storage.dyn_cast<const Decl *>()) { if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) return cxstring::createDup(ND->getNameAsString()); return cxstring::createEmpty(); } if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) return cxstring::createDup(E->getName().getAsString()); OverloadedTemplateStorage *Ovl = Storage.get<OverloadedTemplateStorage*>(); if (Ovl->size() == 0) return cxstring::createEmpty(); return cxstring::createDup((*Ovl->begin())->getNameAsString()); } case CXCursor_VariableRef: { const VarDecl *Var = getCursorVariableRef(C).first; assert(Var && "Missing variable decl"); return cxstring::createDup(Var->getNameAsString()); } default: return cxstring::createRef("<not implemented>"); } } if (clang_isExpression(C.kind)) { const Expr *E = getCursorExpr(C); if (C.kind == CXCursor_ObjCStringLiteral || C.kind == CXCursor_StringLiteral) { const StringLiteral *SLit; if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) { SLit = OSL->getString(); } else { SLit = cast<StringLiteral>(E); } SmallString<256> Buf; llvm::raw_svector_ostream OS(Buf); SLit->outputString(OS); return cxstring::createDup(OS.str()); } const Decl *D = getDeclFromExpr(getCursorExpr(C)); if (D) return getDeclSpelling(D, declPolicy); return cxstring::createEmpty(); } if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) return cxstring::createRef(Label->getName()); return cxstring::createEmpty(); } if (C.kind == CXCursor_MacroExpansion) return cxstring::createRef(getCursorMacroExpansion(C).getName() ->getNameStart()); if (C.kind == CXCursor_MacroDefinition) return cxstring::createRef(getCursorMacroDefinition(C)->getName() ->getNameStart()); if (C.kind == CXCursor_InclusionDirective) return cxstring::createDup(getCursorInclusionDirective(C)->getFileName()); if (clang_isDeclaration(C.kind)) return getDeclSpelling(getCursorDecl(C), declPolicy); if (C.kind == CXCursor_AnnotateAttr) { const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); return cxstring::createDup(AA->getAnnotation()); } if (C.kind == CXCursor_AsmLabelAttr) { const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); return cxstring::createDup(AA->getLabel()); } if (C.kind == CXCursor_PackedAttr) { return cxstring::createRef("packed"); } return cxstring::createEmpty(); } // HLSL Change Starts CXString clang_getCursorSpelling(CXCursor C) { return clang_getCursorSpellingWithFormatting(C, 0); } // HLSL Change Ends CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex, unsigned options) { if (clang_Cursor_isNull(C)) return clang_getNullRange(); ASTContext &Ctx = getCursorContext(C); if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { if (pieceIndex > 0) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); } return clang_getNullRange(); } if (C.kind == CXCursor_ObjCMessageExpr) { if (const ObjCMessageExpr * ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { if (pieceIndex >= ME->getNumSelectorLocs()) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); } } if (C.kind == CXCursor_ObjCInstanceMethodDecl || C.kind == CXCursor_ObjCClassMethodDecl) { if (const ObjCMethodDecl * MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { if (pieceIndex >= MD->getNumSelectorLocs()) return clang_getNullRange(); return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); } } if (C.kind == CXCursor_ObjCCategoryDecl || C.kind == CXCursor_ObjCCategoryImplDecl) { if (pieceIndex > 0) return clang_getNullRange(); if (const ObjCCategoryDecl * CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); if (const ObjCCategoryImplDecl * CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); } if (C.kind == CXCursor_ModuleImportDecl) { if (pieceIndex > 0) return clang_getNullRange(); if (const ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); if (!Locs.empty()) return cxloc::translateSourceRange(Ctx, SourceRange(Locs.front(), Locs.back())); } return clang_getNullRange(); } if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor || C.kind == CXCursor_ConversionFunction) { if (pieceIndex > 0) return clang_getNullRange(); if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) { DeclarationNameInfo FunctionName = FD->getNameInfo(); return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange()); } return clang_getNullRange(); } // FIXME: A CXCursor_InclusionDirective should give the location of the // filename, but we don't keep track of this. // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation // but we don't keep track of this. // FIXME: A CXCursor_AsmLabelAttr should give the location of the label // but we don't keep track of this. // Default handling, give the location of the cursor. if (pieceIndex > 0) return clang_getNullRange(); CXSourceLocation CXLoc = clang_getCursorLocation(C); SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); return cxloc::translateSourceRange(Ctx, Loc); } CXString clang_Cursor_getMangling(CXCursor C) { if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) return cxstring::createEmpty(); // Mangling only works for functions and variables. const Decl *D = getCursorDecl(C); if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D))) return cxstring::createEmpty(); // First apply frontend mangling. const NamedDecl *ND = cast<NamedDecl>(D); ASTContext &Ctx = ND->getASTContext(); std::unique_ptr<MangleContext> MC(Ctx.createMangleContext()); std::string FrontendBuf; llvm::raw_string_ostream FrontendBufOS(FrontendBuf); MC->mangleName(ND, FrontendBufOS); // Now apply backend mangling. std::unique_ptr<llvm::DataLayout> DL( new llvm::DataLayout(Ctx.getTargetInfo().getTargetDescription())); std::string FinalBuf; llvm::raw_string_ostream FinalBufOS(FinalBuf); llvm::Mangler::getNameWithPrefix(FinalBufOS, llvm::Twine(FrontendBufOS.str()), *DL); return cxstring::createDup(FinalBufOS.str()); } CXString clang_getCursorDisplayName(CXCursor C) { if (!clang_isDeclaration(C.kind)) return clang_getCursorSpelling(C); const Decl *D = getCursorDecl(C); if (!D) return cxstring::createEmpty(); PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) D = FunTmpl->getTemplatedDecl(); if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { SmallString<64> Str; llvm::raw_svector_ostream OS(Str); OS << *Function; if (Function->getPrimaryTemplate()) OS << "<>"; OS << "("; for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { if (I) OS << ", "; OS << Function->getParamDecl(I)->getType().getAsString(Policy); } if (Function->isVariadic()) { if (Function->getNumParams()) OS << ", "; OS << "..."; } OS << ")"; return cxstring::createDup(OS.str()); } if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { SmallString<64> Str; llvm::raw_svector_ostream OS(Str); OS << *ClassTemplate; OS << "<"; TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); for (unsigned I = 0, N = Params->size(); I != N; ++I) { if (I) OS << ", "; NamedDecl *Param = Params->getParam(I); if (Param->getIdentifier()) { OS << Param->getIdentifier()->getName(); continue; } // There is no parameter name, which makes this tricky. Try to come up // with something useful that isn't too long. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) OS << NTTP->getType().getAsString(Policy); else OS << "template<...> class"; } OS << ">"; return cxstring::createDup(OS.str()); } if (const ClassTemplateSpecializationDecl *ClassSpec = dyn_cast<ClassTemplateSpecializationDecl>(D)) { // If the type was explicitly written, use that. if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) return cxstring::createDup(TSInfo->getType().getAsString(Policy)); SmallString<128> Str; llvm::raw_svector_ostream OS(Str); OS << *ClassSpec; TemplateSpecializationType::PrintTemplateArgumentList(OS, ClassSpec->getTemplateArgs().data(), ClassSpec->getTemplateArgs().size(), Policy); return cxstring::createDup(OS.str()); } return clang_getCursorSpelling(C); } CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { switch (Kind) { case CXCursor_FunctionDecl: return cxstring::createRef("FunctionDecl"); case CXCursor_TypedefDecl: return cxstring::createRef("TypedefDecl"); case CXCursor_EnumDecl: return cxstring::createRef("EnumDecl"); case CXCursor_EnumConstantDecl: return cxstring::createRef("EnumConstantDecl"); case CXCursor_StructDecl: return cxstring::createRef("StructDecl"); case CXCursor_UnionDecl: return cxstring::createRef("UnionDecl"); case CXCursor_ClassDecl: return cxstring::createRef("ClassDecl"); case CXCursor_FieldDecl: return cxstring::createRef("FieldDecl"); case CXCursor_VarDecl: return cxstring::createRef("VarDecl"); case CXCursor_ParmDecl: return cxstring::createRef("ParmDecl"); case CXCursor_ObjCInterfaceDecl: return cxstring::createRef("ObjCInterfaceDecl"); case CXCursor_ObjCCategoryDecl: return cxstring::createRef("ObjCCategoryDecl"); case CXCursor_ObjCProtocolDecl: return cxstring::createRef("ObjCProtocolDecl"); case CXCursor_ObjCPropertyDecl: return cxstring::createRef("ObjCPropertyDecl"); case CXCursor_ObjCIvarDecl: return cxstring::createRef("ObjCIvarDecl"); case CXCursor_ObjCInstanceMethodDecl: return cxstring::createRef("ObjCInstanceMethodDecl"); case CXCursor_ObjCClassMethodDecl: return cxstring::createRef("ObjCClassMethodDecl"); case CXCursor_ObjCImplementationDecl: return cxstring::createRef("ObjCImplementationDecl"); case CXCursor_ObjCCategoryImplDecl: return cxstring::createRef("ObjCCategoryImplDecl"); case CXCursor_CXXMethod: return cxstring::createRef("CXXMethod"); case CXCursor_UnexposedDecl: return cxstring::createRef("UnexposedDecl"); case CXCursor_ObjCSuperClassRef: return cxstring::createRef("ObjCSuperClassRef"); case CXCursor_ObjCProtocolRef: return cxstring::createRef("ObjCProtocolRef"); case CXCursor_ObjCClassRef: return cxstring::createRef("ObjCClassRef"); case CXCursor_TypeRef: return cxstring::createRef("TypeRef"); case CXCursor_TemplateRef: return cxstring::createRef("TemplateRef"); case CXCursor_NamespaceRef: return cxstring::createRef("NamespaceRef"); case CXCursor_MemberRef: return cxstring::createRef("MemberRef"); case CXCursor_LabelRef: return cxstring::createRef("LabelRef"); case CXCursor_OverloadedDeclRef: return cxstring::createRef("OverloadedDeclRef"); case CXCursor_VariableRef: return cxstring::createRef("VariableRef"); case CXCursor_IntegerLiteral: return cxstring::createRef("IntegerLiteral"); case CXCursor_FloatingLiteral: return cxstring::createRef("FloatingLiteral"); case CXCursor_ImaginaryLiteral: return cxstring::createRef("ImaginaryLiteral"); case CXCursor_StringLiteral: return cxstring::createRef("StringLiteral"); case CXCursor_CharacterLiteral: return cxstring::createRef("CharacterLiteral"); case CXCursor_ParenExpr: return cxstring::createRef("ParenExpr"); case CXCursor_UnaryOperator: return cxstring::createRef("UnaryOperator"); case CXCursor_ArraySubscriptExpr: return cxstring::createRef("ArraySubscriptExpr"); case CXCursor_BinaryOperator: return cxstring::createRef("BinaryOperator"); case CXCursor_CompoundAssignOperator: return cxstring::createRef("CompoundAssignOperator"); case CXCursor_ConditionalOperator: return cxstring::createRef("ConditionalOperator"); case CXCursor_CStyleCastExpr: return cxstring::createRef("CStyleCastExpr"); case CXCursor_CompoundLiteralExpr: return cxstring::createRef("CompoundLiteralExpr"); case CXCursor_InitListExpr: return cxstring::createRef("InitListExpr"); case CXCursor_AddrLabelExpr: return cxstring::createRef("AddrLabelExpr"); case CXCursor_StmtExpr: return cxstring::createRef("StmtExpr"); case CXCursor_GenericSelectionExpr: return cxstring::createRef("GenericSelectionExpr"); case CXCursor_GNUNullExpr: return cxstring::createRef("GNUNullExpr"); case CXCursor_CXXStaticCastExpr: return cxstring::createRef("CXXStaticCastExpr"); case CXCursor_CXXDynamicCastExpr: return cxstring::createRef("CXXDynamicCastExpr"); case CXCursor_CXXReinterpretCastExpr: return cxstring::createRef("CXXReinterpretCastExpr"); case CXCursor_CXXConstCastExpr: return cxstring::createRef("CXXConstCastExpr"); case CXCursor_CXXFunctionalCastExpr: return cxstring::createRef("CXXFunctionalCastExpr"); case CXCursor_CXXTypeidExpr: return cxstring::createRef("CXXTypeidExpr"); case CXCursor_CXXBoolLiteralExpr: return cxstring::createRef("CXXBoolLiteralExpr"); case CXCursor_CXXNullPtrLiteralExpr: return cxstring::createRef("CXXNullPtrLiteralExpr"); case CXCursor_CXXThisExpr: return cxstring::createRef("CXXThisExpr"); case CXCursor_CXXThrowExpr: return cxstring::createRef("CXXThrowExpr"); case CXCursor_CXXNewExpr: return cxstring::createRef("CXXNewExpr"); case CXCursor_CXXDeleteExpr: return cxstring::createRef("CXXDeleteExpr"); case CXCursor_UnaryExpr: return cxstring::createRef("UnaryExpr"); case CXCursor_ObjCStringLiteral: return cxstring::createRef("ObjCStringLiteral"); case CXCursor_ObjCBoolLiteralExpr: return cxstring::createRef("ObjCBoolLiteralExpr"); case CXCursor_ObjCSelfExpr: return cxstring::createRef("ObjCSelfExpr"); case CXCursor_ObjCEncodeExpr: return cxstring::createRef("ObjCEncodeExpr"); case CXCursor_ObjCSelectorExpr: return cxstring::createRef("ObjCSelectorExpr"); case CXCursor_ObjCProtocolExpr: return cxstring::createRef("ObjCProtocolExpr"); case CXCursor_ObjCBridgedCastExpr: return cxstring::createRef("ObjCBridgedCastExpr"); case CXCursor_BlockExpr: return cxstring::createRef("BlockExpr"); case CXCursor_PackExpansionExpr: return cxstring::createRef("PackExpansionExpr"); case CXCursor_SizeOfPackExpr: return cxstring::createRef("SizeOfPackExpr"); case CXCursor_LambdaExpr: return cxstring::createRef("LambdaExpr"); case CXCursor_UnexposedExpr: return cxstring::createRef("UnexposedExpr"); case CXCursor_DeclRefExpr: return cxstring::createRef("DeclRefExpr"); case CXCursor_MemberRefExpr: return cxstring::createRef("MemberRefExpr"); case CXCursor_CallExpr: return cxstring::createRef("CallExpr"); case CXCursor_ObjCMessageExpr: return cxstring::createRef("ObjCMessageExpr"); case CXCursor_UnexposedStmt: return cxstring::createRef("UnexposedStmt"); case CXCursor_DeclStmt: return cxstring::createRef("DeclStmt"); case CXCursor_LabelStmt: return cxstring::createRef("LabelStmt"); case CXCursor_CompoundStmt: return cxstring::createRef("CompoundStmt"); case CXCursor_CaseStmt: return cxstring::createRef("CaseStmt"); case CXCursor_DefaultStmt: return cxstring::createRef("DefaultStmt"); case CXCursor_IfStmt: return cxstring::createRef("IfStmt"); case CXCursor_SwitchStmt: return cxstring::createRef("SwitchStmt"); case CXCursor_WhileStmt: return cxstring::createRef("WhileStmt"); case CXCursor_DoStmt: return cxstring::createRef("DoStmt"); case CXCursor_ForStmt: return cxstring::createRef("ForStmt"); case CXCursor_GotoStmt: return cxstring::createRef("GotoStmt"); case CXCursor_IndirectGotoStmt: return cxstring::createRef("IndirectGotoStmt"); case CXCursor_ContinueStmt: return cxstring::createRef("ContinueStmt"); case CXCursor_BreakStmt: return cxstring::createRef("BreakStmt"); case CXCursor_ReturnStmt: return cxstring::createRef("ReturnStmt"); case CXCursor_GCCAsmStmt: return cxstring::createRef("GCCAsmStmt"); case CXCursor_MSAsmStmt: return cxstring::createRef("MSAsmStmt"); case CXCursor_ObjCAtTryStmt: return cxstring::createRef("ObjCAtTryStmt"); case CXCursor_ObjCAtCatchStmt: return cxstring::createRef("ObjCAtCatchStmt"); case CXCursor_ObjCAtFinallyStmt: return cxstring::createRef("ObjCAtFinallyStmt"); case CXCursor_ObjCAtThrowStmt: return cxstring::createRef("ObjCAtThrowStmt"); case CXCursor_ObjCAtSynchronizedStmt: return cxstring::createRef("ObjCAtSynchronizedStmt"); case CXCursor_ObjCAutoreleasePoolStmt: return cxstring::createRef("ObjCAutoreleasePoolStmt"); case CXCursor_ObjCForCollectionStmt: return cxstring::createRef("ObjCForCollectionStmt"); case CXCursor_CXXCatchStmt: return cxstring::createRef("CXXCatchStmt"); case CXCursor_CXXTryStmt: return cxstring::createRef("CXXTryStmt"); case CXCursor_CXXForRangeStmt: return cxstring::createRef("CXXForRangeStmt"); case CXCursor_SEHTryStmt: return cxstring::createRef("SEHTryStmt"); case CXCursor_SEHExceptStmt: return cxstring::createRef("SEHExceptStmt"); case CXCursor_SEHFinallyStmt: return cxstring::createRef("SEHFinallyStmt"); case CXCursor_SEHLeaveStmt: return cxstring::createRef("SEHLeaveStmt"); case CXCursor_NullStmt: return cxstring::createRef("NullStmt"); case CXCursor_InvalidFile: return cxstring::createRef("InvalidFile"); case CXCursor_InvalidCode: return cxstring::createRef("InvalidCode"); case CXCursor_NoDeclFound: return cxstring::createRef("NoDeclFound"); case CXCursor_NotImplemented: return cxstring::createRef("NotImplemented"); case CXCursor_TranslationUnit: return cxstring::createRef("TranslationUnit"); case CXCursor_UnexposedAttr: return cxstring::createRef("UnexposedAttr"); case CXCursor_IBActionAttr: return cxstring::createRef("attribute(ibaction)"); case CXCursor_IBOutletAttr: return cxstring::createRef("attribute(iboutlet)"); case CXCursor_IBOutletCollectionAttr: return cxstring::createRef("attribute(iboutletcollection)"); case CXCursor_CXXFinalAttr: return cxstring::createRef("attribute(final)"); case CXCursor_CXXOverrideAttr: return cxstring::createRef("attribute(override)"); case CXCursor_AnnotateAttr: return cxstring::createRef("attribute(annotate)"); case CXCursor_AsmLabelAttr: return cxstring::createRef("asm label"); case CXCursor_PackedAttr: return cxstring::createRef("attribute(packed)"); case CXCursor_PureAttr: return cxstring::createRef("attribute(pure)"); case CXCursor_ConstAttr: return cxstring::createRef("attribute(const)"); case CXCursor_NoDuplicateAttr: return cxstring::createRef("attribute(noduplicate)"); case CXCursor_CUDAConstantAttr: return cxstring::createRef("attribute(constant)"); case CXCursor_CUDADeviceAttr: return cxstring::createRef("attribute(device)"); case CXCursor_CUDAGlobalAttr: return cxstring::createRef("attribute(global)"); case CXCursor_CUDAHostAttr: return cxstring::createRef("attribute(host)"); case CXCursor_CUDASharedAttr: return cxstring::createRef("attribute(shared)"); case CXCursor_PreprocessingDirective: return cxstring::createRef("preprocessing directive"); case CXCursor_MacroDefinition: return cxstring::createRef("macro definition"); case CXCursor_MacroExpansion: return cxstring::createRef("macro expansion"); case CXCursor_InclusionDirective: return cxstring::createRef("inclusion directive"); case CXCursor_Namespace: return cxstring::createRef("Namespace"); case CXCursor_LinkageSpec: return cxstring::createRef("LinkageSpec"); case CXCursor_CXXBaseSpecifier: return cxstring::createRef("C++ base class specifier"); case CXCursor_Constructor: return cxstring::createRef("CXXConstructor"); case CXCursor_Destructor: return cxstring::createRef("CXXDestructor"); case CXCursor_ConversionFunction: return cxstring::createRef("CXXConversion"); case CXCursor_TemplateTypeParameter: return cxstring::createRef("TemplateTypeParameter"); case CXCursor_NonTypeTemplateParameter: return cxstring::createRef("NonTypeTemplateParameter"); case CXCursor_TemplateTemplateParameter: return cxstring::createRef("TemplateTemplateParameter"); case CXCursor_FunctionTemplate: return cxstring::createRef("FunctionTemplate"); case CXCursor_ClassTemplate: return cxstring::createRef("ClassTemplate"); case CXCursor_ClassTemplatePartialSpecialization: return cxstring::createRef("ClassTemplatePartialSpecialization"); case CXCursor_NamespaceAlias: return cxstring::createRef("NamespaceAlias"); case CXCursor_UsingDirective: return cxstring::createRef("UsingDirective"); case CXCursor_UsingDeclaration: return cxstring::createRef("UsingDeclaration"); case CXCursor_TypeAliasDecl: return cxstring::createRef("TypeAliasDecl"); case CXCursor_ObjCSynthesizeDecl: return cxstring::createRef("ObjCSynthesizeDecl"); case CXCursor_ObjCDynamicDecl: return cxstring::createRef("ObjCDynamicDecl"); case CXCursor_CXXAccessSpecifier: return cxstring::createRef("CXXAccessSpecifier"); case CXCursor_ModuleImportDecl: return cxstring::createRef("ModuleImport"); case CXCursor_OMPParallelDirective: return cxstring::createRef("OMPParallelDirective"); case CXCursor_OMPSimdDirective: return cxstring::createRef("OMPSimdDirective"); case CXCursor_OMPForDirective: return cxstring::createRef("OMPForDirective"); case CXCursor_OMPForSimdDirective: return cxstring::createRef("OMPForSimdDirective"); case CXCursor_OMPSectionsDirective: return cxstring::createRef("OMPSectionsDirective"); case CXCursor_OMPSectionDirective: return cxstring::createRef("OMPSectionDirective"); case CXCursor_OMPSingleDirective: return cxstring::createRef("OMPSingleDirective"); case CXCursor_OMPMasterDirective: return cxstring::createRef("OMPMasterDirective"); case CXCursor_OMPCriticalDirective: return cxstring::createRef("OMPCriticalDirective"); case CXCursor_OMPParallelForDirective: return cxstring::createRef("OMPParallelForDirective"); case CXCursor_OMPParallelForSimdDirective: return cxstring::createRef("OMPParallelForSimdDirective"); case CXCursor_OMPParallelSectionsDirective: return cxstring::createRef("OMPParallelSectionsDirective"); case CXCursor_OMPTaskDirective: return cxstring::createRef("OMPTaskDirective"); case CXCursor_OMPTaskyieldDirective: return cxstring::createRef("OMPTaskyieldDirective"); case CXCursor_OMPBarrierDirective: return cxstring::createRef("OMPBarrierDirective"); case CXCursor_OMPTaskwaitDirective: return cxstring::createRef("OMPTaskwaitDirective"); case CXCursor_OMPTaskgroupDirective: return cxstring::createRef("OMPTaskgroupDirective"); case CXCursor_OMPFlushDirective: return cxstring::createRef("OMPFlushDirective"); case CXCursor_OMPOrderedDirective: return cxstring::createRef("OMPOrderedDirective"); case CXCursor_OMPAtomicDirective: return cxstring::createRef("OMPAtomicDirective"); case CXCursor_OMPTargetDirective: return cxstring::createRef("OMPTargetDirective"); case CXCursor_OMPTeamsDirective: return cxstring::createRef("OMPTeamsDirective"); case CXCursor_OMPCancellationPointDirective: return cxstring::createRef("OMPCancellationPointDirective"); case CXCursor_OMPCancelDirective: return cxstring::createRef("OMPCancelDirective"); case CXCursor_OverloadCandidate: return cxstring::createRef("OverloadCandidate"); } llvm_unreachable("Unhandled CXCursorKind"); } struct GetCursorData { SourceLocation TokenBeginLoc; bool PointsAtMacroArgExpansion; bool VisitedObjCPropertyImplDecl; SourceLocation VisitedDeclaratorDeclStartLoc; CXCursor &BestCursor; GetCursorData(SourceManager &SM, SourceLocation tokenBegin, CXCursor &outputCursor) : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); VisitedObjCPropertyImplDecl = false; } }; static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { GetCursorData *Data = static_cast<GetCursorData *>(client_data); CXCursor *BestCursor = &Data->BestCursor; // If we point inside a macro argument we should provide info of what the // token is so use the actual cursor, don't replace it with a macro expansion // cursor. if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) return CXChildVisit_Recurse; if (clang_isDeclaration(cursor.kind)) { // Avoid having the implicit methods override the property decls. if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { if (MD->isImplicit()) return CXChildVisit_Break; } else if (const ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { // Check that when we have multiple @class references in the same line, // that later ones do not override the previous ones. // If we have: // @class Foo, Bar; // source ranges for both start at '@', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || BestCursor->kind == CXCursor_ObjCClassRef) if (const ObjCInterfaceDecl *PrevID = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){ if (PrevID != ID && !PrevID->isThisDeclarationADefinition() && !ID->isThisDeclarationADefinition()) return CXChildVisit_Break; } } else if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { SourceLocation StartLoc = DD->getSourceRange().getBegin(); // Check that when we have multiple declarators in the same line, // that later ones do not override the previous ones. // If we have: // int Foo, Bar; // source ranges for both start at 'int', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) return CXChildVisit_Break; Data->VisitedDeclaratorDeclStartLoc = StartLoc; } else if (const ObjCPropertyImplDecl *PropImp = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) { (void)PropImp; // Check that when we have multiple @synthesize in the same line, // that later ones do not override the previous ones. // If we have: // @synthesize Foo, Bar; // source ranges for both start at '@', so 'Bar' will end up overriding // 'Foo' even though the cursor location was at 'Foo'. if (Data->VisitedObjCPropertyImplDecl) return CXChildVisit_Break; Data->VisitedObjCPropertyImplDecl = true; } } if (clang_isExpression(cursor.kind) && clang_isDeclaration(BestCursor->kind)) { if (const Decl *D = getCursorDecl(*BestCursor)) { // Avoid having the cursor of an expression replace the declaration cursor // when the expression source range overlaps the declaration range. // This can happen for C++ constructor expressions whose range generally // include the variable declaration, e.g.: // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && D->getLocation() == Data->TokenBeginLoc) return CXChildVisit_Break; } } // If our current best cursor is the construction of a temporary object, // don't replace that cursor with a type reference, because we want // clang_getCursor() to point at the constructor. if (clang_isExpression(BestCursor->kind) && isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && cursor.kind == CXCursor_TypeRef) { // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it // as having the actual point on the type reference. *BestCursor = getTypeRefedCallExprCursor(*BestCursor); return CXChildVisit_Recurse; } // If we already have an Objective-C superclass reference, don't // update it further. if (BestCursor->kind == CXCursor_ObjCSuperClassRef) return CXChildVisit_Break; *BestCursor = cursor; return CXChildVisit_Recurse; } CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullCursor(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); ASTUnit::ConcurrencyCheck Check(*CXXUnit); SourceLocation SLoc = cxloc::translateSourceLocation(Loc); CXCursor Result = cxcursor::getCursor(TU, SLoc); LOG_FUNC_SECTION { CXFile SearchFile; unsigned SearchLine, SearchColumn; CXFile ResultFile; unsigned ResultLine, ResultColumn; CXString SearchFileName, ResultFileName, KindSpelling, USR; const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; CXSourceLocation ResultLoc = clang_getCursorLocation(Result); clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, nullptr); clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn, nullptr); SearchFileName = clang_getFileName(SearchFile); ResultFileName = clang_getFileName(ResultFile); KindSpelling = clang_getCursorKindSpelling(Result.kind); USR = clang_getCursorUSR(Result); *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName), SearchLine, SearchColumn, clang_getCString(KindSpelling)) << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName), ResultLine, ResultColumn, clang_getCString(USR), IsDef); clang_disposeString(SearchFileName); clang_disposeString(ResultFileName); clang_disposeString(KindSpelling); clang_disposeString(USR); CXCursor Definition = clang_getCursorDefinition(Result); if (!clang_equalCursors(Definition, clang_getNullCursor())) { CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); CXString DefinitionKindSpelling = clang_getCursorKindSpelling(Definition.kind); CXFile DefinitionFile; unsigned DefinitionLine, DefinitionColumn; clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine, &DefinitionColumn, nullptr); CXString DefinitionFileName = clang_getFileName(DefinitionFile); *Log << llvm::format(" -> %s(%s:%d:%d)", clang_getCString(DefinitionKindSpelling), clang_getCString(DefinitionFileName), DefinitionLine, DefinitionColumn); clang_disposeString(DefinitionFileName); clang_disposeString(DefinitionKindSpelling); } } return Result; } CXCursor clang_getNullCursor(void) { return MakeCXCursorInvalid(CXCursor_InvalidFile); } unsigned clang_equalCursors(CXCursor X, CXCursor Y) { // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we // can't set consistently. For example, when visiting a DeclStmt we will set // it but we don't set it on the result of clang_getCursorDefinition for // a reference of the same declaration. // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works // when visiting a DeclStmt currently, the AST should be enhanced to be able // to provide that kind of info. if (clang_isDeclaration(X.kind)) X.data[1] = nullptr; if (clang_isDeclaration(Y.kind)) Y.data[1] = nullptr; return X == Y; } unsigned clang_hashCursor(CXCursor C) { unsigned Index = 0; if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) Index = 1; return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue( std::make_pair(C.kind, C.data[Index])); } unsigned clang_isInvalid(enum CXCursorKind K) { return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; } unsigned clang_isDeclaration(enum CXCursorKind K) { return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); } unsigned clang_isReference(enum CXCursorKind K) { return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; } unsigned clang_isExpression(enum CXCursorKind K) { return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; } unsigned clang_isStatement(enum CXCursorKind K) { return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; } unsigned clang_isAttribute(enum CXCursorKind K) { return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; } unsigned clang_isTranslationUnit(enum CXCursorKind K) { return K == CXCursor_TranslationUnit; } unsigned clang_isPreprocessing(enum CXCursorKind K) { return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; } unsigned clang_isUnexposed(enum CXCursorKind K) { switch (K) { case CXCursor_UnexposedDecl: case CXCursor_UnexposedExpr: case CXCursor_UnexposedStmt: case CXCursor_UnexposedAttr: return true; default: return false; } } CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; } CXSourceLocation clang_getCursorLocation(CXCursor C) { if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: { std::pair<const ObjCInterfaceDecl *, SourceLocation> P = getCursorObjCSuperClassRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_ObjCProtocolRef: { std::pair<const ObjCProtocolDecl *, SourceLocation> P = getCursorObjCProtocolRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_ObjCClassRef: { std::pair<const ObjCInterfaceDecl *, SourceLocation> P = getCursorObjCClassRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_TypeRef: { std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_TemplateRef: { std::pair<const TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_NamespaceRef: { std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_MemberRef: { std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_VariableRef: { std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); } case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); if (!BaseSpec) return clang_getNullLocation(); if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) return cxloc::translateSourceLocation(getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc()); return cxloc::translateSourceLocation(getCursorContext(C), BaseSpec->getLocStart()); } case CXCursor_LabelRef: { std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); return cxloc::translateSourceLocation(getCursorContext(C), P.second); } case CXCursor_OverloadedDeclRef: return cxloc::translateSourceLocation(getCursorContext(C), getCursorOverloadedDeclRef(C).second); default: // FIXME: Need a way to enumerate all non-reference cases. llvm_unreachable("Missed a reference kind"); } } if (clang_isExpression(C.kind)) return cxloc::translateSourceLocation(getCursorContext(C), getLocationFromExpr(getCursorExpr(C))); if (clang_isStatement(C.kind)) return cxloc::translateSourceLocation(getCursorContext(C), getCursorStmt(C)->getLocStart()); if (C.kind == CXCursor_PreprocessingDirective) { SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_MacroExpansion) { SourceLocation L = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_MacroDefinition) { SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (C.kind == CXCursor_InclusionDirective) { SourceLocation L = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (clang_isAttribute(C.kind)) { SourceLocation L = cxcursor::getCursorAttr(C)->getLocation(); return cxloc::translateSourceLocation(getCursorContext(C), L); } if (!clang_isDeclaration(C.kind)) return clang_getNullLocation(); const Decl *D = getCursorDecl(C); if (!D) return clang_getNullLocation(); SourceLocation Loc = D->getLocation(); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (!cxcursor::isFirstInDeclGroup(C)) Loc = VD->getLocation(); } // For ObjC methods, give the start location of the method name. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) Loc = MD->getSelectorStartLoc(); return cxloc::translateSourceLocation(getCursorContext(C), Loc); } // } // end extern "C" // HLSL Change -Don't use c linkage. CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { assert(TU); // Guard against an invalid SourceLocation, or we may assert in one // of the following calls. if (SLoc.isInvalid()) return clang_getNullCursor(); ASTUnit *CXXUnit = cxtu::getASTUnit(TU); // Translate the given source location to make it point at the beginning of // the token under the cursor. SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), CXXUnit->getASTContext().getLangOpts()); CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); if (SLoc.isValid()) { GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, SourceLocation(SLoc)); CursorVis.visitFileRegion(); } return Result; } static SourceRange getRawCursorExtent(CXCursor C) { if (clang_isReference(C.kind)) { switch (C.kind) { case CXCursor_ObjCSuperClassRef: return getCursorObjCSuperClassRef(C).second; case CXCursor_ObjCProtocolRef: return getCursorObjCProtocolRef(C).second; case CXCursor_ObjCClassRef: return getCursorObjCClassRef(C).second; case CXCursor_TypeRef: return getCursorTypeRef(C).second; case CXCursor_TemplateRef: return getCursorTemplateRef(C).second; case CXCursor_NamespaceRef: return getCursorNamespaceRef(C).second; case CXCursor_MemberRef: return getCursorMemberRef(C).second; case CXCursor_CXXBaseSpecifier: return getCursorCXXBaseSpecifier(C)->getSourceRange(); case CXCursor_LabelRef: return getCursorLabelRef(C).second; case CXCursor_OverloadedDeclRef: return getCursorOverloadedDeclRef(C).second; case CXCursor_VariableRef: return getCursorVariableRef(C).second; default: // FIXME: Need a way to enumerate all non-reference cases. llvm_unreachable("Missed a reference kind"); } } if (clang_isExpression(C.kind)) return getCursorExpr(C)->getSourceRange(); if (clang_isStatement(C.kind)) return getCursorStmt(C)->getSourceRange(); if (clang_isAttribute(C.kind)) return getCursorAttr(C)->getRange(); if (C.kind == CXCursor_PreprocessingDirective) return cxcursor::getCursorPreprocessingDirective(C); if (C.kind == CXCursor_MacroExpansion) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_MacroDefinition) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_InclusionDirective) { ASTUnit *TU = getCursorASTUnit(C); SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); return TU->mapRangeFromPreamble(Range); } if (C.kind == CXCursor_TranslationUnit) { ASTUnit *TU = getCursorASTUnit(C); FileID MainID = TU->getSourceManager().getMainFileID(); SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); return SourceRange(Start, End); } if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return SourceRange(); SourceRange R = D->getSourceRange(); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (!cxcursor::isFirstInDeclGroup(C)) R.setBegin(VD->getLocation()); } return R; } return SourceRange(); } /// \brief Retrieves the "raw" cursor extent, which is then extended to include /// the decl-specifier-seq for declarations. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { if (clang_isDeclaration(C.kind)) { const Decl *D = cxcursor::getCursorDecl(C); if (!D) return SourceRange(); SourceRange R = D->getSourceRange(); // Adjust the start of the location for declarations preceded by // declaration specifiers. SourceLocation StartLoc; if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) StartLoc = TI->getTypeLoc().getLocStart(); } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) StartLoc = TI->getTypeLoc().getLocStart(); } if (StartLoc.isValid() && R.getBegin().isValid() && SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) R.setBegin(StartLoc); // FIXME: Multiple variables declared in a single declaration // currently lack the information needed to correctly determine their // ranges when accounting for the type-specifier. We use context // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, // and if so, whether it is the first decl. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (!cxcursor::isFirstInDeclGroup(C)) R.setBegin(VD->getLocation()); } return R; } return getRawCursorExtent(C); } // extern "C" { // HLSL Change -Don't use c linkage. CXSourceRange clang_getCursorExtent(CXCursor C) { SourceRange R = getRawCursorExtent(C); if (R.isInvalid()) return clang_getNullRange(); return cxloc::translateSourceRange(getCursorContext(C), R); } CXCursor clang_getCursorReferenced(CXCursor C) { if (clang_isInvalid(C.kind)) return clang_getNullCursor(); CXTranslationUnit tu = getCursorTU(C); if (clang_isDeclaration(C.kind)) { const Decl *D = getCursorDecl(C); if (!D) return clang_getNullCursor(); if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); if (const ObjCPropertyImplDecl *PropImpl = dyn_cast<ObjCPropertyImplDecl>(D)) if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) return MakeCXCursor(Property, tu); return C; } if (clang_isExpression(C.kind)) { const Expr *E = getCursorExpr(C); const Decl *D = getDeclFromExpr(E); if (D) { CXCursor declCursor = MakeCXCursor(D, tu); declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), declCursor); return declCursor; } if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) return MakeCursorOverloadedDeclRef(Ovl, tu); return clang_getNullCursor(); } if (clang_isStatement(C.kind)) { const Stmt *S = getCursorStmt(C); if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) if (LabelDecl *label = Goto->getLabel()) if (LabelStmt *labelS = label->getStmt()) return MakeCXCursor(labelS, getCursorDecl(C), tu); return clang_getNullCursor(); } if (C.kind == CXCursor_MacroExpansion) { if (const MacroDefinitionRecord *Def = getCursorMacroExpansion(C).getDefinition()) return MakeMacroDefinitionCursor(Def, tu); } if (!clang_isReference(C.kind)) return clang_getNullCursor(); switch (C.kind) { case CXCursor_ObjCSuperClassRef: return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); case CXCursor_ObjCProtocolRef: { const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; if (const ObjCProtocolDecl *Def = Prot->getDefinition()) return MakeCXCursor(Def, tu); return MakeCXCursor(Prot, tu); } case CXCursor_ObjCClassRef: { const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; if (const ObjCInterfaceDecl *Def = Class->getDefinition()) return MakeCXCursor(Def, tu); return MakeCXCursor(Class, tu); } case CXCursor_TypeRef: return MakeCXCursor(getCursorTypeRef(C).first, tu ); case CXCursor_TemplateRef: return MakeCXCursor(getCursorTemplateRef(C).first, tu ); case CXCursor_NamespaceRef: return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); case CXCursor_MemberRef: return MakeCXCursor(getCursorMemberRef(C).first, tu ); case CXCursor_CXXBaseSpecifier: { const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu )); } case CXCursor_LabelRef: // FIXME: We end up faking the "parent" declaration here because we // don't want to make CXCursor larger. return MakeCXCursor(getCursorLabelRef(C).first, cxtu::getASTUnit(tu)->getASTContext() .getTranslationUnitDecl(), tu); case CXCursor_OverloadedDeclRef: return C; case CXCursor_VariableRef: return MakeCXCursor(getCursorVariableRef(C).first, tu); default: // We would prefer to enumerate all non-reference cursor kinds here. llvm_unreachable("Unhandled reference cursor kind"); } } CXCursor clang_getCursorDefinition(CXCursor C) { if (clang_isInvalid(C.kind)) return clang_getNullCursor(); CXTranslationUnit TU = getCursorTU(C); bool WasReference = false; if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { C = clang_getCursorReferenced(C); WasReference = true; } if (C.kind == CXCursor_MacroExpansion) return clang_getCursorReferenced(C); if (!clang_isDeclaration(C.kind)) return clang_getNullCursor(); const Decl *D = getCursorDecl(C); if (!D) return clang_getNullCursor(); switch (D->getKind()) { // Declaration kinds that don't really separate the notions of // declaration and definition. case Decl::Namespace: case Decl::Typedef: case Decl::TypeAlias: case Decl::TypeAliasTemplate: case Decl::TemplateTypeParm: case Decl::EnumConstant: case Decl::Field: case Decl::MSProperty: case Decl::IndirectField: case Decl::ObjCIvar: case Decl::ObjCAtDefsField: case Decl::ImplicitParam: case Decl::ParmVar: case Decl::NonTypeTemplateParm: case Decl::TemplateTemplateParm: case Decl::ObjCCategoryImpl: case Decl::ObjCImplementation: case Decl::AccessSpec: case Decl::LinkageSpec: case Decl::ObjCPropertyImpl: case Decl::FileScopeAsm: case Decl::StaticAssert: case Decl::Block: case Decl::Captured: case Decl::Label: // FIXME: Is this right?? case Decl::ClassScopeFunctionSpecialization: case Decl::Import: case Decl::OMPThreadPrivate: case Decl::ObjCTypeParam: return C; // Declaration kinds that don't make any sense here, but are // nonetheless harmless. case Decl::Empty: case Decl::TranslationUnit: case Decl::ExternCContext: break; // Declaration kinds for which the definition is not resolvable. case Decl::UnresolvedUsingTypename: case Decl::UnresolvedUsingValue: break; case Decl::UsingDirective: return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), TU); case Decl::NamespaceAlias: return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); case Decl::Enum: case Decl::Record: case Decl::CXXRecord: case Decl::ClassTemplateSpecialization: case Decl::ClassTemplatePartialSpecialization: if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::Function: case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: case Decl::CXXConversion: { const FunctionDecl *Def = nullptr; if (cast<FunctionDecl>(D)->getBody(Def)) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::Var: case Decl::VarTemplateSpecialization: case Decl::VarTemplatePartialSpecialization: { // Ask the variable if it has a definition. if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::FunctionTemplate: { const FunctionDecl *Def = nullptr; if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); return clang_getNullCursor(); } case Decl::ClassTemplate: { if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() ->getDefinition()) return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), TU); return clang_getNullCursor(); } case Decl::VarTemplate: { if (VarDecl *Def = cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU); return clang_getNullCursor(); } case Decl::Using: return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), D->getLocation(), TU); case Decl::UsingShadow: return clang_getCursorDefinition( MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU)); case Decl::ObjCMethod: { const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); if (Method->isThisDeclarationADefinition()) return C; // Dig out the method definition in the associated // @implementation, if we have it. // FIXME: The ASTs should make finding the definition easier. if (const ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), Method->isInstanceMethod())) if (Def->isThisDeclarationADefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); } case Decl::ObjCCategory: if (ObjCCategoryImplDecl *Impl = cast<ObjCCategoryDecl>(D)->getImplementation()) return MakeCXCursor(Impl, TU); return clang_getNullCursor(); case Decl::ObjCProtocol: if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::ObjCInterface: { // There are two notions of a "definition" for an Objective-C // class: the interface and its implementation. When we resolved a // reference to an Objective-C class, produce the @interface as // the definition; when we were provided with the interface, // produce the @implementation as the definition. const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); if (WasReference) { if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) return MakeCXCursor(Def, TU); } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) return MakeCXCursor(Impl, TU); return clang_getNullCursor(); } case Decl::ObjCProperty: // FIXME: We don't really know where to find the // ObjCPropertyImplDecls that implement this property. return clang_getNullCursor(); case Decl::ObjCCompatibleAlias: if (const ObjCInterfaceDecl *Class = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) if (const ObjCInterfaceDecl *Def = Class->getDefinition()) return MakeCXCursor(Def, TU); return clang_getNullCursor(); case Decl::Friend: if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); return clang_getNullCursor(); case Decl::FriendTemplate: if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); return clang_getNullCursor(); case Decl::HLSLBuffer: // HLSL Change return clang_getNullCursor(); // HLSL Change } return clang_getNullCursor(); } unsigned clang_isCursorDefinition(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; return clang_getCursorDefinition(C) == C; } CXCursor clang_getCanonicalCursor(CXCursor C) { if (!clang_isDeclaration(C.kind)) return C; if (const Decl *D = getCursorDecl(C)) { if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) return MakeCXCursor(CatD, getCursorTU(C)); if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) return MakeCXCursor(IFD, getCursorTU(C)); return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); } return C; } int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; } unsigned clang_getNumOverloadedDecls(CXCursor C) { if (C.kind != CXCursor_OverloadedDeclRef) return 0; OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) return E->getNumDecls(); if (OverloadedTemplateStorage *S = Storage.dyn_cast<OverloadedTemplateStorage*>()) return S->size(); const Decl *D = Storage.get<const Decl *>(); if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) return Using->shadow_size(); return 0; } CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { if (cursor.kind != CXCursor_OverloadedDeclRef) return clang_getNullCursor(); if (index >= clang_getNumOverloadedDecls(cursor)) return clang_getNullCursor(); CXTranslationUnit TU = getCursorTU(cursor); OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) return MakeCXCursor(E->decls_begin()[index], TU); if (OverloadedTemplateStorage *S = Storage.dyn_cast<OverloadedTemplateStorage*>()) return MakeCXCursor(S->begin()[index], TU); const Decl *D = Storage.get<const Decl *>(); if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) { // FIXME: This is, unfortunately, linear time. UsingDecl::shadow_iterator Pos = Using->shadow_begin(); std::advance(Pos, index); return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); } return clang_getNullCursor(); } void clang_getDefinitionSpellingAndExtent(CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine, unsigned *startColumn, unsigned *endLine, unsigned *endColumn) { assert(getCursorDecl(C) && "CXCursor has null decl"); const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C)); CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); SourceManager &SM = FD->getASTContext().getSourceManager(); *startBuf = SM.getCharacterData(Body->getLBracLoc()); *endBuf = SM.getCharacterData(Body->getRBracLoc()); *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); } CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, unsigned PieceIndex) { RefNamePieces Pieces; switch (C.kind) { case CXCursor_MemberRefExpr: if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), E->getQualifierLoc().getSourceRange()); break; case CXCursor_DeclRefExpr: if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) Pieces = buildPieces(NameFlags, false, E->getNameInfo(), E->getQualifierLoc().getSourceRange(), E->getOptionalExplicitTemplateArgs()); break; case CXCursor_CallExpr: if (const CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { const Expr *Callee = OCE->getCallee(); if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) Callee = ICE->getSubExpr(); if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), DRE->getQualifierLoc().getSourceRange()); } break; default: break; } if (Pieces.empty()) { if (PieceIndex == 0) return clang_getCursorExtent(C); } else if (PieceIndex < Pieces.size()) { SourceRange R = Pieces[PieceIndex]; if (R.isValid()) return cxloc::translateSourceRange(getCursorContext(C), R); } return clang_getNullRange(); } void clang_enableStackTraces(void) { llvm::sys::PrintStackTraceOnErrorSignal(); } void clang_executeOnThread(void (*fn)(void*), void *user_data, unsigned stack_size) { llvm::llvm_execute_on_thread(fn, user_data, stack_size); } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Token-based Operations. //===----------------------------------------------------------------------===// /* CXToken layout: * int_data[0]: a CXTokenKind * int_data[1]: starting token location * int_data[2]: token length * int_data[3]: reserved * ptr_data: for identifiers and keywords, an IdentifierInfo*. * otherwise unused. */ // extern "C" { // HLSL Change -Don't use c linkage. CXTokenKind clang_getTokenKind(CXToken CXTok) { return static_cast<CXTokenKind>(CXTok.int_data[0]); } CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { switch (clang_getTokenKind(CXTok)) { case CXToken_Identifier: case CXToken_Keyword: case CXToken_BuiltInType: // HLSL Change // We know we have an IdentifierInfo*, so use that. return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data) ->getNameStart()); case CXToken_Literal: { // We have stashed the starting pointer in the ptr_data field. Use it. const char *Text = static_cast<const char *>(CXTok.ptr_data); return cxstring::createDup(StringRef(Text, CXTok.int_data[2])); } case CXToken_Punctuation: case CXToken_Comment: break; } if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return cxstring::createEmpty(); } // We have to find the starting buffer pointer the hard way, by // deconstructing the source location. ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit) return cxstring::createEmpty(); SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); std::pair<FileID, unsigned> LocInfo = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); bool Invalid = false; StringRef Buffer = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); if (Invalid) return cxstring::createEmpty(); return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2])); } CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullLocation(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit) return clang_getNullLocation(); return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SourceLocation::getFromRawEncoding(CXTok.int_data[1])); } CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return clang_getNullRange(); } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit) return clang_getNullRange(); return cxloc::translateSourceRange(CXXUnit->getASTContext(), SourceLocation::getFromRawEncoding(CXTok.int_data[1])); } // HLSL Change Starts static bool IsHLSLBuiltInType(IdentifierInfo* ii, const LangOptions &langOpts) { // Checks, purely by name, whether the specified identifier is considered a built-in type. clang::tok::TokenKind tokenKind = ii->getTokenID(); // Some of the built-in types are keywords. if (tokenKind == clang::tok::kw_bool || tokenKind == clang::tok::kw_int || tokenKind == clang::tok::kw_float || tokenKind == clang::tok::kw_double) { return true; } // Vectors and matrices can be parsed with internal lookup tables. hlsl::HLSLScalarType scalarType; int count; return hlsl::TryParseAny(ii->getNameStart(), ii->getLength(), &scalarType, &count, &count, langOpts); } // HLSL Change Ends static void getTokens(ASTUnit *CXXUnit, SourceRange Range, SmallVectorImpl<CXToken> &CXTokens) { SourceManager &SourceMgr = CXXUnit->getSourceManager(); std::pair<FileID, unsigned> BeginLocInfo = SourceMgr.getDecomposedSpellingLoc(Range.getBegin()); std::pair<FileID, unsigned> EndLocInfo = SourceMgr.getDecomposedSpellingLoc(Range.getEnd()); // Cannot tokenize across files. if (BeginLocInfo.first != EndLocInfo.first) return; // Create a lexer bool Invalid = false; StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); if (Invalid) return; Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); Lex.SetCommentRetentionState(true); // Lex tokens until we hit the end of the range. const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; Token Tok; bool previousWasAt = false; do { // Lex the next token Lex.LexFromRawLexer(Tok); if (Tok.is(tok::eof)) break; // Initialize the CXToken. CXToken CXTok; // - Common fields CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); CXTok.int_data[2] = Tok.getLength(); CXTok.int_data[3] = 0; // - Kind-specific fields if (Tok.isLiteral()) { CXTok.int_data[0] = CXToken_Literal; CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData()); } else if (Tok.is(tok::raw_identifier)) { // Lookup the identifier to determine whether we have a keyword. IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { CXTok.int_data[0] = CXToken_Keyword; } // HLSL Change Starts - Check for HLSL built-in types else if (IsHLSLBuiltInType(II, CXXUnit->getLangOpts())) { CXTok.int_data[0] = CXToken_BuiltInType; } // HLSL Change Ends else { CXTok.int_data[0] = Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword; } CXTok.ptr_data = II; } else if (Tok.is(tok::comment)) { CXTok.int_data[0] = CXToken_Comment; CXTok.ptr_data = nullptr; } else { CXTok.int_data[0] = CXToken_Punctuation; CXTok.ptr_data = nullptr; } CXTokens.push_back(CXTok); previousWasAt = Tok.is(tok::at); } while (Lex.getBufferLocation() <= EffectiveBufferEnd); } void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens, unsigned *NumTokens) { LOG_FUNC_SECTION { *Log << TU << ' ' << Range; } if (Tokens) *Tokens = nullptr; if (NumTokens) *NumTokens = 0; if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return; } ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit || !Tokens || !NumTokens) return; ASTUnit::ConcurrencyCheck Check(*CXXUnit); SourceRange R = cxloc::translateCXSourceRange(Range); if (R.isInvalid()) return; SmallVector<CXToken, 32> CXTokens; getTokens(CXXUnit, R, CXTokens); if (CXTokens.empty()) return; *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); *NumTokens = CXTokens.size(); } void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens, unsigned NumTokens) { free(Tokens); } //} // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Token annotation APIs. //===----------------------------------------------------------------------===// static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data); static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, CXClientData client_data); namespace { class AnnotateTokensWorker { CXToken *Tokens; CXCursor *Cursors; unsigned NumTokens; unsigned TokIdx; unsigned PreprocessingTokIdx; CursorVisitor AnnotateVis; SourceManager &SrcMgr; bool HasContextSensitiveKeywords; struct PostChildrenInfo { CXCursor Cursor; SourceRange CursorRange; unsigned BeforeReachingCursorIdx; unsigned BeforeChildrenTokenIdx; }; SmallVector<PostChildrenInfo, 8> PostChildrenInfos; CXToken &getTok(unsigned Idx) { assert(Idx < NumTokens); return Tokens[Idx]; } const CXToken &getTok(unsigned Idx) const { assert(Idx < NumTokens); return Tokens[Idx]; } bool MoreTokens() const { return TokIdx < NumTokens; } unsigned NextToken() const { return TokIdx; } void AdvanceToken() { ++TokIdx; } SourceLocation GetTokenLoc(unsigned tokI) { return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); } bool isFunctionMacroToken(unsigned tokI) const { return getTok(tokI).int_data[3] != 0; } SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]); } void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, SourceRange); public: AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, CXTranslationUnit TU, SourceRange RegionOfInterest) : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), AnnotateVis(TU, AnnotateTokensVisitor, this, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, RegionOfInterest, /*VisitDeclsOnly=*/false, AnnotateTokensPostChildrenVisitor), SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()), HasContextSensitiveKeywords(false) { } void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); bool postVisitChildren(CXCursor cursor); void AnnotateTokens(); /// \brief Determine whether the annotator saw any cursors that have /// context-sensitive keywords. bool hasContextSensitiveKeywords() const { return HasContextSensitiveKeywords; } ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); } }; } void AnnotateTokensWorker::AnnotateTokens() { // Walk the AST within the region of interest, annotating tokens // along the way. AnnotateVis.visitFileRegion(); } static inline void updateCursorAnnotation(CXCursor &Cursor, const CXCursor &updateC) { if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind)) return; Cursor = updateC; } /// \brief It annotates and advances tokens with a cursor until the comparison //// between the cursor location and the source range is the same as /// \arg compResult. /// /// Pass RangeBefore to annotate tokens with a cursor until a range is reached. /// Pass RangeOverlap to annotate tokens inside a range. void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { while (MoreTokens()) { const unsigned I = NextToken(); if (isFunctionMacroToken(I)) if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range)) return; SourceLocation TokLoc = GetTokenLoc(I); if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { updateCursorAnnotation(Cursors[I], updateC); AdvanceToken(); continue; } break; } } /// \brief Special annotation handling for macro argument tokens. /// \returns true if it advanced beyond all macro tokens, false otherwise. bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { assert(MoreTokens()); assert(isFunctionMacroToken(NextToken()) && "Should be called only for macro arg tokens"); // This works differently than annotateAndAdvanceTokens; because expanded // macro arguments can have arbitrary translation-unit source order, we do not // advance the token index one by one until a token fails the range test. // We only advance once past all of the macro arg tokens if all of them // pass the range test. If one of them fails we keep the token index pointing // at the start of the macro arg tokens so that the failing token will be // annotated by a subsequent annotation try. bool atLeastOneCompFail = false; unsigned I = NextToken(); for (; I < NumTokens && isFunctionMacroToken(I); ++I) { SourceLocation TokLoc = getFunctionMacroTokenLoc(I); if (TokLoc.isFileID()) continue; // not macro arg token, it's parens or comma. if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) Cursors[I] = updateC; } else atLeastOneCompFail = true; } if (atLeastOneCompFail) return false; TokIdx = I; // All of the tokens were handled, advance beyond all of them. return true; } enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { SourceRange cursorRange = getRawCursorExtent(cursor); if (cursorRange.isInvalid()) return CXChildVisit_Recurse; if (!HasContextSensitiveKeywords) { // Objective-C properties can have context-sensitive keywords. if (cursor.kind == CXCursor_ObjCPropertyDecl) { if (const ObjCPropertyDecl *Property = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; } // Objective-C methods can have context-sensitive keywords. else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || cursor.kind == CXCursor_ObjCClassMethodDecl) { if (const ObjCMethodDecl *Method = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { if (Method->getObjCDeclQualifier()) HasContextSensitiveKeywords = true; else { for (const auto *P : Method->params()) { if (P->getObjCDeclQualifier()) { HasContextSensitiveKeywords = true; break; } } } } } // C++ methods can have context-sensitive keywords. else if (cursor.kind == CXCursor_CXXMethod) { if (const CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) HasContextSensitiveKeywords = true; } } // C++ classes can have context-sensitive keywords. else if (cursor.kind == CXCursor_StructDecl || cursor.kind == CXCursor_ClassDecl || cursor.kind == CXCursor_ClassTemplate || cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { if (const Decl *D = getCursorDecl(cursor)) if (D->hasAttr<FinalAttr>()) HasContextSensitiveKeywords = true; } } // Don't override a property annotation with its getter/setter method. if (cursor.kind == CXCursor_ObjCInstanceMethodDecl && parent.kind == CXCursor_ObjCPropertyDecl) return CXChildVisit_Continue; if (clang_isPreprocessing(cursor.kind)) { // Items in the preprocessing record are kept separate from items in // declarations, so we keep a separate token index. unsigned SavedTokIdx = TokIdx; TokIdx = PreprocessingTokIdx; // Skip tokens up until we catch up to the beginning of the preprocessing // entry. while (MoreTokens()) { const unsigned I = NextToken(); SourceLocation TokLoc = GetTokenLoc(I); switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { case RangeBefore: AdvanceToken(); continue; case RangeAfter: case RangeOverlap: break; } break; } // Look at all of the tokens within this range. while (MoreTokens()) { const unsigned I = NextToken(); SourceLocation TokLoc = GetTokenLoc(I); switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { case RangeBefore: llvm_unreachable("Infeasible"); case RangeAfter: break; case RangeOverlap: // For macro expansions, just note where the beginning of the macro // expansion occurs. if (cursor.kind == CXCursor_MacroExpansion) { if (TokLoc == cursorRange.getBegin()) Cursors[I] = cursor; AdvanceToken(); break; } // We may have already annotated macro names inside macro definitions. if (Cursors[I].kind != CXCursor_MacroExpansion) Cursors[I] = cursor; AdvanceToken(); continue; } break; } // Save the preprocessing token index; restore the non-preprocessing // token index. PreprocessingTokIdx = TokIdx; TokIdx = SavedTokIdx; return CXChildVisit_Recurse; } if (cursorRange.isInvalid()) return CXChildVisit_Continue; unsigned BeforeReachingCursorIdx = NextToken(); const enum CXCursorKind cursorK = clang_getCursorKind(cursor); const enum CXCursorKind K = clang_getCursorKind(parent); const CXCursor updateC = (clang_isInvalid(K) || K == CXCursor_TranslationUnit || // Attributes are annotated out-of-order, skip tokens until we reach it. clang_isAttribute(cursor.kind)) ? clang_getNullCursor() : parent; annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); // Avoid having the cursor of an expression "overwrite" the annotation of the // variable declaration that it belongs to. // This can happen for C++ constructor expressions whose range generally // include the variable declaration, e.g.: // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. if (clang_isExpression(cursorK) && MoreTokens()) { const Expr *E = getCursorExpr(cursor); if (const Decl *D = getCursorParentDecl(cursor)) { const unsigned I = NextToken(); if (E->getLocStart().isValid() && D->getLocation().isValid() && E->getLocStart() == D->getLocation() && E->getLocStart() == GetTokenLoc(I)) { updateCursorAnnotation(Cursors[I], updateC); AdvanceToken(); } } } // Before recursing into the children keep some state that we are going // to use in the AnnotateTokensWorker::postVisitChildren callback to do some // extra work after the child nodes are visited. // Note that we don't call VisitChildren here to avoid traversing statements // code-recursively which can blow the stack. PostChildrenInfo Info; Info.Cursor = cursor; Info.CursorRange = cursorRange; Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx; Info.BeforeChildrenTokenIdx = NextToken(); PostChildrenInfos.push_back(Info); return CXChildVisit_Recurse; } bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { if (PostChildrenInfos.empty()) return false; const PostChildrenInfo &Info = PostChildrenInfos.back(); if (!clang_equalCursors(Info.Cursor, cursor)) return false; const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; const unsigned AfterChildren = NextToken(); SourceRange cursorRange = Info.CursorRange; // Scan the tokens that are at the end of the cursor, but are not captured // but the child cursors. annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); // Scan the tokens that are at the beginning of the cursor, but are not // capture by the child cursors. for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) break; Cursors[I] = cursor; } // Attributes are annotated out-of-order, rewind TokIdx to when we first // encountered the attribute cursor. if (clang_isAttribute(cursor.kind)) TokIdx = Info.BeforeReachingCursorIdx; PostChildrenInfos.pop_back(); return false; } static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); } static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, CXClientData client_data) { return static_cast<AnnotateTokensWorker*>(client_data)-> postVisitChildren(cursor); } namespace { /// \brief Uses the macro expansions in the preprocessing record to find /// and mark tokens that are macro arguments. This info is used by the /// AnnotateTokensWorker. class MarkMacroArgTokensVisitor { SourceManager &SM; CXToken *Tokens; unsigned NumTokens; unsigned CurIdx; public: MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens, unsigned numTokens) : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { } CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { if (cursor.kind != CXCursor_MacroExpansion) return CXChildVisit_Continue; SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); if (macroRange.getBegin() == macroRange.getEnd()) return CXChildVisit_Continue; // it's not a function macro. for (; CurIdx < NumTokens; ++CurIdx) { if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), macroRange.getBegin())) break; } if (CurIdx == NumTokens) return CXChildVisit_Break; for (; CurIdx < NumTokens; ++CurIdx) { SourceLocation tokLoc = getTokenLoc(CurIdx); if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) break; setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); } if (CurIdx == NumTokens) return CXChildVisit_Break; return CXChildVisit_Continue; } private: CXToken &getTok(unsigned Idx) { assert(Idx < NumTokens); return Tokens[Idx]; } const CXToken &getTok(unsigned Idx) const { assert(Idx < NumTokens); return Tokens[Idx]; } SourceLocation getTokenLoc(unsigned tokI) { return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); } void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { // The third field is reserved and currently not used. Use it here // to mark macro arg expanded tokens with their expanded locations. getTok(tokI).int_data[3] = loc.getRawEncoding(); } }; } // end anonymous namespace static CXChildVisitResult MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, CXClientData client_data) { return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor, parent); } namespace { struct clang_annotateTokens_Data { CXTranslationUnit TU; ASTUnit *CXXUnit; CXToken *Tokens; unsigned NumTokens; CXCursor *Cursors; }; } /// \brief Used by \c annotatePreprocessorTokens. /// \returns true if lexing was finished, false otherwise. static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx, unsigned NumTokens) { if (NextIdx >= NumTokens) return true; ++NextIdx; Lex.LexFromRawLexer(Tok); if (Tok.is(tok::eof)) return true; return false; } static void annotatePreprocessorTokens(CXTranslationUnit TU, SourceRange RegionOfInterest, CXCursor *Cursors, CXToken *Tokens, unsigned NumTokens) { ASTUnit *CXXUnit = cxtu::getASTUnit(TU); Preprocessor &PP = CXXUnit->getPreprocessor(); SourceManager &SourceMgr = CXXUnit->getSourceManager(); std::pair<FileID, unsigned> BeginLocInfo = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin()); std::pair<FileID, unsigned> EndLocInfo = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd()); if (BeginLocInfo.first != EndLocInfo.first) return; StringRef Buffer; bool Invalid = false; Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); if (Buffer.empty() || Invalid) return; Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); Lex.SetCommentRetentionState(true); unsigned NextIdx = 0; // Lex tokens in raw mode until we hit the end of the range, to avoid // entering #includes or expanding macros. while (true) { Token Tok; if (lexNext(Lex, Tok, NextIdx, NumTokens)) break; unsigned TokIdx = NextIdx-1; assert(Tok.getLocation() == SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); reprocess: if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { // We have found a preprocessing directive. Annotate the tokens // appropriately. // // FIXME: Some simple tests here could identify macro definitions and // #undefs, to provide specific cursor kinds for those. SourceLocation BeginLoc = Tok.getLocation(); if (lexNext(Lex, Tok, NextIdx, NumTokens)) break; MacroInfo *MI = nullptr; if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") { if (lexNext(Lex, Tok, NextIdx, NumTokens)) break; if (Tok.is(tok::raw_identifier)) { IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); SourceLocation MappedTokLoc = CXXUnit->mapLocationToPreamble(Tok.getLocation()); MI = getMacroInfo(II, MappedTokLoc, TU); } } bool finished = false; do { if (lexNext(Lex, Tok, NextIdx, NumTokens)) { finished = true; break; } // If we are in a macro definition, check if the token was ever a // macro name and annotate it if that's the case. if (MI) { SourceLocation SaveLoc = Tok.getLocation(); Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); MacroDefinitionRecord *MacroDef = checkForMacroInMacroDefinition(MI, Tok, TU); Tok.setLocation(SaveLoc); if (MacroDef) Cursors[NextIdx - 1] = MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU); } } while (!Tok.isAtStartOfLine()); unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2; assert(TokIdx <= LastIdx); SourceLocation EndLoc = SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); CXCursor Cursor = MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); for (; TokIdx <= LastIdx; ++TokIdx) updateCursorAnnotation(Cursors[TokIdx], Cursor); if (finished) break; goto reprocess; } } } // This gets run a separate thread to avoid stack blowout. static void clang_annotateTokensImpl(void *UserData) { CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU; ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit; CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens; const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens; CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors; CIndexer *CXXIdx = TU->CIdx; if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) setThreadBackgroundPriority(); // Determine the region of interest, which contains all of the tokens. SourceRange RegionOfInterest; RegionOfInterest.setBegin( cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); RegionOfInterest.setEnd( cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[NumTokens-1]))); // Relex the tokens within the source range to look for preprocessing // directives. annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); // If begin location points inside a macro argument, set it to the expansion // location so we can have the full context when annotating semantically. { SourceManager &SM = CXXUnit->getSourceManager(); SourceLocation Loc = SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin()); if (Loc.isMacroID()) RegionOfInterest.setBegin(SM.getExpansionLoc(Loc)); } if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { // Search and mark tokens that are macro argument expansions. MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens, NumTokens); CursorVisitor MacroArgMarker(TU, MarkMacroArgTokensVisitorDelegate, &Visitor, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, RegionOfInterest); MacroArgMarker.visitPreprocessedEntitiesInRegion(); } // Annotate all of the source locations in the region of interest that map to // a specific cursor. AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); // FIXME: We use a ridiculous stack size here because the data-recursion // algorithm uses a large stack frame than the non-data recursive version, // and AnnotationTokensWorker currently transforms the data-recursion // algorithm back into a traditional recursion by explicitly calling // VisitChildren(). We will need to remove this explicit recursive call. W.AnnotateTokens(); // If we ran into any entities that involve context-sensitive keywords, // take another pass through the tokens to mark them as such. if (W.hasContextSensitiveKeywords()) { for (unsigned I = 0; I != NumTokens; ++I) { if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) continue; if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); if (const ObjCPropertyDecl *Property = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { if (Property->getPropertyAttributesAsWritten() != 0 && llvm::StringSwitch<bool>(II->getName()) .Case("readonly", true) .Case("assign", true) .Case("unsafe_unretained", true) .Case("readwrite", true) .Case("retain", true) .Case("copy", true) .Case("nonatomic", true) .Case("atomic", true) .Case("getter", true) .Case("setter", true) .Case("strong", true) .Case("weak", true) .Default(false)) Tokens[I].int_data[0] = CXToken_Keyword; } continue; } if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); if (llvm::StringSwitch<bool>(II->getName()) .Case("in", true) .Case("out", true) .Case("inout", true) .Case("oneway", true) .Case("bycopy", true) .Case("byref", true) .Default(false)) Tokens[I].int_data[0] = CXToken_Keyword; continue; } if (Cursors[I].kind == CXCursor_CXXFinalAttr || Cursors[I].kind == CXCursor_CXXOverrideAttr) { Tokens[I].int_data[0] = CXToken_Keyword; continue; } } } } // extern "C" { // HLSL Change -Don't use c linkage. void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens, unsigned NumTokens, CXCursor *Cursors) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return; } if (NumTokens == 0 || !Tokens || !Cursors) { LOG_FUNC_SECTION { *Log << "<null input>"; } return; } LOG_FUNC_SECTION { *Log << TU << ' '; CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]); *Log << clang_getRange(bloc, eloc); } // Any token we don't specifically annotate will have a NULL cursor. CXCursor C = clang_getNullCursor(); for (unsigned I = 0; I != NumTokens; ++I) Cursors[I] = C; ASTUnit *CXXUnit = cxtu::getASTUnit(TU); if (!CXXUnit) return; ASTUnit::ConcurrencyCheck Check(*CXXUnit); clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors }; llvm::CrashRecoveryContext CRC; if (!RunSafely(CRC, clang_annotateTokensImpl, &data, GetSafetyThreadStackSize() * 2)) { fprintf(stderr, "libclang: crash detected while annotating tokens\n"); } } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Operations for querying linkage of a cursor. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { if (!clang_isDeclaration(cursor.kind)) return CXLinkage_Invalid; const Decl *D = cxcursor::getCursorDecl(cursor); if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) switch (ND->getLinkageInternal()) { case NoLinkage: case VisibleNoLinkage: return CXLinkage_NoLinkage; case InternalLinkage: return CXLinkage_Internal; case UniqueExternalLinkage: return CXLinkage_UniqueExternal; case ExternalLinkage: return CXLinkage_External; }; return CXLinkage_Invalid; } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Operations for querying language of a cursor. //===----------------------------------------------------------------------===// static CXLanguageKind getDeclLanguage(const Decl *D) { if (!D) return CXLanguage_C; switch (D->getKind()) { default: break; case Decl::ImplicitParam: case Decl::ObjCAtDefsField: case Decl::ObjCCategory: case Decl::ObjCCategoryImpl: case Decl::ObjCCompatibleAlias: case Decl::ObjCImplementation: case Decl::ObjCInterface: case Decl::ObjCIvar: case Decl::ObjCMethod: case Decl::ObjCProperty: case Decl::ObjCPropertyImpl: case Decl::ObjCProtocol: case Decl::ObjCTypeParam: return CXLanguage_ObjC; case Decl::CXXConstructor: case Decl::CXXConversion: case Decl::CXXDestructor: case Decl::CXXMethod: case Decl::CXXRecord: case Decl::ClassTemplate: case Decl::ClassTemplatePartialSpecialization: case Decl::ClassTemplateSpecialization: case Decl::Friend: case Decl::FriendTemplate: case Decl::FunctionTemplate: case Decl::LinkageSpec: case Decl::Namespace: case Decl::NamespaceAlias: case Decl::NonTypeTemplateParm: case Decl::StaticAssert: case Decl::TemplateTemplateParm: case Decl::TemplateTypeParm: case Decl::UnresolvedUsingTypename: case Decl::UnresolvedUsingValue: case Decl::Using: case Decl::UsingDirective: case Decl::UsingShadow: return CXLanguage_CPlusPlus; } return CXLanguage_C; } // extern "C" { // HLSL Change -Don't use c linkage. static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) { if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) return CXAvailability_Available; switch (D->getAvailability()) { case AR_Available: case AR_NotYetIntroduced: if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) return getCursorAvailabilityForDecl( cast<Decl>(EnumConst->getDeclContext())); return CXAvailability_Available; case AR_Deprecated: return CXAvailability_Deprecated; case AR_Unavailable: return CXAvailability_NotAvailable; } llvm_unreachable("Unknown availability kind!"); } enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { if (clang_isDeclaration(cursor.kind)) if (const Decl *D = cxcursor::getCursorDecl(cursor)) return getCursorAvailabilityForDecl(D); return CXAvailability_Available; } static CXVersion convertVersion(VersionTuple In) { CXVersion Out = { -1, -1, -1 }; if (In.empty()) return Out; Out.Major = In.getMajor(); Optional<unsigned> Minor = In.getMinor(); if (Minor.hasValue()) Out.Minor = *Minor; else return Out; Optional<unsigned> Subminor = In.getSubminor(); if (Subminor.hasValue()) Out.Subminor = *Subminor; return Out; } static int getCursorPlatformAvailabilityForDecl(const Decl *D, int *always_deprecated, CXString *deprecated_message, int *always_unavailable, CXString *unavailable_message, CXPlatformAvailability *availability, int availability_size) { bool HadAvailAttr = false; int N = 0; for (auto A : D->attrs()) { if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) { HadAvailAttr = true; if (always_deprecated) *always_deprecated = 1; if (deprecated_message) { clang_disposeString(*deprecated_message); *deprecated_message = cxstring::createDup(Deprecated->getMessage()); } continue; } if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) { HadAvailAttr = true; if (always_unavailable) *always_unavailable = 1; if (unavailable_message) { clang_disposeString(*unavailable_message); *unavailable_message = cxstring::createDup(Unavailable->getMessage()); } continue; } if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) { HadAvailAttr = true; if (N < availability_size) { availability[N].Platform = cxstring::createDup(Avail->getPlatform()->getName()); availability[N].Introduced = convertVersion(Avail->getIntroduced()); availability[N].Deprecated = convertVersion(Avail->getDeprecated()); availability[N].Obsoleted = convertVersion(Avail->getObsoleted()); availability[N].Unavailable = Avail->getUnavailable(); availability[N].Message = cxstring::createDup(Avail->getMessage()); } ++N; } } if (!HadAvailAttr) if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) return getCursorPlatformAvailabilityForDecl( cast<Decl>(EnumConst->getDeclContext()), always_deprecated, deprecated_message, always_unavailable, unavailable_message, availability, availability_size); return N; } int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, CXString *deprecated_message, int *always_unavailable, CXString *unavailable_message, CXPlatformAvailability *availability, int availability_size) { if (always_deprecated) *always_deprecated = 0; if (deprecated_message) *deprecated_message = cxstring::createEmpty(); if (always_unavailable) *always_unavailable = 0; if (unavailable_message) *unavailable_message = cxstring::createEmpty(); if (!clang_isDeclaration(cursor.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(cursor); if (!D) return 0; return getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message, always_unavailable, unavailable_message, availability, availability_size); } void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { clang_disposeString(availability->Platform); clang_disposeString(availability->Message); } CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { if (clang_isDeclaration(cursor.kind)) return getDeclLanguage(cxcursor::getCursorDecl(cursor)); return CXLanguage_Invalid; } /// \brief If the given cursor is the "templated" declaration /// descibing a class or function template, return the class or /// function template. static const Decl *maybeGetTemplateCursor(const Decl *D) { if (!D) return nullptr; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) return FunTmpl; if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) return ClassTmpl; return D; } enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) { StorageClass sc = SC_None; const Decl *D = getCursorDecl(C); if (D) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { sc = FD->getStorageClass(); } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { sc = VD->getStorageClass(); } else { return CX_SC_Invalid; } } else { return CX_SC_Invalid; } switch (sc) { case SC_None: return CX_SC_None; case SC_Extern: return CX_SC_Extern; case SC_Static: return CX_SC_Static; case SC_PrivateExtern: return CX_SC_PrivateExtern; case SC_OpenCLWorkGroupLocal: return CX_SC_OpenCLWorkGroupLocal; case SC_Auto: return CX_SC_Auto; case SC_Register: return CX_SC_Register; } llvm_unreachable("Unhandled storage class!"); } CXCursor clang_getCursorSemanticParent(CXCursor cursor) { if (clang_isDeclaration(cursor.kind)) { if (const Decl *D = getCursorDecl(cursor)) { const DeclContext *DC = D->getDeclContext(); if (!DC) return clang_getNullCursor(); return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), getCursorTU(cursor)); } } if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { if (const Decl *D = getCursorDecl(cursor)) return MakeCXCursor(D, getCursorTU(cursor)); } return clang_getNullCursor(); } CXCursor clang_getCursorLexicalParent(CXCursor cursor) { if (clang_isDeclaration(cursor.kind)) { if (const Decl *D = getCursorDecl(cursor)) { const DeclContext *DC = D->getLexicalDeclContext(); if (!DC) return clang_getNullCursor(); return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), getCursorTU(cursor)); } } // FIXME: Note that we can't easily compute the lexical context of a // statement or expression, so we return nothing. return clang_getNullCursor(); } CXFile clang_getIncludedFile(CXCursor cursor) { if (cursor.kind != CXCursor_InclusionDirective) return nullptr; const InclusionDirective *ID = getCursorInclusionDirective(cursor); return const_cast<FileEntry *>(ID->getFile()); } unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) { if (C.kind != CXCursor_ObjCPropertyDecl) return CXObjCPropertyAttr_noattr; unsigned Result = CXObjCPropertyAttr_noattr; const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); ObjCPropertyDecl::PropertyAttributeKind Attr = PD->getPropertyAttributesAsWritten(); #define SET_CXOBJCPROP_ATTR(A) \ if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \ Result |= CXObjCPropertyAttr_##A SET_CXOBJCPROP_ATTR(readonly); SET_CXOBJCPROP_ATTR(getter); SET_CXOBJCPROP_ATTR(assign); SET_CXOBJCPROP_ATTR(readwrite); SET_CXOBJCPROP_ATTR(retain); SET_CXOBJCPROP_ATTR(copy); SET_CXOBJCPROP_ATTR(nonatomic); SET_CXOBJCPROP_ATTR(setter); SET_CXOBJCPROP_ATTR(atomic); SET_CXOBJCPROP_ATTR(weak); SET_CXOBJCPROP_ATTR(strong); SET_CXOBJCPROP_ATTR(unsafe_unretained); #undef SET_CXOBJCPROP_ATTR return Result; } unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) { if (!clang_isDeclaration(C.kind)) return CXObjCDeclQualifier_None; Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None; const Decl *D = getCursorDecl(C); if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) QT = MD->getObjCDeclQualifier(); else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) QT = PD->getObjCDeclQualifier(); if (QT == Decl::OBJC_TQ_None) return CXObjCDeclQualifier_None; unsigned Result = CXObjCDeclQualifier_None; if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In; if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout; if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out; if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy; if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref; if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway; return Result; } unsigned clang_Cursor_isObjCOptional(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = getCursorDecl(C); if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional; if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) return MD->getImplementationControl() == ObjCMethodDecl::Optional; return 0; } unsigned clang_Cursor_isVariadic(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = getCursorDecl(C); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) return FD->isVariadic(); if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) return MD->isVariadic(); return 0; } CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { if (!clang_isDeclaration(C.kind)) return clang_getNullRange(); const Decl *D = getCursorDecl(C); ASTContext &Context = getCursorContext(C); const RawComment *RC = Context.getRawCommentForAnyRedecl(D); if (!RC) return clang_getNullRange(); return cxloc::translateSourceRange(Context, RC->getSourceRange()); } CXString clang_Cursor_getRawCommentText(CXCursor C) { if (!clang_isDeclaration(C.kind)) return cxstring::createNull(); const Decl *D = getCursorDecl(C); ASTContext &Context = getCursorContext(C); const RawComment *RC = Context.getRawCommentForAnyRedecl(D); StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) : StringRef(); // Don't duplicate the string because RawText points directly into source // code. return cxstring::createRef(RawText); } CXString clang_Cursor_getBriefCommentText(CXCursor C) { if (!clang_isDeclaration(C.kind)) return cxstring::createNull(); const Decl *D = getCursorDecl(C); const ASTContext &Context = getCursorContext(C); const RawComment *RC = Context.getRawCommentForAnyRedecl(D); if (RC) { StringRef BriefText = RC->getBriefText(Context); // Don't duplicate the string because RawComment ensures that this memory // will not go away. return cxstring::createRef(BriefText); } return cxstring::createNull(); } CXModule clang_Cursor_getModule(CXCursor C) { if (C.kind == CXCursor_ModuleImportDecl) { if (const ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) return ImportD->getImportedModule(); } return nullptr; } CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return nullptr; } if (!File) return nullptr; FileEntry *FE = static_cast<FileEntry *>(File); ASTUnit &Unit = *cxtu::getASTUnit(TU); HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo(); ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE); return Header.getModule(); } CXFile clang_Module_getASTFile(CXModule CXMod) { if (!CXMod) return nullptr; Module *Mod = static_cast<Module*>(CXMod); return const_cast<FileEntry *>(Mod->getASTFile()); } CXModule clang_Module_getParent(CXModule CXMod) { if (!CXMod) return nullptr; Module *Mod = static_cast<Module*>(CXMod); return Mod->Parent; } CXString clang_Module_getName(CXModule CXMod) { if (!CXMod) return cxstring::createEmpty(); Module *Mod = static_cast<Module*>(CXMod); return cxstring::createDup(Mod->Name); } CXString clang_Module_getFullName(CXModule CXMod) { if (!CXMod) return cxstring::createEmpty(); Module *Mod = static_cast<Module*>(CXMod); return cxstring::createDup(Mod->getFullModuleName()); } int clang_Module_isSystem(CXModule CXMod) { if (!CXMod) return 0; Module *Mod = static_cast<Module*>(CXMod); return Mod->IsSystem; } unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU, CXModule CXMod) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return 0; } if (!CXMod) return 0; Module *Mod = static_cast<Module*>(CXMod); FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); return TopHeaders.size(); } CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod, unsigned Index) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return nullptr; } if (!CXMod) return nullptr; Module *Mod = static_cast<Module*>(CXMod); FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); if (Index < TopHeaders.size()) return const_cast<FileEntry *>(TopHeaders[Index]); return nullptr; } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // C++ AST instrospection. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. unsigned clang_CXXMethod_isPureVirtual(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(C); const CXXMethodDecl *Method = D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0; } unsigned clang_CXXMethod_isConst(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(C); const CXXMethodDecl *Method = D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0; } unsigned clang_CXXMethod_isStatic(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(C); const CXXMethodDecl *Method = D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; return (Method && Method->isStatic()) ? 1 : 0; } unsigned clang_CXXMethod_isVirtual(CXCursor C) { if (!clang_isDeclaration(C.kind)) return 0; const Decl *D = cxcursor::getCursorDecl(C); const CXXMethodDecl *Method = D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; return (Method && Method->isVirtual()) ? 1 : 0; } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Attribute introspection. //===----------------------------------------------------------------------===// // extern "C" { // HLSL Change -Don't use c linkage. CXType clang_getIBOutletCollectionType(CXCursor C) { if (C.kind != CXCursor_IBOutletCollectionAttr) return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); const IBOutletCollectionAttr *A = cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); } // } // end: extern "C" // HLSL Change -Don't use c linkage. //===----------------------------------------------------------------------===// // Inspecting memory usage. //===----------------------------------------------------------------------===// typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, enum CXTUResourceUsageKind k, unsigned long amount) { CXTUResourceUsageEntry entry = { k, amount }; entries.push_back(entry); } // extern "C" { // HLSL Change -Don't use c linkage. const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { const char *str = ""; switch (kind) { case CXTUResourceUsage_AST: str = "ASTContext: expressions, declarations, and types"; break; case CXTUResourceUsage_Identifiers: str = "ASTContext: identifiers"; break; case CXTUResourceUsage_Selectors: str = "ASTContext: selectors"; break; case CXTUResourceUsage_GlobalCompletionResults: str = "Code completion: cached global results"; break; case CXTUResourceUsage_SourceManagerContentCache: str = "SourceManager: content cache allocator"; break; case CXTUResourceUsage_AST_SideTables: str = "ASTContext: side tables"; break; case CXTUResourceUsage_SourceManager_Membuffer_Malloc: str = "SourceManager: malloc'ed memory buffers"; break; case CXTUResourceUsage_SourceManager_Membuffer_MMap: str = "SourceManager: mmap'ed memory buffers"; break; case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: str = "ExternalASTSource: malloc'ed memory buffers"; break; case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: str = "ExternalASTSource: mmap'ed memory buffers"; break; case CXTUResourceUsage_Preprocessor: str = "Preprocessor: malloc'ed memory"; break; case CXTUResourceUsage_PreprocessingRecord: str = "Preprocessor: PreprocessingRecord"; break; case CXTUResourceUsage_SourceManager_DataStructures: str = "SourceManager: data structures and tables"; break; case CXTUResourceUsage_Preprocessor_HeaderSearch: str = "Preprocessor: header search tables"; break; } return str; } CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr }; return usage; } ASTUnit *astUnit = cxtu::getASTUnit(TU); std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries()); ASTContext &astContext = astUnit->getASTContext(); // How much memory is used by AST nodes and types? createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, (unsigned long) astContext.getASTAllocatedMemory()); // How much memory is used by identifiers? createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); // How much memory is used for selectors? createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, (unsigned long) astContext.Selectors.getTotalMemory()); // How much memory is used by ASTContext's side tables? createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables, (unsigned long) astContext.getSideTableAllocatedMemory()); // How much memory is used for caching global code completion results? unsigned long completionBytes = 0; if (GlobalCodeCompletionAllocator *completionAllocator = astUnit->getCachedCompletionAllocator().get()) { completionBytes = completionAllocator->getTotalMemory(); } createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes); // How much memory is being used by SourceManager's content cache? createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_SourceManagerContentCache, (unsigned long) astContext.getSourceManager().getContentCacheSize()); // How much memory is being used by the MemoryBuffer's in SourceManager? const SourceManager::MemoryBufferSizes &srcBufs = astUnit->getSourceManager().getMemoryBufferSizes(); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_SourceManager_Membuffer_Malloc, (unsigned long) srcBufs.malloc_bytes); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_SourceManager_Membuffer_MMap, (unsigned long) srcBufs.mmap_bytes); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_SourceManager_DataStructures, (unsigned long) astContext.getSourceManager() .getDataStructureSizes()); // How much memory is being used by the ExternalASTSource? if (ExternalASTSource *esrc = astContext.getExternalSource()) { const ExternalASTSource::MemoryBufferSizes &sizes = esrc->getMemoryBufferSizes(); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, (unsigned long) sizes.malloc_bytes); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, (unsigned long) sizes.mmap_bytes); } // How much memory is being used by the Preprocessor? Preprocessor &pp = astUnit->getPreprocessor(); createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor, pp.getTotalMemory()); if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_PreprocessingRecord, pRec->getTotalMemory()); } createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor_HeaderSearch, pp.getHeaderSearchInfo().getTotalMemory()); CXTUResourceUsage usage = { (void*) entries.get(), (unsigned) entries->size(), !entries->empty() ? &(*entries)[0] : nullptr }; entries.release(); return usage; } void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { if (usage.data) delete (MemUsageEntries*) usage.data; } CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) { CXSourceRangeList *skipped = new CXSourceRangeList; skipped->count = 0; skipped->ranges = nullptr; if (isNotUsableTU(TU)) { LOG_BAD_TU(TU); return skipped; } if (!file) return skipped; ASTUnit *astUnit = cxtu::getASTUnit(TU); PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); if (!ppRec) return skipped; ASTContext &Ctx = astUnit->getASTContext(); SourceManager &sm = Ctx.getSourceManager(); FileEntry *fileEntry = static_cast<FileEntry *>(file); FileID wantedFileID = sm.translateFile(fileEntry); const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); std::vector<SourceRange> wantedRanges; for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end(); i != ei; ++i) { if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID) wantedRanges.push_back(*i); } skipped->count = wantedRanges.size(); skipped->ranges = new CXSourceRange[skipped->count]; for (unsigned i = 0, ei = skipped->count; i != ei; ++i) skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]); return skipped; } void clang_disposeSourceRangeList(CXSourceRangeList *ranges) { if (ranges) { delete[] ranges->ranges; delete ranges; } } //} // end extern "C" // HLSL Change -Don't use c linkage. void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); for (unsigned I = 0; I != Usage.numEntries; ++I) fprintf(stderr, " %s: %lu\n", clang_getTUResourceUsageName(Usage.entries[I].kind), Usage.entries[I].amount); clang_disposeCXTUResourceUsage(Usage); } //===----------------------------------------------------------------------===// // Misc. utility functions. //===----------------------------------------------------------------------===// /// Default to using an 8 MB stack size on "safety" threads. static unsigned SafetyStackThreadSize = 8 << 20; namespace clang { bool RunSafely(llvm::CrashRecoveryContext &CRC, void (*Fn)(void*), void *UserData, unsigned Size) { if (!Size) Size = GetSafetyThreadStackSize(); if (Size) return CRC.RunSafelyOnThread(Fn, UserData, Size); return CRC.RunSafely(Fn, UserData); } unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; } void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; } } void clang::setThreadBackgroundPriority() { if (getenv("LIBCLANG_BGPRIO_DISABLE")) return; #ifdef USE_DARWIN_THREADS setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); #endif } void cxindex::printDiagsToStderr(ASTUnit *Unit) { if (!Unit) return; for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), DEnd = Unit->stored_diag_end(); D != DEnd; ++D) { CXStoredDiagnostic Diag(*D, Unit->getLangOpts()); CXString Msg = clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions()); fprintf(stderr, "%s\n", clang_getCString(Msg)); clang_disposeString(Msg); } #ifdef LLVM_ON_WIN32 // On Windows, force a flush, since there may be multiple copies of // stderr and stdout in the file system, all with different buffers // but writing to the same device. fflush(stderr); #endif } MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, SourceLocation MacroDefLoc, CXTranslationUnit TU){ if (MacroDefLoc.isInvalid() || !TU) return nullptr; if (!II.hadMacroDefinition()) return nullptr; ASTUnit *Unit = cxtu::getASTUnit(TU); Preprocessor &PP = Unit->getPreprocessor(); MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II); if (MD) { for (MacroDirective::DefInfo Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) { if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc()) return Def.getMacroInfo(); } } return nullptr; } const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef, CXTranslationUnit TU) { if (!MacroDef || !TU) return nullptr; const IdentifierInfo *II = MacroDef->getName(); if (!II) return nullptr; return getMacroInfo(*II, MacroDef->getLocation(), TU); } MacroDefinitionRecord * cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, CXTranslationUnit TU) { if (!MI || !TU) return nullptr; if (Tok.isNot(tok::raw_identifier)) return nullptr; if (MI->getNumTokens() == 0) return nullptr; SourceRange DefRange(MI->getReplacementToken(0).getLocation(), MI->getDefinitionEndLoc()); ASTUnit *Unit = cxtu::getASTUnit(TU); // Check that the token is inside the definition and not its argument list. SourceManager &SM = Unit->getSourceManager(); if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) return nullptr; if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) return nullptr; Preprocessor &PP = Unit->getPreprocessor(); PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); if (!PPRec) return nullptr; IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); if (!II.hadMacroDefinition()) return nullptr; // Check that the identifier is not one of the macro arguments. if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end()) return nullptr; MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II); if (!InnerMD) return nullptr; return PPRec->findMacroDefinition(InnerMD->getMacroInfo()); } MacroDefinitionRecord * cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, CXTranslationUnit TU) { if (Loc.isInvalid() || !MI || !TU) return nullptr; if (MI->getNumTokens() == 0) return nullptr; ASTUnit *Unit = cxtu::getASTUnit(TU); Preprocessor &PP = Unit->getPreprocessor(); if (!PP.getPreprocessingRecord()) return nullptr; Loc = Unit->getSourceManager().getSpellingLoc(Loc); Token Tok; if (PP.getRawToken(Loc, Tok)) return nullptr; return checkForMacroInMacroDefinition(MI, Tok, TU); } // extern "C" { // HLSL Change -Don't use c linkage. CXString clang_getClangVersion() { return cxstring::createDup(getClangFullVersion()); } // } // end: extern "C" // HLSL Change -Don't use c linkage. Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { if (TU) { if (ASTUnit *Unit = cxtu::getASTUnit(TU)) { LogOS << '<' << Unit->getMainFileName() << '>'; if (Unit->isMainFileAST()) LogOS << " (" << Unit->getASTFileName() << ')'; return *this; } } else { LogOS << "<NULL TU>"; } return *this; } Logger &cxindex::Logger::operator<<(const FileEntry *FE) { *this << FE->getName(); return *this; } Logger &cxindex::Logger::operator<<(CXCursor cursor) { CXString cursorName = clang_getCursorDisplayName(cursor); *this << cursorName << "@" << clang_getCursorLocation(cursor); clang_disposeString(cursorName); return *this; } Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { CXFile File; unsigned Line, Column; clang_getFileLocation(Loc, &File, &Line, &Column, nullptr); CXString FileName = clang_getFileName(File); *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); clang_disposeString(FileName); return *this; } Logger &cxindex::Logger::operator<<(CXSourceRange range) { CXSourceLocation BLoc = clang_getRangeStart(range); CXSourceLocation ELoc = clang_getRangeEnd(range); CXFile BFile; unsigned BLine, BColumn; clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr); CXFile EFile; unsigned ELine, EColumn; clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr); CXString BFileName = clang_getFileName(BFile); if (BFile == EFile) { *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), BLine, BColumn, ELine, EColumn); } else { CXString EFileName = clang_getFileName(EFile); *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine, BColumn) << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine, EColumn); clang_disposeString(EFileName); } clang_disposeString(BFileName); return *this; } Logger &cxindex::Logger::operator<<(CXString Str) { *this << clang_getCString(Str); return *this; } Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { LogOS << Fmt; return *this; } static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex; cxindex::Logger::~Logger() { LogOS.flush(); llvm::sys::ScopedLock L(*LoggingMutex); static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); raw_ostream &OS = llvm::errs(); OS << "[libclang:" << Name << ':'; #ifdef USE_DARWIN_THREADS // TODO: Portability. mach_port_t tid = pthread_mach_thread_np(pthread_self()); OS << tid << ':'; #endif llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); OS << Msg << '\n'; if (Trace) { // llvm::sys::PrintStackTrace(OS); // HLSL Change - disable this OS << "--------------------------------------------------\n"; } } // HLSL Change Starts unsigned clang_ms_countSkippedRanges(CXTranslationUnit TU, CXFile file) { unsigned result = 0; ASTUnit *astUnit = cxtu::getASTUnit(TU); PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); if (ppRec == nullptr) { return 0; } ASTContext &Ctx = astUnit->getASTContext(); SourceManager &sm = Ctx.getSourceManager(); FileEntry *fileEntry = static_cast<FileEntry *>(file); FileID wantedFileID = sm.translateFile(fileEntry); const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end(); i != ei; ++i) { if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID) { ++result; } } return result; } void clang_ms_getSkippedRanges(CXTranslationUnit TU, CXFile file, CXSourceRange* ranges, unsigned len) { if (len == 0) return; assert(ranges != nullptr); ASTUnit *astUnit = cxtu::getASTUnit(TU); PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); assert(ppRec != nullptr); ASTContext &Ctx = astUnit->getASTContext(); SourceManager &sm = Ctx.getSourceManager(); FileEntry *fileEntry = static_cast<FileEntry *>(file); FileID wantedFileID = sm.translateFile(fileEntry); const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end(); i != ei; ++i) { SourceLocation begin = i->getBegin(); SourceLocation end = i->getEnd(); if (sm.getFileID(begin) == wantedFileID || sm.getFileID(end) == wantedFileID) { // preprocessor token (if,else,endif), so it's adjusted to the end of that line (so the line // gets colorized). The end position given is at the end of the closing preprocessor token, so // it's adjusted to the beginning of the line (so that line is also colorized). unsigned beginOffset = sm.getFileOffset(begin); unsigned endOffset = sm.getFileOffset(end); // Adjust the end position to the beginning of its line (column 1). unsigned endLine = sm.getLineNumber(wantedFileID, endOffset); end = sm.translateLineCol(wantedFileID, endLine, 1); // Adjust the start position to the end of its line by scanning the buffer. unsigned beginLine = sm.getLineNumber(wantedFileID, beginOffset); unsigned beginCol = sm.getColumnNumber(wantedFileID, beginOffset); // Move beginCol forward until we see a '\n' or the end of the file. const llvm::MemoryBuffer* memBuffer = sm.getBuffer(wantedFileID); const char* buffer = memBuffer->getBufferStart() + (beginOffset + (beginCol-1)); const char* bufferEnd = memBuffer->getBufferEnd(); while (buffer < bufferEnd && *buffer != '\n') { ++buffer; ++beginCol; } begin = sm.translateLineCol(wantedFileID, beginLine, beginCol); // cxloc::translateSourceRange extends the end of a range, which typically points to the start // of the last token, to the end of that last token for external consumption. However that // behavior does not apply in this line-based case, so construct the range directly. CXSourceRange Result = { { &sm, &astUnit->getASTContext().getLangOpts() }, begin.getRawEncoding(), end.getRawEncoding() }; *ranges = Result; --len, ranges++; if (len == 0) return; } } assert(len == 0); } // HLSL Change Ends
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CXComment.h
//===- CXComment.h - Routines for manipulating CXComments -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines routines for manipulating CXComments. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_LIBCLANG_CXCOMMENT_H #define LLVM_CLANG_TOOLS_LIBCLANG_CXCOMMENT_H #include "CXTranslationUnit.h" #include "clang-c/Documentation.h" #include "clang-c/Index.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Comment.h" #include "clang/Frontend/ASTUnit.h" namespace clang { namespace comments { class CommandTraits; } namespace cxcomment { static inline CXComment createCXComment(const comments::Comment *C, CXTranslationUnit TU) { CXComment Result; Result.ASTNode = C; Result.TranslationUnit = TU; return Result; } static inline const comments::Comment *getASTNode(CXComment CXC) { return static_cast<const comments::Comment *>(CXC.ASTNode); } template<typename T> static inline const T *getASTNodeAs(CXComment CXC) { const comments::Comment *C = getASTNode(CXC); if (!C) return nullptr; return dyn_cast<T>(C); } static inline ASTContext &getASTContext(CXComment CXC) { return cxtu::getASTUnit(CXC.TranslationUnit)->getASTContext(); } static inline comments::CommandTraits &getCommandTraits(CXComment CXC) { return getASTContext(CXC).getCommentCommandTraits(); } } // end namespace cxcomment } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/libclang/CIndexCXX.cpp
//===- CIndexCXX.cpp - Clang-C Source Indexing Library --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the libclang support for C++ cursors. // //===----------------------------------------------------------------------===// #include "CIndexer.h" #include "CXCursor.h" #include "CXType.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" using namespace clang; using namespace clang::cxcursor; // extern "C" { // HLSL Change -Don't use c linkage. unsigned clang_isVirtualBase(CXCursor C) { if (C.kind != CXCursor_CXXBaseSpecifier) return 0; const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); return B->isVirtual(); } enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor C) { AccessSpecifier spec = AS_none; if (C.kind == CXCursor_CXXAccessSpecifier || clang_isDeclaration(C.kind)) spec = getCursorDecl(C)->getAccess(); else if (C.kind == CXCursor_CXXBaseSpecifier) spec = getCursorCXXBaseSpecifier(C)->getAccessSpecifier(); else return CX_CXXInvalidAccessSpecifier; switch (spec) { case AS_public: return CX_CXXPublic; case AS_protected: return CX_CXXProtected; case AS_private: return CX_CXXPrivate; case AS_none: return CX_CXXInvalidAccessSpecifier; } llvm_unreachable("Invalid AccessSpecifier!"); } enum CXCursorKind clang_getTemplateCursorKind(CXCursor C) { using namespace clang::cxcursor; switch (C.kind) { case CXCursor_ClassTemplate: case CXCursor_FunctionTemplate: if (const TemplateDecl *Template = dyn_cast_or_null<TemplateDecl>(getCursorDecl(C))) return MakeCXCursor(Template->getTemplatedDecl(), getCursorTU(C)).kind; break; case CXCursor_ClassTemplatePartialSpecialization: if (const ClassTemplateSpecializationDecl *PartialSpec = dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>( getCursorDecl(C))) { switch (PartialSpec->getTagKind()) { case TTK_Interface: case TTK_Struct: return CXCursor_StructDecl; case TTK_Class: return CXCursor_ClassDecl; case TTK_Union: return CXCursor_UnionDecl; case TTK_Enum: return CXCursor_NoDeclFound; } } break; default: break; } return CXCursor_NoDeclFound; } CXCursor clang_getSpecializedCursorTemplate(CXCursor C) { if (!clang_isDeclaration(C.kind)) return clang_getNullCursor(); const Decl *D = getCursorDecl(C); if (!D) return clang_getNullCursor(); Decl *Template = nullptr; if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) { if (const ClassTemplatePartialSpecializationDecl *PartialSpec = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) Template = PartialSpec->getSpecializedTemplate(); else if (const ClassTemplateSpecializationDecl *ClassSpec = dyn_cast<ClassTemplateSpecializationDecl>(CXXRecord)) { llvm::PointerUnion<ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl *> Result = ClassSpec->getSpecializedTemplateOrPartial(); if (Result.is<ClassTemplateDecl *>()) Template = Result.get<ClassTemplateDecl *>(); else Template = Result.get<ClassTemplatePartialSpecializationDecl *>(); } else Template = CXXRecord->getInstantiatedFromMemberClass(); } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { Template = Function->getPrimaryTemplate(); if (!Template) Template = Function->getInstantiatedFromMemberFunction(); } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { if (Var->isStaticDataMember()) Template = Var->getInstantiatedFromStaticDataMember(); } else if (const RedeclarableTemplateDecl *Tmpl = dyn_cast<RedeclarableTemplateDecl>(D)) Template = Tmpl->getInstantiatedFromMemberTemplate(); if (!Template) return clang_getNullCursor(); return MakeCXCursor(Template, getCursorTU(C)); } // } // end extern "C" // HLSL Change -Don't use c linkage.
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/clang-fuzzer/CMakeLists.txt
if( LLVM_USE_SANITIZE_COVERAGE ) set(LLVM_LINK_COMPONENTS support) add_clang_executable(clang-fuzzer EXCLUDE_FROM_ALL ClangFuzzer.cpp ) target_link_libraries(clang-fuzzer ${CLANG_FORMAT_LIB_DEPS} clangAST clangBasic clangDriver clangFrontend clangRewriteFrontend clangStaticAnalyzerFrontend clangTooling LLVMFuzzer ) endif()
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/clang-fuzzer/ClangFuzzer.cpp
//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a function that runs Clang on a single /// input. This function is then linked into the Fuzzer library. /// //===----------------------------------------------------------------------===// #include "clang/Tooling/Tooling.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Option/Option.h" using namespace clang; extern "C" void LLVMFuzzerTestOneInput(uint8_t *data, size_t size) { std::string s((const char *)data, size); llvm::opt::ArgStringList CC1Args; CC1Args.push_back("-cc1"); CC1Args.push_back("./test.cc"); llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions())); IgnoringDiagConsumer Diags; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &Diags, false); std::unique_ptr<clang::CompilerInvocation> Invocation( tooling::newInvocation(&Diagnostics, CC1Args)); std::unique_ptr<llvm::MemoryBuffer> Input = llvm::MemoryBuffer::getMemBuffer(s); Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release()); std::unique_ptr<tooling::ToolAction> action( tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>()); std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<RawPCHContainerOperations>(); action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps, &Diags); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/cc1as_main.cpp
//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the entry point to the clang -cc1as functionality, which implements // the direct interface to the LLVM MC based assembler. // //===----------------------------------------------------------------------===// #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Frontend/Utils.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/MCAsmParser.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCTargetAsmParser.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include <memory> #include <system_error> using namespace clang; using namespace clang::driver; using namespace clang::driver::options; using namespace llvm; using namespace llvm::opt; namespace { /// \brief Helper class for representing a single invocation of the assembler. struct AssemblerInvocation { /// @name Target Options /// @{ /// The name of the target triple to assemble for. std::string Triple; /// If given, the name of the target CPU to determine which instructions /// are legal. std::string CPU; /// The list of target specific features to enable or disable -- this should /// be a list of strings starting with '+' or '-'. std::vector<std::string> Features; /// @} /// @name Language Options /// @{ std::vector<std::string> IncludePaths; unsigned NoInitialTextSection : 1; unsigned SaveTemporaryLabels : 1; unsigned GenDwarfForAssembly : 1; unsigned CompressDebugSections : 1; unsigned DwarfVersion; std::string DwarfDebugFlags; std::string DwarfDebugProducer; std::string DebugCompilationDir; std::string MainFileName; /// @} /// @name Frontend Options /// @{ std::string InputFile; std::vector<std::string> LLVMArgs; std::string OutputPath; enum FileType { FT_Asm, ///< Assembly (.s) output, transliterate mode. FT_Null, ///< No output, for timing purposes. FT_Obj ///< Object file output. }; FileType OutputType; unsigned ShowHelp : 1; unsigned ShowVersion : 1; /// @} /// @name Transliterate Options /// @{ unsigned OutputAsmVariant; unsigned ShowEncoding : 1; unsigned ShowInst : 1; /// @} /// @name Assembler Options /// @{ unsigned RelaxAll : 1; unsigned NoExecStack : 1; unsigned FatalWarnings : 1; /// @} public: AssemblerInvocation() { Triple = ""; NoInitialTextSection = 0; InputFile = "-"; OutputPath = "-"; OutputType = FT_Asm; OutputAsmVariant = 0; ShowInst = 0; ShowEncoding = 0; RelaxAll = 0; NoExecStack = 0; FatalWarnings = 0; DwarfVersion = 3; } static bool CreateFromArgs(AssemblerInvocation &Res, ArrayRef<const char *> Argv, DiagnosticsEngine &Diags); }; } bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts, ArrayRef<const char *> Argv, DiagnosticsEngine &Diags) { bool Success = true; // Parse the arguments. std::unique_ptr<OptTable> OptTbl(createDriverOptTable()); const unsigned IncludedFlagsBitmask = options::CC1AsOption; unsigned MissingArgIndex, MissingArgCount; InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount, IncludedFlagsBitmask); // Check for missing argument error. if (MissingArgCount) { Diags.Report(diag::err_drv_missing_argument) << Args.getArgString(MissingArgIndex) << MissingArgCount; Success = false; } // Issue errors on unknown arguments. for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args); Success = false; } // Construct the invocation. // Target Options Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple)); Opts.CPU = Args.getLastArgValue(OPT_target_cpu); Opts.Features = Args.getAllArgValues(OPT_target_feature); // Use the default target triple if unspecified. if (Opts.Triple.empty()) Opts.Triple = llvm::sys::getDefaultTargetTriple(); // Language Options Opts.IncludePaths = Args.getAllArgValues(OPT_I); Opts.NoInitialTextSection = Args.hasArg(OPT_n); Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels); Opts.GenDwarfForAssembly = Args.hasArg(OPT_g_Flag); Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections); if (Args.hasArg(OPT_gdwarf_2)) Opts.DwarfVersion = 2; if (Args.hasArg(OPT_gdwarf_3)) Opts.DwarfVersion = 3; if (Args.hasArg(OPT_gdwarf_4)) Opts.DwarfVersion = 4; Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags); Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer); Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir); Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name); // Frontend Options if (Args.hasArg(OPT_INPUT)) { bool First = true; for (arg_iterator it = Args.filtered_begin(OPT_INPUT), ie = Args.filtered_end(); it != ie; ++it, First = false) { const Arg *A = it; if (First) Opts.InputFile = A->getValue(); else { Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args); Success = false; } } } Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); Opts.OutputPath = Args.getLastArgValue(OPT_o); if (Arg *A = Args.getLastArg(OPT_filetype)) { StringRef Name = A->getValue(); unsigned OutputType = StringSwitch<unsigned>(Name) .Case("asm", FT_Asm) .Case("null", FT_Null) .Case("obj", FT_Obj) .Default(~0U); if (OutputType == ~0U) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else Opts.OutputType = FileType(OutputType); } Opts.ShowHelp = Args.hasArg(OPT_help); Opts.ShowVersion = Args.hasArg(OPT_version); // Transliterate Options Opts.OutputAsmVariant = getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags); Opts.ShowEncoding = Args.hasArg(OPT_show_encoding); Opts.ShowInst = Args.hasArg(OPT_show_inst); // Assemble Options Opts.RelaxAll = Args.hasArg(OPT_mrelax_all); Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); return Success; } static std::unique_ptr<raw_fd_ostream> getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags, bool Binary) { if (Opts.OutputPath.empty()) Opts.OutputPath = "-"; // Make sure that the Out file gets unlinked from the disk if we get a // SIGINT. if (Opts.OutputPath != "-") sys::RemoveFileOnSignal(Opts.OutputPath); std::error_code EC; auto Out = llvm::make_unique<raw_fd_ostream>( Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text)); if (EC) { Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath << EC.message(); return nullptr; } return Out; } static bool ExecuteAssembler(AssemblerInvocation &Opts, DiagnosticsEngine &Diags) { // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error); if (!TheTarget) return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile); if (std::error_code EC = Buffer.getError()) { Error = EC.message(); return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile; } SourceMgr SrcMgr; // Tell SrcMgr about this buffer, which is what the parser will pick up. SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc()); // Record the location of the include directories so that the lexer can find // it later. SrcMgr.setIncludeDirs(Opts.IncludePaths); std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple)); assert(MRI && "Unable to create target register info!"); std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple)); assert(MAI && "Unable to create target asm info!"); // Ensure MCAsmInfo initialization occurs before any use, otherwise sections // may be created with a combination of default and explicit settings. if (Opts.CompressDebugSections) MAI->setCompressDebugSections(true); bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary); if (!FDOS) return true; // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and // MCObjectFileInfo needs a MCContext reference in order to initialize itself. std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo()); MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr); // FIXME: Assembler behavior can change with -static. MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), Reloc::Default, CodeModel::Default, Ctx); if (Opts.SaveTemporaryLabels) Ctx.setAllowTemporaryLabels(false); if (Opts.GenDwarfForAssembly) Ctx.setGenDwarfForAssembly(true); if (!Opts.DwarfDebugFlags.empty()) Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags)); if (!Opts.DwarfDebugProducer.empty()) Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer)); if (!Opts.DebugCompilationDir.empty()) Ctx.setCompilationDir(Opts.DebugCompilationDir); if (!Opts.MainFileName.empty()) Ctx.setMainFileName(StringRef(Opts.MainFileName)); Ctx.setDwarfVersion(Opts.DwarfVersion); // Build up the feature string from the target feature list. std::string FS; if (!Opts.Features.empty()) { FS = Opts.Features[0]; for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i) FS += "," + Opts.Features[i]; } std::unique_ptr<MCStreamer> Str; std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); std::unique_ptr<MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS)); raw_pwrite_stream *Out = FDOS.get(); std::unique_ptr<buffer_ostream> BOS; // FIXME: There is a bit of code duplication with addPassesToEmitFile. if (Opts.OutputType == AssemblerInvocation::FT_Asm) { MCInstPrinter *IP = TheTarget->createMCInstPrinter( llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI); MCCodeEmitter *CE = nullptr; MCAsmBackend *MAB = nullptr; if (Opts.ShowEncoding) { CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU); } auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out); Str.reset(TheTarget->createAsmStreamer( Ctx, std::move(FOut), /*asmverbose*/ true, /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst)); } else if (Opts.OutputType == AssemblerInvocation::FT_Null) { Str.reset(createNullStreamer(Ctx)); } else { assert(Opts.OutputType == AssemblerInvocation::FT_Obj && "Invalid file type!"); if (!FDOS->supportsSeeking()) { BOS = make_unique<buffer_ostream>(*FDOS); Out = BOS.get(); } MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU); Triple T(Opts.Triple); Str.reset(TheTarget->createMCObjectStreamer(T, Ctx, *MAB, *Out, CE, *STI, Opts.RelaxAll, /*DWARFMustBeAtTheEnd*/ true)); Str.get()->InitSections(Opts.NoExecStack); } bool Failed = false; std::unique_ptr<MCAsmParser> Parser( createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI)); // FIXME: init MCTargetOptions from sanitizer flags here. MCTargetOptions Options; std::unique_ptr<MCTargetAsmParser> TAP( TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options)); if (!TAP) Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; if (!Failed) { Parser->setTargetParser(*TAP.get()); Failed = Parser->Run(Opts.NoInitialTextSection); } // Close Streamer first. // It might have a reference to the output stream. Str.reset(); // Close the output stream early. BOS.reset(); FDOS.reset(); // Delete output file if there were errors. if (Failed && Opts.OutputPath != "-") sys::fs::remove(Opts.OutputPath); return Failed; } static void LLVMErrorHandler(void *UserData, const std::string &Message, bool GenCrashDiag) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; // We cannot recover from llvm errors. exit(1); } int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(Argv.size(), Argv.data()); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets and assembly printers/parsers. InitializeAllTargetInfos(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); // Construct our diagnostic client. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(errs(), &*DiagOpts); DiagClient->setPrefix("clang -cc1as"); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); // Set an error handler, so that any LLVM backend diagnostics go through our // error handler. ScopedFatalErrorHandler FatalErrorHandler (LLVMErrorHandler, static_cast<void*>(&Diags)); // Parse the arguments. AssemblerInvocation Asm; if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags)) return 1; if (Asm.ShowHelp) { std::unique_ptr<OptTable> Opts(driver::createDriverOptTable()); Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler", /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0); return 0; } // Honor -version. // // FIXME: Use a better -version message? if (Asm.ShowVersion) { llvm::cl::PrintVersionMessage(); return 0; } // Honor -mllvm. // // FIXME: Remove this, one day. if (!Asm.LLVMArgs.empty()) { unsigned NumArgs = Asm.LLVMArgs.size(); const char **Args = new const char*[NumArgs + 2]; Args[0] = "clang (LLVM option parsing)"; for (unsigned i = 0; i != NumArgs; ++i) Args[i + 1] = Asm.LLVMArgs[i].c_str(); Args[NumArgs + 1] = nullptr; llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args); } // Execute the invocation, unless there were parsing errors. bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags); // If any timers were active but haven't been destroyed yet, print their // results now. TimerGroup::printAll(errs()); return !!Failed; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/Info.plist.in
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>@TOOL_INFO_UTI@</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>@TOOL_INFO_NAME</string> <key>CFBundleShortVersionString</key> <string>@TOOL_INFO_VERSION@</string> <key>CFBundleVersion</key> <string>@TOOL_INFO_BUILD_VERSION@</string> <key>CFBundleSignature</key> <string>????</string> </dict> </plist>
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/driver.cpp
//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the entry point to the clang driver; it is a thin wrapper // for functionality in the Driver clang library. // //===----------------------------------------------------------------------===// #include "clang/Basic/CharInfo.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "clang/Frontend/ChainedDiagnosticConsumer.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/SerializedDiagnosticPrinter.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Frontend/Utils.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Config/llvm-config.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/Option.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Process.h" #include "llvm/Support/Program.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include <memory> #include <system_error> // HLSL Change Starts #include <windows.h> #include "llvm/Support/MSFileSystem.h" // HLSL Change Ends using namespace clang; using namespace clang::driver; using namespace llvm::opt; std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) { if (!CanonicalPrefixes) return Argv0; // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void *P = (void*) (intptr_t) GetExecutablePath; return llvm::sys::fs::getMainExecutable(Argv0, P); } static const char *GetStableCStr(std::set<std::string> &SavedStrings, StringRef S) { return SavedStrings.insert(S).first->c_str(); } /// ApplyQAOverride - Apply a list of edits to the input argument lists. /// /// The input string is a space separate list of edits to perform, /// they are applied in order to the input argument lists. Edits /// should be one of the following forms: /// /// '#': Silence information about the changes to the command line arguments. /// /// '^': Add FOO as a new argument at the beginning of the command line. /// /// '+': Add FOO as a new argument at the end of the command line. /// /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command /// line. /// /// 'xOPTION': Removes all instances of the literal argument OPTION. /// /// 'XOPTION': Removes all instances of the literal argument OPTION, /// and the following argument. /// /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox' /// at the end of the command line. /// /// \param OS - The stream to write edit information to. /// \param Args - The vector of command line arguments. /// \param Edit - The override command to perform. /// \param SavedStrings - Set to use for storing string representations. static void ApplyOneQAOverride(raw_ostream &OS, SmallVectorImpl<const char*> &Args, StringRef Edit, std::set<std::string> &SavedStrings) { // This does not need to be efficient. if (Edit[0] == '^') { const char *Str = GetStableCStr(SavedStrings, Edit.substr(1)); OS << "### Adding argument " << Str << " at beginning\n"; Args.insert(Args.begin() + 1, Str); } else if (Edit[0] == '+') { const char *Str = GetStableCStr(SavedStrings, Edit.substr(1)); OS << "### Adding argument " << Str << " at end\n"; Args.push_back(Str); } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") && Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) { StringRef MatchPattern = Edit.substr(2).split('/').first; StringRef ReplPattern = Edit.substr(2).split('/').second; ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1); for (unsigned i = 1, e = Args.size(); i != e; ++i) { // Ignore end-of-line response file markers if (Args[i] == nullptr) continue; std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]); if (Repl != Args[i]) { OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n"; Args[i] = GetStableCStr(SavedStrings, Repl); } } } else if (Edit[0] == 'x' || Edit[0] == 'X') { std::string Option = Edit.substr(1, std::string::npos); for (unsigned i = 1; i < Args.size();) { if (Option == Args[i]) { OS << "### Deleting argument " << Args[i] << '\n'; Args.erase(Args.begin() + i); if (Edit[0] == 'X') { if (i < Args.size()) { OS << "### Deleting argument " << Args[i] << '\n'; Args.erase(Args.begin() + i); } else OS << "### Invalid X edit, end of command line!\n"; } } else ++i; } } else if (Edit[0] == 'O') { for (unsigned i = 1; i < Args.size();) { const char *A = Args[i]; // Ignore end-of-line response file markers if (A == nullptr) continue; if (A[0] == '-' && A[1] == 'O' && (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' || ('0' <= A[2] && A[2] <= '9'))))) { OS << "### Deleting argument " << Args[i] << '\n'; Args.erase(Args.begin() + i); } else ++i; } OS << "### Adding argument " << Edit << " at end\n"; Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str())); } else { OS << "### Unrecognized edit: " << Edit << "\n"; } } /// ApplyQAOverride - Apply a comma separate list of edits to the /// input argument lists. See ApplyOneQAOverride. static void ApplyQAOverride(SmallVectorImpl<const char*> &Args, const char *OverrideStr, std::set<std::string> &SavedStrings) { raw_ostream *OS = &llvm::errs(); if (OverrideStr[0] == '#') { ++OverrideStr; OS = &llvm::nulls(); } *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n"; // This does not need to be efficient. const char *S = OverrideStr; while (*S) { const char *End = ::strchr(S, ' '); if (!End) End = S + strlen(S); if (End != S) ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings); S = End; if (*S != '\0') ++S; } } extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr); extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr); struct DriverSuffix { const char *Suffix; const char *ModeFlag; }; static const DriverSuffix *FindDriverSuffix(StringRef ProgName) { // A list of known driver suffixes. Suffixes are compared against the // program name in order. If there is a match, the frontend type if updated as // necessary by applying the ModeFlag. static const DriverSuffix DriverSuffixes[] = { {"clang", nullptr}, {"clang++", "--driver-mode=g++"}, {"clang-c++", "--driver-mode=g++"}, {"clang-cc", nullptr}, {"clang-cpp", "--driver-mode=cpp"}, {"clang-g++", "--driver-mode=g++"}, {"clang-gcc", nullptr}, {"clang-cl", "--driver-mode=cl"}, {"cc", nullptr}, {"cpp", "--driver-mode=cpp"}, {"cl", "--driver-mode=cl"}, {"++", "--driver-mode=g++"}, }; for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) if (ProgName.endswith(DriverSuffixes[i].Suffix)) return &DriverSuffixes[i]; return nullptr; } static void ParseProgName(SmallVectorImpl<const char *> &ArgVector, std::set<std::string> &SavedStrings) { // Try to infer frontend type and default target from the program name by // comparing it against DriverSuffixes in order. // If there is a match, the function tries to identify a target as prefix. // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target // prefix "x86_64-linux". If such a target prefix is found, is gets added via // -target as implicit first argument. std::string ProgName =llvm::sys::path::stem(ArgVector[0]); #ifdef LLVM_ON_WIN32 // Transform to lowercase for case insensitive file systems. ProgName = StringRef(ProgName).lower(); #endif StringRef ProgNameRef = ProgName; const DriverSuffix *DS = FindDriverSuffix(ProgNameRef); if (!DS) { // Try again after stripping any trailing version number: // clang++3.5 -> clang++ ProgNameRef = ProgNameRef.rtrim("0123456789."); DS = FindDriverSuffix(ProgNameRef); } if (!DS) { // Try again after stripping trailing -component. // clang++-tot -> clang++ ProgNameRef = ProgNameRef.slice(0, ProgNameRef.rfind('-')); DS = FindDriverSuffix(ProgNameRef); } if (DS) { if (const char *Flag = DS->ModeFlag) { // Add Flag to the arguments. auto it = ArgVector.begin(); if (it != ArgVector.end()) ++it; ArgVector.insert(it, Flag); } StringRef::size_type LastComponent = ProgNameRef.rfind( '-', ProgNameRef.size() - strlen(DS->Suffix)); if (LastComponent == StringRef::npos) return; // Infer target from the prefix. StringRef Prefix = ProgNameRef.slice(0, LastComponent); std::string IgnoredError; if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) { auto it = ArgVector.begin(); if (it != ArgVector.end()) ++it; const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) }; ArgVector.insert(it, std::begin(arr), std::end(arr)); } } } static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) { // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE. TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS"); if (TheDriver.CCPrintOptions) TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE"); // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE. TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS"); if (TheDriver.CCPrintHeaders) TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE"); // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE. TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS"); if (TheDriver.CCLogDiagnostics) TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE"); } static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient, const std::string &Path) { // If the clang binary happens to be named cl.exe for compatibility reasons, // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC. StringRef ExeBasename(llvm::sys::path::filename(Path)); if (ExeBasename.equals_lower("cl.exe")) ExeBasename = "clang-cl.exe"; DiagClient->setPrefix(ExeBasename); } // This lets us create the DiagnosticsEngine with a properly-filled-out // DiagnosticOptions instance. static DiagnosticOptions * CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) { auto *DiagOpts = new DiagnosticOptions; std::unique_ptr<OptTable> Opts(createDriverOptTable()); unsigned MissingArgIndex, MissingArgCount; InputArgList Args = Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount); // We ignore MissingArgCount and the return value of ParseDiagnosticArgs. // Any errors that would be diagnosed here will also be diagnosed later, // when the DiagnosticsEngine actually exists. (void)ParseDiagnosticArgs(*DiagOpts, Args); return DiagOpts; } static void SetInstallDir(SmallVectorImpl<const char *> &argv, Driver &TheDriver) { // Attempt to find the original path used to invoke the driver, to determine // the installed path. We do this manually, because we want to support that // path being a symlink. SmallString<128> InstalledPath(argv[0]); // Do a PATH lookup, if there are no directory components. if (llvm::sys::path::filename(InstalledPath) == InstalledPath) if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName( llvm::sys::path::filename(InstalledPath.str()))) InstalledPath = *Tmp; llvm::sys::fs::make_absolute(InstalledPath); InstalledPath = llvm::sys::path::parent_path(InstalledPath); if (llvm::sys::fs::exists(InstalledPath.c_str())) TheDriver.setInstalledDir(InstalledPath); } static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) { void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath; if (Tool == "") return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP); if (Tool == "as") return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP); // Reject unknown tools. llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n"; return 1; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc_, const char **argv_) { // HLSL Change Starts if (llvm::sys::fs::SetupPerThreadFileSystem()) return 1; llvm::sys::fs::AutoCleanupPerThreadFileSystem auto_cleanup_fs; llvm::sys::fs::MSFileSystem* msfPtr; HRESULT hr; if (!SUCCEEDED(hr = CreateMSFileSystemForDisk(&msfPtr))) return 1; std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr); llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); llvm::STDStreamCloser stdStreamCloser; // HLSL Change Ends llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc_, argv_); if (llvm::sys::Process::FixupStandardFileDescriptors()) return 1; SmallVector<const char *, 256> argv; llvm::SpecificBumpPtrAllocator<char> ArgAllocator; std::error_code EC = llvm::sys::Process::GetArgumentVector( argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator); if (EC) { llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n'; return 1; } llvm::BumpPtrAllocator A; llvm::BumpPtrStringSaver Saver(A); // Determines whether we want nullptr markers in argv to indicate response // files end-of-lines. We only use this for the /LINK driver argument. bool MarkEOLs = true; if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1")) MarkEOLs = false; llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, argv, MarkEOLs); // Handle -cc1 integrated tools, even if -cc1 was expanded from a response // file. auto FirstArg = std::find_if(argv.begin() + 1, argv.end(), [](const char *A) { return A != nullptr; }); if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) { // If -cc1 came from a response file, remove the EOL sentinels. if (MarkEOLs) { auto newEnd = std::remove(argv.begin(), argv.end(), nullptr); argv.resize(newEnd - argv.begin()); } return ExecuteCC1Tool(argv, argv[1] + 4); } bool CanonicalPrefixes = true; for (int i = 1, size = argv.size(); i < size; ++i) { // Skip end-of-line response file markers if (argv[i] == nullptr) continue; if (StringRef(argv[i]) == "-no-canonical-prefixes") { CanonicalPrefixes = false; break; } } std::set<std::string> SavedStrings; // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the // scenes. if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) { // FIXME: Driver shouldn't take extra initial argument. ApplyQAOverride(argv, OverrideStr, SavedStrings); } std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes); IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(argv); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts); FixupDiagPrefixExeName(DiagClient, Path); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); if (!DiagOpts->DiagnosticSerializationFile.empty()) { auto SerializedConsumer = clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile, &*DiagOpts, /*MergeChildRecords=*/true); Diags.setClient(new ChainedDiagnosticConsumer( Diags.takeClient(), std::move(SerializedConsumer))); } ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false); Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags); SetInstallDir(argv, TheDriver); llvm::InitializeAllTargets(); ParseProgName(argv, SavedStrings); SetBackdoorDriverOutputsFromEnvVars(TheDriver); std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv)); int Res = 0; SmallVector<std::pair<int, const Command *>, 4> FailingCommands; if (C.get()) Res = TheDriver.ExecuteCompilation(*C, FailingCommands); // Force a crash to test the diagnostics. if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) { Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH"; // Pretend that every command failed. FailingCommands.clear(); for (const auto &J : C->getJobs()) if (const Command *C = dyn_cast<Command>(&J)) FailingCommands.push_back(std::make_pair(-1, C)); } for (const auto &P : FailingCommands) { int CommandRes = P.first; const Command *FailingCommand = P.second; if (!Res) Res = CommandRes; // If result status is < 0, then the driver command signalled an error. // If result status is 70, then the driver command reported a fatal error. // On Windows, abort will return an exit code of 3. In these cases, // generate additional diagnostic information if possible. bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70; #ifdef LLVM_ON_WIN32 DiagnoseCrash |= CommandRes == 3; #endif if (DiagnoseCrash) { TheDriver.generateCompilationDiagnostics(*C, *FailingCommand); break; } } Diags.getClient()->finish(); // If any timers were active but haven't been destroyed yet, print their // results now. This happens in -disable-free mode. llvm::TimerGroup::printAll(llvm::errs()); llvm::llvm_shutdown(); #ifdef LLVM_ON_WIN32 // Exit status should not be negative on Win32, unless abnormal termination. // Once abnormal termiation was caught, negative status should not be // propagated. if (Res < 0) Res = 1; #endif // If we have multiple failing commands, we return the result of the first // failing command. return Res; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/CMakeLists.txt
set( LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Analysis # CodeGen # HLSL Change Core IPA IPO InstCombine # Instrumentation # HLSL Change # MC # HLSL Change # MCParser # HLSL Change # ObjCARCOpts # HLSL Change Option ScalarOpts Support TransformUtils Vectorize mssupport # HLSL Change hlsl # HLSL Change ) option(CLANG_PLUGIN_SUPPORT "Build clang with plugin support" ON) # Support plugins. This must be before add_clang_executable as it reads # LLVM_NO_DEAD_STRIP. if(CLANG_PLUGIN_SUPPORT) set(LLVM_NO_DEAD_STRIP 1) endif() add_clang_executable(clang driver.cpp cc1_main.cpp cc1as_main.cpp ) target_link_libraries(clang clangBasic clangCodeGen clangDriver clangFrontend clangFrontendTool ) if(WIN32 AND NOT CYGWIN) # Prevent versioning if the buildhost is targeting for Win32. else() set_target_properties(clang PROPERTIES VERSION ${CLANG_EXECUTABLE_VERSION}) endif() # HLSL Change Start if (NOT HLSL_OPTIONAL_PROJS_IN_DEFAULT) set_target_properties(clang PROPERTIES EXCLUDE_FROM_ALL ON EXCLUDE_FROM_DEFAULT_BUILD ON) # HLSL Change endif () # HLSL Change Ends # Support plugins. if(CLANG_PLUGIN_SUPPORT) export_executable_symbols(clang) endif() # add_dependencies(clang clang-headers) - HLSL Change if(UNIX) set(CLANGXX_LINK_OR_COPY create_symlink) # Create a relative symlink set(clang_binary "clang${CMAKE_EXECUTABLE_SUFFIX}") else() set(CLANGXX_LINK_OR_COPY copy) set(clang_binary "${LLVM_RUNTIME_OUTPUT_INTDIR}/clang${CMAKE_EXECUTABLE_SUFFIX}") endif() # Create the clang++ symlink in the build directory. set(clang_pp "${LLVM_RUNTIME_OUTPUT_INTDIR}/clang++${CMAKE_EXECUTABLE_SUFFIX}") add_custom_command(TARGET clang POST_BUILD COMMAND ${CMAKE_COMMAND} -E ${CLANGXX_LINK_OR_COPY} "${clang_binary}" "${clang_pp}" WORKING_DIRECTORY "${LLVM_RUNTIME_OUTPUT_INTDIR}") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${clang_pp}) # Create the clang-cl symlink in the build directory. set(clang_cl "${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}") add_custom_command(TARGET clang POST_BUILD COMMAND ${CMAKE_COMMAND} -E ${CLANGXX_LINK_OR_COPY} "${clang_binary}" "${clang_cl}" WORKING_DIRECTORY "${LLVM_RUNTIME_OUTPUT_INTDIR}") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${clang_cl}) # HLSL Changes Start - do not install clang.exe unless we build it by default if (HLSL_OPTIONAL_PROJS_IN_DEFAULT) install(TARGETS clang RUNTIME DESTINATION bin) # Create the clang++ and clang-cl symlinks at installation time. install(SCRIPT clang_symlink.cmake -DCMAKE_INSTALL_PREFIX=\"${CMAKE_INSTALL_PREFIX}\") endif (HLSL_OPTIONAL_PROJS_IN_DEFAULT) # HLSL Change Ends # Configure plist creation for OS X. set (TOOL_INFO_PLIST "Info.plist" CACHE STRING "Plist name") if (APPLE) if (CLANG_VENDOR) set(TOOL_INFO_NAME "${CLANG_VENDOR} clang") else() set(TOOL_INFO_NAME "clang") endif() set(TOOL_INFO_UTI "${CLANG_VENDOR_UTI}") set(TOOL_INFO_VERSION "${CLANG_VERSION}") if (LLVM_SUBMIT_VERSION) set(TOOL_INFO_BUILD_VERSION "${LLVM_SUBMIT_VERSION}.${LLVM_SUBMIT_SUBVERSION}") endif() set(TOOL_INFO_PLIST_OUT "${CMAKE_CURRENT_BINARY_DIR}/${TOOL_INFO_PLIST}") target_link_libraries(clang "-Wl,-sectcreate,__TEXT,__info_plist,${TOOL_INFO_PLIST_OUT}") configure_file("${TOOL_INFO_PLIST}.in" "${TOOL_INFO_PLIST_OUT}" @ONLY) set(TOOL_INFO_UTI) set(TOOL_INFO_NAME) set(TOOL_INFO_VERSION) set(TOOL_INFO_BUILD_VERSION) endif() if(CLANG_ORDER_FILE) target_link_libraries(clang "-Wl,-order_file,${CLANG_ORDER_FILE}") endif() if(WITH_POLLY AND LINK_POLLY_INTO_TOOLS) target_link_libraries(clang Polly) if(POLLY_LINK_LIBS) foreach(lib ${POLLY_LINK_LIBS}) target_link_libraries(clang ${lib}) endforeach(lib) endif(POLLY_LINK_LIBS) endif(WITH_POLLY AND LINK_POLLY_INTO_TOOLS)
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/cc1_main.cpp
//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the entry point to the clang -cc1 functionality, which implements the // core compiler functionality along with a number of additional tools for // demonstration and testing purposes. // //===----------------------------------------------------------------------===// #include "llvm/Option/Arg.h" #include "clang/CodeGen/ObjectFilePCHContainerOperations.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Frontend/Utils.h" #include "clang/FrontendTool/Utils.h" #include "llvm/ADT/Statistic.h" #include "llvm/LinkAllPasses.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> using namespace clang; using namespace llvm::opt; //===----------------------------------------------------------------------===// // Main driver //===----------------------------------------------------------------------===// static void LLVMErrorHandler(void *UserData, const std::string &Message, bool GenCrashDiag) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; // Run the interrupt handlers to make sure any special cleanups get done, in // particular that we remove files registered with RemoveFileOnSignal. llvm::sys::RunInterruptHandlers(); // We cannot recover from llvm errors. When reporting a fatal error, exit // with status 70 to generate crash diagnostics. For BSD systems this is // defined as an internal software error. Otherwise, exit with status 1. exit(GenCrashDiag ? 70 : 1); } #ifdef LINK_POLLY_INTO_TOOLS namespace polly { void initializePollyPasses(llvm::PassRegistry &Registry); } #endif int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); // Register the support for object-file-wrapped Clang modules. auto PCHOps = Clang->getPCHContainerOperations(); PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>()); PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>()); // Initialize targets first, so that --version shows registered targets. llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); #ifdef LINK_POLLY_INTO_TOOLS llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); polly::initializePollyPasses(Registry); #endif // Buffer diagnostics from argument parsing so that we can output them using a // well formed diagnostic object. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); bool Success = CompilerInvocation::CreateFromArgs( Clang->getInvocation(), Argv.begin(), Argv.end(), Diags); // Infer the builtin include path if unspecified. if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && Clang->getHeaderSearchOpts().ResourceDir.empty()) Clang->getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(Argv0, MainAddr); // Create the actual diagnostics engine. Clang->createDiagnostics(); if (!Clang->hasDiagnostics()) return 1; // Set an error handler, so that any LLVM backend diagnostics go through our // error handler. llvm::install_fatal_error_handler(LLVMErrorHandler, static_cast<void*>(&Clang->getDiagnostics())); DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); if (!Success) return 1; // Execute the frontend actions. Success = ExecuteCompilerInvocation(Clang.get()); // If any timers were active but haven't been destroyed yet, print their // results now. This happens in -disable-free mode. llvm::TimerGroup::printAll(llvm::errs()); // Our error handler depends on the Diagnostics object, which we're // potentially about to delete. Uninstall the handler now so that any // later errors use the default handling behavior instead. llvm::remove_fatal_error_handler(); // When running with -disable-free, don't do any destruction or shutdown. if (Clang->getFrontendOpts().DisableFree) { if (llvm::AreStatisticsEnabled() || Clang->getFrontendOpts().ShowStats) llvm::PrintStatistics(); BuryPointer(std::move(Clang)); return !Success; } // Managed static deconstruction. Useful for making things like // -time-passes usable. llvm::llvm_shutdown(); return !Success; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/driver/clang_symlink.cmake
# We need to execute this script at installation time because the # DESTDIR environment variable may be unset at configuration time. # See PR8397. if(UNIX) set(CLANGXX_LINK_OR_COPY create_symlink) set(CLANGXX_DESTDIR $ENV{DESTDIR}) else() set(CLANGXX_LINK_OR_COPY copy) endif() # CMAKE_EXECUTABLE_SUFFIX is undefined on cmake scripts. See PR9286. if( WIN32 ) set(EXECUTABLE_SUFFIX ".exe") else() set(EXECUTABLE_SUFFIX "") endif() set(bindir "${CLANGXX_DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/") set(clang "clang${EXECUTABLE_SUFFIX}") set(clangxx "clang++${EXECUTABLE_SUFFIX}") set(clang_cl "clang-cl${EXECUTABLE_SUFFIX}") set(cl "cl${EXECUTABLE_SUFFIX}") message("Creating clang++ executable based on ${clang}") execute_process( COMMAND "${CMAKE_COMMAND}" -E ${CLANGXX_LINK_OR_COPY} "${clang}" "${clangxx}" WORKING_DIRECTORY "${bindir}") message("Creating clang-cl executable based on ${clang}") execute_process( COMMAND "${CMAKE_COMMAND}" -E ${CLANGXX_LINK_OR_COPY} "${clang}" "${clang_cl}" WORKING_DIRECTORY "${bindir}") if (WIN32) message("Creating cl executable based on ${clang}") execute_process( COMMAND "${CMAKE_COMMAND}" -E ${CLANGXX_LINK_OR_COPY} "${clang}" "../msbuild-bin/${cl}" WORKING_DIRECTORY "${bindir}") endif()
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxc/dxc.rc
// Copyright (c) Microsoft Corporation. All rights reserved. // #include <windows.h> #include <ntverp.h> #define VER_FILETYPE VFT_DLL #define VER_FILESUBTYPE VFT_UNKNOWN #define VER_FILEDESCRIPTION_STR "DX Compiler" #define VER_INTERNALNAME_STR "DX Compiler" #define VER_ORIGINALFILENAME_STR "dxc.exe" #include <common.ver>
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxc/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. # Builds dxc.exe if (MSVC) find_package(DiaSDK REQUIRED) # Used for constants and declarations. endif (MSVC) set( LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} dxcsupport DXIL DxilContainer HLSL Option # option library Support # just for assert and raw streams ) add_clang_executable(dxc dxcmain.cpp # dxr.rc ) target_link_libraries(dxc dxclib dxcompiler dxclib ) if(ENABLE_SPIRV_CODEGEN) target_link_libraries(dxc SPIRV-Tools) endif() set_target_properties(dxc PROPERTIES VERSION ${CLANG_EXECUTABLE_VERSION}) if (MSVC) include_directories(AFTER ${DIASDK_INCLUDE_DIRS}) endif (MSVC) include_directories(${LLVM_SOURCE_DIR}/tools/clang/tools) add_dependencies(dxc dxclib dxcompiler) if(UNIX) set(CLANGXX_LINK_OR_COPY create_symlink) # Create a relative symlink set(dxc_binary "dxc${CMAKE_EXECUTABLE_SUFFIX}") else() set(CLANGXX_LINK_OR_COPY copy) set(dxc_binary "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CMAKE_CFG_INTDIR}/dxc${CMAKE_EXECUTABLE_SUFFIX}") endif() install(TARGETS dxc RUNTIME DESTINATION bin COMPONENT dxc) add_custom_target(install-dxc DEPENDS dxc COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=dxc -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dxc/dxcmain.cpp
/////////////////////////////////////////////////////////////////////////////// // // // dxc.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides the entry point for the dxc console program. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxclib/dxc.h" #ifdef _WIN32 int __cdecl wmain(int argc, const wchar_t **argv_) { return dxc::main(argc, argv_); #else int main(int argc, const char **argv_) { return dxc::main(argc, argv_); #endif // _WIN32 }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/DiagnosticNames.cpp
//===- DiagnosticNames.cpp - Defines a table of all builtin diagnostics ----==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DiagnosticNames.h" #include "clang/Basic/AllDiagnostics.h" #include "llvm/ADT/STLExtras.h" using namespace clang; using namespace diagtool; static const DiagnosticRecord BuiltinDiagnosticsByName[] = { #define DIAG_NAME_INDEX(ENUM) { #ENUM, diag::ENUM, STR_SIZE(#ENUM, uint8_t) }, #include "clang/Basic/DiagnosticIndexName.inc" #undef DIAG_NAME_INDEX }; llvm::ArrayRef<DiagnosticRecord> diagtool::getBuiltinDiagnosticsByName() { return llvm::makeArrayRef(BuiltinDiagnosticsByName); } // FIXME: Is it worth having two tables, especially when this one can get // out of sync easily? static const DiagnosticRecord BuiltinDiagnosticsByID[] = { #define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP, \ SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) \ { #ENUM, diag::ENUM, STR_SIZE(#ENUM, uint8_t) }, #include "clang/Basic/DiagnosticCommonKinds.inc" #include "clang/Basic/DiagnosticDriverKinds.inc" #include "clang/Basic/DiagnosticFrontendKinds.inc" #include "clang/Basic/DiagnosticSerializationKinds.inc" #include "clang/Basic/DiagnosticLexKinds.inc" #include "clang/Basic/DiagnosticParseKinds.inc" #include "clang/Basic/DiagnosticASTKinds.inc" #include "clang/Basic/DiagnosticCommentKinds.inc" #include "clang/Basic/DiagnosticSemaKinds.inc" #include "clang/Basic/DiagnosticAnalysisKinds.inc" #undef DIAG }; static bool orderByID(const DiagnosticRecord &Left, const DiagnosticRecord &Right) { return Left.DiagID < Right.DiagID; } const DiagnosticRecord &diagtool::getDiagnosticForID(short DiagID) { DiagnosticRecord Key = {nullptr, DiagID, 0}; const DiagnosticRecord *Result = std::lower_bound(std::begin(BuiltinDiagnosticsByID), std::end(BuiltinDiagnosticsByID), Key, orderByID); assert(Result && "diagnostic not found; table may be out of date"); return *Result; } #define GET_DIAG_ARRAYS #include "clang/Basic/DiagnosticGroups.inc" #undef GET_DIAG_ARRAYS // Second the table of options, sorted by name for fast binary lookup. static const GroupRecord OptionTable[] = { #define GET_DIAG_TABLE #include "clang/Basic/DiagnosticGroups.inc" #undef GET_DIAG_TABLE }; llvm::StringRef GroupRecord::getName() const { return StringRef(DiagGroupNames + NameOffset + 1, DiagGroupNames[NameOffset]); } GroupRecord::subgroup_iterator GroupRecord::subgroup_begin() const { return DiagSubGroups + SubGroups; } GroupRecord::subgroup_iterator GroupRecord::subgroup_end() const { return nullptr; } GroupRecord::diagnostics_iterator GroupRecord::diagnostics_begin() const { return DiagArrays + Members; } GroupRecord::diagnostics_iterator GroupRecord::diagnostics_end() const { return nullptr; } llvm::ArrayRef<GroupRecord> diagtool::getDiagnosticGroups() { return llvm::makeArrayRef(OptionTable); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/ListWarnings.cpp
//===- ListWarnings.h - diagtool tool for printing warning flags ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides a diagtool tool that displays warning flags for // diagnostics. // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "DiagnosticNames.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/Diagnostic.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Format.h" DEF_DIAGTOOL("list-warnings", "List warnings and their corresponding flags", ListWarnings) using namespace clang; using namespace diagtool; namespace { struct Entry { llvm::StringRef DiagName; llvm::StringRef Flag; Entry(llvm::StringRef diagN, llvm::StringRef flag) : DiagName(diagN), Flag(flag) {} bool operator<(const Entry &x) const { return DiagName < x.DiagName; } }; } static void printEntries(std::vector<Entry> &entries, llvm::raw_ostream &out) { for (std::vector<Entry>::iterator it = entries.begin(), ei = entries.end(); it != ei; ++it) { out << " " << it->DiagName; if (!it->Flag.empty()) out << " [-W" << it->Flag << "]"; out << '\n'; } } int ListWarnings::run(unsigned int argc, char **argv, llvm::raw_ostream &out) { std::vector<Entry> Flagged, Unflagged; llvm::StringMap<std::vector<unsigned> > flagHistogram; ArrayRef<DiagnosticRecord> AllDiagnostics = getBuiltinDiagnosticsByName(); for (ArrayRef<DiagnosticRecord>::iterator di = AllDiagnostics.begin(), de = AllDiagnostics.end(); di != de; ++di) { unsigned diagID = di->DiagID; if (DiagnosticIDs::isBuiltinNote(diagID)) continue; if (!DiagnosticIDs::isBuiltinWarningOrExtension(diagID)) continue; Entry entry(di->getName(), DiagnosticIDs::getWarningOptionForDiag(diagID)); if (entry.Flag.empty()) Unflagged.push_back(entry); else { Flagged.push_back(entry); flagHistogram[entry.Flag].push_back(diagID); } } out << "Warnings with flags (" << Flagged.size() << "):\n"; printEntries(Flagged, out); out << "Warnings without flags (" << Unflagged.size() << "):\n"; printEntries(Unflagged, out); out << "\nSTATISTICS:\n\n"; double percentFlagged = ((double) Flagged.size()) / (Flagged.size() + Unflagged.size()) * 100.0; out << " Percentage of warnings with flags: " << llvm::format("%.4g",percentFlagged) << "%\n"; out << " Number of unique flags: " << flagHistogram.size() << '\n'; double avgDiagsPerFlag = (double) Flagged.size() / flagHistogram.size(); out << " Average number of diagnostics per flag: " << llvm::format("%.4g", avgDiagsPerFlag) << '\n'; out << " Number in -Wpedantic (not covered by other -W flags): " << flagHistogram["pedantic"].size() << '\n'; out << '\n'; return 0; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/DiagTool.h
//===- DiagTool.h - Classes for defining diagtool tools -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the boilerplate for defining diagtool tools. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_DIAGTOOL_DIAGTOOL_H #define LLVM_CLANG_TOOLS_DIAGTOOL_DIAGTOOL_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include <string> namespace diagtool { class DiagTool { const std::string cmd; const std::string description; public: DiagTool(llvm::StringRef toolCmd, llvm::StringRef toolDesc); virtual ~DiagTool(); llvm::StringRef getName() const { return cmd; } llvm::StringRef getDescription() const { return description; } virtual int run(unsigned argc, char *argv[], llvm::raw_ostream &out) = 0; }; class DiagTools { void *tools; public: DiagTools(); ~DiagTools(); DiagTool *getTool(llvm::StringRef toolCmd); void registerTool(DiagTool *tool); void printCommands(llvm::raw_ostream &out); }; extern llvm::ManagedStatic<DiagTools> diagTools; template <typename DIAGTOOL> class RegisterDiagTool { public: RegisterDiagTool() { diagTools->registerTool(new DIAGTOOL()); } }; } // end diagtool namespace #define DEF_DIAGTOOL(NAME, DESC, CLSNAME)\ namespace {\ class CLSNAME : public diagtool::DiagTool {\ public:\ CLSNAME() : DiagTool(NAME, DESC) {}\ virtual ~CLSNAME() {}\ int run(unsigned argc, char *argv[], llvm::raw_ostream &out) override;\ };\ diagtool::RegisterDiagTool<CLSNAME> Register##CLSNAME;\ } #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/TreeView.cpp
//===- TreeView.cpp - diagtool tool for printing warning flags ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "DiagnosticNames.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Format.h" #include "llvm/Support/Process.h" DEF_DIAGTOOL("tree", "Show warning flags in a tree view", TreeView) using namespace clang; using namespace diagtool; static bool hasColors(const llvm::raw_ostream &out) { if (&out != &llvm::errs() && &out != &llvm::outs()) return false; return llvm::errs().is_displayed() && llvm::outs().is_displayed(); } class TreePrinter { public: llvm::raw_ostream &out; const bool ShowColors; bool FlagsOnly; TreePrinter(llvm::raw_ostream &out) : out(out), ShowColors(hasColors(out)), FlagsOnly(false) {} void setColor(llvm::raw_ostream::Colors Color) { if (ShowColors) out << llvm::sys::Process::OutputColor(Color, false, false); } void resetColor() { if (ShowColors) out << llvm::sys::Process::ResetColor(); } static bool isIgnored(unsigned DiagID) { // FIXME: This feels like a hack. static clang::DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions); return Diags.isIgnored(DiagID, SourceLocation()); } void printGroup(const GroupRecord &Group, unsigned Indent = 0) { out.indent(Indent * 2); setColor(llvm::raw_ostream::YELLOW); out << "-W" << Group.getName() << "\n"; resetColor(); ++Indent; for (GroupRecord::subgroup_iterator I = Group.subgroup_begin(), E = Group.subgroup_end(); I != E; ++I) { printGroup(*I, Indent); } if (!FlagsOnly) { for (GroupRecord::diagnostics_iterator I = Group.diagnostics_begin(), E = Group.diagnostics_end(); I != E; ++I) { if (ShowColors && !isIgnored(I->DiagID)) setColor(llvm::raw_ostream::GREEN); out.indent(Indent * 2); out << I->getName(); resetColor(); out << "\n"; } } } int showGroup(StringRef RootGroup) { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); if (RootGroup.size() > UINT16_MAX) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } const GroupRecord *Found = std::lower_bound(AllGroups.begin(), AllGroups.end(), RootGroup); if (Found == AllGroups.end() || Found->getName() != RootGroup) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } printGroup(*Found); return 0; } int showAll() { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); llvm::DenseSet<unsigned> NonRootGroupIDs; for (ArrayRef<GroupRecord>::iterator I = AllGroups.begin(), E = AllGroups.end(); I != E; ++I) { for (GroupRecord::subgroup_iterator SI = I->subgroup_begin(), SE = I->subgroup_end(); SI != SE; ++SI) { NonRootGroupIDs.insert((unsigned)SI.getID()); } } assert(NonRootGroupIDs.size() < AllGroups.size()); for (unsigned i = 0, e = AllGroups.size(); i != e; ++i) { if (!NonRootGroupIDs.count(i)) printGroup(AllGroups[i]); } return 0; } void showKey() { if (ShowColors) { out << '\n'; setColor(llvm::raw_ostream::GREEN); out << "GREEN"; resetColor(); out << " = enabled by default\n\n"; } } }; static void printUsage() { llvm::errs() << "Usage: diagtool tree [--flags-only] [<diagnostic-group>]\n"; } int TreeView::run(unsigned int argc, char **argv, llvm::raw_ostream &out) { // First check our one flag (--flags-only). bool FlagsOnly = false; if (argc > 0) { StringRef FirstArg(*argv); if (FirstArg.equals("--flags-only")) { FlagsOnly = true; --argc; ++argv; } } bool ShowAll = false; StringRef RootGroup; switch (argc) { case 0: ShowAll = true; break; case 1: RootGroup = argv[0]; if (RootGroup.startswith("-W")) RootGroup = RootGroup.substr(2); if (RootGroup == "everything") ShowAll = true; // FIXME: Handle other special warning flags, like -pedantic. break; default: printUsage(); return -1; } TreePrinter TP(out); TP.FlagsOnly = FlagsOnly; TP.showKey(); return ShowAll ? TP.showAll() : TP.showGroup(RootGroup); }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Support mcparser # HLSL Change hlsl # HLSL Change ) add_clang_executable(diagtool diagtool_main.cpp DiagTool.cpp DiagnosticNames.cpp ListWarnings.cpp ShowEnabledWarnings.cpp TreeView.cpp ) target_link_libraries(diagtool clangBasic clangFrontend ) if(UNIX) set(CLANGXX_LINK_OR_COPY create_symlink) else() set(CLANGXX_LINK_OR_COPY copy) endif()
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/ShowEnabledWarnings.cpp
//===- ShowEnabledWarnings - diagtool tool for printing enabled flags -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "DiagnosticNames.h" #include "clang/Basic/LLVM.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Frontend/Utils.h" #include "llvm/Support/TargetSelect.h" DEF_DIAGTOOL("show-enabled", "Show which warnings are enabled for a given command line", ShowEnabledWarnings) using namespace clang; using namespace diagtool; namespace { struct PrettyDiag { StringRef Name; StringRef Flag; DiagnosticsEngine::Level Level; PrettyDiag(StringRef name, StringRef flag, DiagnosticsEngine::Level level) : Name(name), Flag(flag), Level(level) {} bool operator<(const PrettyDiag &x) const { return Name < x.Name; } }; } static void printUsage() { llvm::errs() << "Usage: diagtool show-enabled [<flags>] <single-input.c>\n"; } static char getCharForLevel(DiagnosticsEngine::Level Level) { switch (Level) { case DiagnosticsEngine::Ignored: return ' '; case DiagnosticsEngine::Note: return '-'; case DiagnosticsEngine::Remark: return 'R'; case DiagnosticsEngine::Warning: return 'W'; case DiagnosticsEngine::Error: return 'E'; case DiagnosticsEngine::Fatal: return 'F'; } llvm_unreachable("Unknown diagnostic level"); } static IntrusiveRefCntPtr<DiagnosticsEngine> createDiagnostics(unsigned int argc, char **argv) { IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs()); // Buffer diagnostics from argument parsing so that we can output them using a // well formed diagnostic object. TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; IntrusiveRefCntPtr<DiagnosticsEngine> InterimDiags( new DiagnosticsEngine(DiagIDs, new DiagnosticOptions(), DiagsBuffer)); // Try to build a CompilerInvocation. std::unique_ptr<CompilerInvocation> Invocation( createInvocationFromCommandLine(llvm::makeArrayRef(argv, argc), InterimDiags)); if (!Invocation) return nullptr; // Build the diagnostics parser IntrusiveRefCntPtr<DiagnosticsEngine> FinalDiags = CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts()); if (!FinalDiags) return nullptr; // Flush any errors created when initializing everything. This could happen // for invalid command lines, which will probably give non-sensical results. DiagsBuffer->FlushDiagnostics(*FinalDiags); return FinalDiags; } int ShowEnabledWarnings::run(unsigned int argc, char **argv, raw_ostream &Out) { // First check our one flag (--levels). bool ShouldShowLevels = true; if (argc > 0) { StringRef FirstArg(*argv); if (FirstArg.equals("--no-levels")) { ShouldShowLevels = false; --argc; ++argv; } else if (FirstArg.equals("--levels")) { ShouldShowLevels = true; --argc; ++argv; } } // Create the diagnostic engine. IntrusiveRefCntPtr<DiagnosticsEngine> Diags = createDiagnostics(argc, argv); if (!Diags) { printUsage(); return EXIT_FAILURE; } // Now we have our diagnostics. Iterate through EVERY diagnostic and see // which ones are turned on. // FIXME: It would be very nice to print which flags are turning on which // diagnostics, but this can be done with a diff. ArrayRef<DiagnosticRecord> AllDiagnostics = getBuiltinDiagnosticsByName(); std::vector<PrettyDiag> Active; for (ArrayRef<DiagnosticRecord>::iterator I = AllDiagnostics.begin(), E = AllDiagnostics.end(); I != E; ++I) { unsigned DiagID = I->DiagID; if (DiagnosticIDs::isBuiltinNote(DiagID)) continue; if (!DiagnosticIDs::isBuiltinWarningOrExtension(DiagID)) continue; DiagnosticsEngine::Level DiagLevel = Diags->getDiagnosticLevel(DiagID, SourceLocation()); if (DiagLevel == DiagnosticsEngine::Ignored) continue; StringRef WarningOpt = DiagnosticIDs::getWarningOptionForDiag(DiagID); Active.push_back(PrettyDiag(I->getName(), WarningOpt, DiagLevel)); } // Print them all out. for (std::vector<PrettyDiag>::const_iterator I = Active.begin(), E = Active.end(); I != E; ++I) { if (ShouldShowLevels) Out << getCharForLevel(I->Level) << " "; Out << I->Name; if (!I->Flag.empty()) Out << " [-W" << I->Flag << "]"; Out << '\n'; } return EXIT_SUCCESS; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/DiagTool.cpp
//===- DiagTool.cpp - Classes for defining diagtool tools -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the boilerplate for defining diagtool tools. // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include <vector> using namespace diagtool; DiagTool::DiagTool(llvm::StringRef toolCmd, llvm::StringRef toolDesc) : cmd(toolCmd), description(toolDesc) {} DiagTool::~DiagTool() {} typedef llvm::StringMap<DiagTool *> ToolMap; static inline ToolMap *getTools(void *v) { return static_cast<ToolMap*>(v); } DiagTools::DiagTools() : tools(new ToolMap()) {} DiagTools::~DiagTools() { delete getTools(tools); } DiagTool *DiagTools::getTool(llvm::StringRef toolCmd) { ToolMap::iterator it = getTools(tools)->find(toolCmd); return (it == getTools(tools)->end()) ? nullptr : it->getValue(); } void DiagTools::registerTool(DiagTool *tool) { (*getTools(tools))[tool->getName()] = tool; } void DiagTools::printCommands(llvm::raw_ostream &out) { std::vector<llvm::StringRef> toolNames; unsigned maxName = 0; for (ToolMap::iterator it = getTools(tools)->begin(), ei = getTools(tools)->end(); it != ei; ++it) { toolNames.push_back(it->getKey()); unsigned len = it->getKey().size(); if (len > maxName) maxName = len; } std::sort(toolNames.begin(), toolNames.end()); for (std::vector<llvm::StringRef>::iterator it = toolNames.begin(), ei = toolNames.end(); it != ei; ++it) { out << " " << (*it); unsigned spaces = (maxName + 3) - (it->size()); for (unsigned i = 0; i < spaces; ++i) out << ' '; out << getTool(*it)->getDescription() << '\n'; } } namespace diagtool { llvm::ManagedStatic<DiagTools> diagTools; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/diagtool_main.cpp
//===- diagtool_main.h - Entry point for invoking all diagnostic tools ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the main function for diagtool. // //===----------------------------------------------------------------------===// #include "DiagTool.h" using namespace diagtool; int main(int argc, char *argv[]) { if (argc > 1) if (DiagTool *tool = diagTools->getTool(argv[1])) return tool->run(argc - 2, &argv[2], llvm::outs()); llvm::errs() << "usage: diagtool <command> [<args>]\n\n"; diagTools->printCommands(llvm::errs()); return 1; }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/diagtool/DiagnosticNames.h
//===- DiagnosticNames.h - Defines a table of all builtin diagnostics ------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_DIAGTOOL_DIAGNOSTICNAMES_H #define LLVM_CLANG_TOOLS_DIAGTOOL_DIAGNOSTICNAMES_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" namespace diagtool { struct DiagnosticRecord { const char *NameStr; short DiagID; uint8_t NameLen; llvm::StringRef getName() const { return llvm::StringRef(NameStr, NameLen); } bool operator<(const DiagnosticRecord &Other) const { return getName() < Other.getName(); } }; /// \brief Get every diagnostic in the system, sorted by name. llvm::ArrayRef<DiagnosticRecord> getBuiltinDiagnosticsByName(); /// \brief Get a diagnostic by its ID. const DiagnosticRecord &getDiagnosticForID(short DiagID); struct GroupRecord { uint16_t NameOffset; uint16_t Members; uint16_t SubGroups; llvm::StringRef getName() const; template<typename RecordType> class group_iterator { const short *CurrentID; friend struct GroupRecord; group_iterator(const short *Start) : CurrentID(Start) { if (CurrentID && *CurrentID == -1) CurrentID = nullptr; } public: typedef RecordType value_type; typedef const value_type & reference; typedef const value_type * pointer; typedef std::forward_iterator_tag iterator_category; typedef std::ptrdiff_t difference_type; inline reference operator*() const; inline pointer operator->() const { return &operator*(); } inline short getID() const { return *CurrentID; } group_iterator &operator++() { ++CurrentID; if (*CurrentID == -1) CurrentID = nullptr; return *this; } bool operator==(group_iterator &Other) const { return CurrentID == Other.CurrentID; } bool operator!=(group_iterator &Other) const { return CurrentID != Other.CurrentID; } }; typedef group_iterator<GroupRecord> subgroup_iterator; subgroup_iterator subgroup_begin() const; subgroup_iterator subgroup_end() const; typedef group_iterator<DiagnosticRecord> diagnostics_iterator; diagnostics_iterator diagnostics_begin() const; diagnostics_iterator diagnostics_end() const; bool operator<(llvm::StringRef Other) const { return getName() < Other; } }; /// \brief Get every diagnostic group in the system, sorted by name. llvm::ArrayRef<GroupRecord> getDiagnosticGroups(); template<> inline GroupRecord::subgroup_iterator::reference GroupRecord::subgroup_iterator::operator*() const { return getDiagnosticGroups()[*CurrentID]; } template<> inline GroupRecord::diagnostics_iterator::reference GroupRecord::diagnostics_iterator::operator*() const { return getDiagnosticForID(*CurrentID); } } // end namespace diagtool #endif
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/D3DCompiler.cs
/////////////////////////////////////////////////////////////////////////////// // // // D3DCompiler.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// namespace D3DCompiler { using DotNetDxc; using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct D3D_SHADER_MACRO { [MarshalAs(UnmanagedType.LPStr)] string Name; [MarshalAs(UnmanagedType.LPStr)] string Definition; } internal static class D3DCompiler { [DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.Winapi, SetLastError = false, CharSet = CharSet.Ansi, ExactSpelling = true)] public extern static Int32 D3DCompile( [MarshalAs(UnmanagedType.LPStr)] string srcData, int srcDataSize, [MarshalAs(UnmanagedType.LPStr)] string sourceName, [MarshalAs(UnmanagedType.LPArray)] D3D_SHADER_MACRO[] defines, int pInclude, [MarshalAs(UnmanagedType.LPStr)] string entryPoint, [MarshalAs(UnmanagedType.LPStr)] string target, UInt32 Flags1, UInt32 Flags2, out IDxcBlob code, out IDxcBlob errorMsgs); [DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.Winapi, SetLastError = false, CharSet = CharSet.Ansi, ExactSpelling = true)] public extern static Int32 D3DDisassemble( IntPtr ptr, uint ptrSize, uint flags, [MarshalAs(UnmanagedType.LPStr)] string szComments, out IDxcBlob disassembly); } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/EditorForm.cs
/////////////////////////////////////////////////////////////////////////////// // // // EditorForm.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// using DotNetDxc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace MainNs { public partial class EditorForm : Form { private const string AppName = "DirectX Compiler Editor"; private const string OptDescSeparator = "\t"; private bool autoDisassemble; private IDxcLibrary library; private IDxcIntelliSense isense; private IDxcIndex lastIndex; private IDxcTranslationUnit lastTU; private IDxcBlob selectedShaderBlob; private string selectedShaderBlobTarget; private bool passesLoaded = false; private bool docModified = false; private string docFileName; private DocumentKind documentKind; private MRUManager mruManager; private SettingsManager settingsManager; private Action pendingASTDump; private FindDialog findDialog; private TabPage errorListTabPage; private List<DiagnosticDetail> diagnosticDetails; private DataGridView diagnosticDetailsGrid; private List<PassInfo> passInfos; private TabPage debugInfoTabPage; private RichTextBox debugInfoControl; private HlslHost hlslHost = new HlslHost(); private TabPage renderViewTabPage; private TabPage rewriterOutputTabPage; private TabPage helpTabPage; private RichTextBox helpControl; internal enum DocumentKind { /// <summary> /// HLSL source code. /// </summary> HlslText, /// <summary> /// LLVM source code. /// </summary> AsmText, /// <summary> /// Compiled DXIL container. /// </summary> CompiledObject, } public EditorForm() { InitializeComponent(); cbProfile.SelectedIndex = 0; } internal IDxcBlob SelectedShaderBlob { get { return this.selectedShaderBlob; } set { this.selectedShaderBlob = value; this.selectedShaderBlobTarget = TryGetBlobShaderTarget(this.selectedShaderBlob); } } private const uint DFCC_DXIL = 1279875140; private const uint DFCC_SHDR = 1380206675; private const uint DFCC_SHEX = 1480935507; private const uint DFCC_ILDB = 1111772233; private const uint DFCC_SPDB = 1111773267; private TabPage HelpTabPage { get { if (this.helpTabPage == null) { this.helpTabPage = new TabPage("Help"); this.AnalysisTabControl.TabPages.Add(helpTabPage); } return this.helpTabPage; } } private RichTextBox HelpControl { get { if (this.helpControl == null) { this.helpControl = new RichTextBox(); this.HelpTabPage.Controls.Add(this.helpControl); this.helpControl.Dock = DockStyle.Fill; this.helpControl.Font = this.CodeBox.Font; } return this.helpControl; } } private TabPage RenderViewTabPage { get { if (this.renderViewTabPage == null) { this.renderViewTabPage = new TabPage("Render View"); this.AnalysisTabControl.TabPages.Add(renderViewTabPage); } return this.renderViewTabPage; } } private TabPage RewriterOutputTabPage { get { if (this.rewriterOutputTabPage == null) { this.rewriterOutputTabPage = new TabPage("Rewriter Output"); this.AnalysisTabControl.TabPages.Add(rewriterOutputTabPage); } return this.rewriterOutputTabPage; } } private string TryGetBlobShaderTarget(IDxcBlob blob) { if (blob == null) return null; uint size = blob.GetBufferSize(); if (size == 0) return null; unsafe { try { var reflection = HlslDxcLib.CreateDxcContainerReflection(); reflection.Load(blob); uint index; int hr = reflection.FindFirstPartKind(DFCC_DXIL, out index); if (hr < 0) hr = reflection.FindFirstPartKind(DFCC_SHEX, out index); if (hr < 0) hr = reflection.FindFirstPartKind(DFCC_SHDR, out index); if (hr < 0) return null; unsafe { IDxcBlob part = reflection.GetPartContent(index); UInt32* p = (UInt32*)part.GetBufferPointer(); return DescribeProgramVersionShort(*p); } } catch (Exception) { return null; } } } private void EditorForm_Shown(object sender, EventArgs e) { // Launched as a console program, so this needs to be done explicitly. this.Activate(); this.UpdateWindowText(); } #region Menu item handlers. private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { // Version information currently is available through validator. string libraryVersion; try { IDxcValidator validator = HlslDxcLib.CreateDxcValidator(); IDxcVersionInfo versionInfo = (IDxcVersionInfo)validator; uint major, minor; versionInfo.GetVersion(out major, out minor); DxcVersionInfoFlags flags = versionInfo.GetFlags(); libraryVersion = major.ToString() + "." + minor.ToString(); if ((flags & DxcVersionInfoFlags.Debug) == DxcVersionInfoFlags.Debug) { libraryVersion += " (debug)"; } } catch (Exception err) { libraryVersion = err.Message; } IDxcLibrary library = HlslDxcLib.CreateDxcLibrary(); MessageBox.Show(this, AppName + "\r\n" + "Compiler Library Version: " + libraryVersion + "\r\n" + "See LICENSE.txt for license information.", "About " + AppName); } private void compileToolStripMenuItem_Click(object sender, EventArgs e) { this.CompileDocument(); this.AnalysisTabControl.SelectedTab = this.DisassemblyTabPage; } private void errorListToolStripMenuItem_Click(object sender, EventArgs e) { if (errorListTabPage == null) { this.errorListTabPage = new TabPage("Error List"); this.AnalysisTabControl.TabPages.Add(this.errorListTabPage); this.diagnosticDetailsGrid = new DataGridView() { AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells, Dock = DockStyle.Fill, ReadOnly = true, }; this.diagnosticDetailsGrid.DoubleClick += DiagnosticDetailsGridDoubleClick; this.diagnosticDetailsGrid.CellDoubleClick += (_, __) => { DiagnosticDetailsGridDoubleClick(sender, EventArgs.Empty); }; this.errorListTabPage.Controls.Add(this.diagnosticDetailsGrid); this.RefreshDiagnosticDetails(); } this.AnalysisTabControl.SelectedTab = this.errorListTabPage; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void fileVariablesToolStripMenuItem_Click(object sender, EventArgs e) { string codeText = this.CodeBox.Text; HlslFileVariables fileVars = GetFileVars(); using (Form form = new Form()) { PropertyGrid grid = new PropertyGrid() { Dock = DockStyle.Fill, SelectedObject = fileVars, }; Button okButton = new Button() { Dock = DockStyle.Bottom, DialogResult = DialogResult.OK, Text = "OK" }; Button cancelButton = new Button() { DialogResult = DialogResult.Cancel, Text = "Cancel" }; form.Controls.Add(grid); form.Controls.Add(okButton); if (form.ShowDialog(this) == DialogResult.OK) { string newFirstLine = fileVars.ToString(); if (fileVars.SetFromText) { int firstEnd = codeText.IndexOf('\n'); if (firstEnd == 0) { codeText = "// " + fileVars.ToString(); } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText.Substring(firstEnd + 1); } } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText; } this.CodeBox.Text = codeText; } } } private void NewToolStripMenuItem_Click(object sender, EventArgs e) { if (!IsOKToOverwriteContent()) return; // Consider: using this a simpler File | New experience. //string psBanner = // "// -*- mode: hlsl; hlsl-entry: main; hlsl-target: ps_6_0; hlsl-args: /Zi; -*-\r\n"; //string simpleShader = // "float4 main() : SV_Target {\r\n return 1;\r\n}\r\n"; string shaderSample = "// -*- mode: hlsl; hlsl-entry: VSMain; hlsl-target: vs_6_0; hlsl-args: /Zi; -*-\r\n" + "struct PSInput {\r\n" + " float4 position : SV_POSITION;\r\n" + " float4 color : COLOR;\r\n" + "};\r\n" + "[RootSignature(\"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)\")]\r\n" + "PSInput VSMain(float4 position: POSITION, float4 color: COLOR) {\r\n" + " float aspect = 320.0 / 200.0;\r\n" + " PSInput result;\r\n" + " result.position = position;\r\n" + " result.position.y *= aspect;\r\n" + " result.color = color;\r\n" + " return result;\r\n" + "}\r\n" + "[RootSignature(\"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)\")]\r\n" + "float4 PSMain(PSInput input) : SV_TARGET {\r\n" + " return input.color;\r\n" + "}\r\n"; string xmlSample = "<ShaderOp PS='PS' VS='VS'>\r\n" + " <RootSignature>RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)</RootSignature>\r\n" + " <Resource Name='VBuffer' Dimension='BUFFER' Width='1024' Flags='ALLOW_UNORDERED_ACCESS' InitialResourceState='COPY_DEST' Init='FromBytes'>\r\n" + " { { 0.0f, 0.25f , 0.0f }, { 1.0f, 0.0f, 0.0f, 1.0f } },\r\n" + " { { 0.25f, -0.25f , 0.0f }, { 0.0f, 1.0f, 0.0f, 1.0f } },\r\n" + " { { -0.25f, -0.25f , 0.0f }, { 0.0f, 0.0f, 1.0f, 1.0f } }\r\n" + " </Resource>\r\n" + " <DescriptorHeap Name='RtvHeap' NumDescriptors='1' Type='RTV'>\r\n" + " </DescriptorHeap>\r\n" + " <InputElements>\r\n" + " <InputElement SemanticName='POSITION' Format='R32G32B32_FLOAT' AlignedByteOffset='0' />\r\n" + " <InputElement SemanticName='COLOR' Format='R32G32B32A32_FLOAT' AlignedByteOffset='12' />\r\n" + " </InputElements>\r\n" + " <Shader Name='VS' Target='vs_6_0' EntryPoint='VSMain' />\r\n" + " <Shader Name='PS' Target='ps_6_0' EntryPoint='PSMain' />\r\n" + "</ShaderOp>\r\n"; this.CodeBox.Text = shaderSample + "\r\n" + ShaderOpStartMarker + "\r\n" + xmlSample + ShaderOpStopMarker + "\r\n"; this.CodeBox.ClearUndo(); this.DocKind = DocumentKind.HlslText; this.DocFileName = null; this.DocModified = false; } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (this.DocKind == DocumentKind.CompiledObject) { throw new NotImplementedException(); } if (String.IsNullOrEmpty(this.DocFileName)) { saveAsToolStripMenuItem_Click(sender, e); return; } try { System.IO.File.WriteAllText(this.DocFileName, GetCodeWithFileVars()); } catch (System.IO.IOException) { this.mruManager.HandleFileFail(this.DocFileName); throw; } this.DocModified = false; this.mruManager.HandleFileSave(this.DocFileName); this.mruManager.SaveToFile(); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { using (SaveFileDialog dialog = new SaveFileDialog()) { dialog.DefaultExt = ".hlsl"; if (!String.IsNullOrEmpty(this.DocFileName)) dialog.FileName = this.DocFileName; dialog.Filter = "HLSL Files (*.hlsl)|*.hlsl|DXIL Files (*.ll)|*.ll|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; this.DocFileName = dialog.FileName; } System.IO.File.WriteAllText(this.DocFileName, GetCodeWithFileVars()); this.DocModified = false; } private void HandleOpenUI(string mruPath) { if (!IsOKToOverwriteContent()) return; if (mruPath == null) { // If not MRU, prompt for a path. using (OpenFileDialog dialog = new OpenFileDialog()) { dialog.DefaultExt = ".hlsl"; if (!String.IsNullOrEmpty(this.DocFileName)) dialog.FileName = this.DocFileName; dialog.Filter = "HLSL Files (*.hlsl)|*.hlsl|Compiled Shader Objects (*.cso;*.fxc)|*.cso;*.fxc|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; this.DocFileName = dialog.FileName; } } else { this.DocFileName = mruPath; } string ext = System.IO.Path.GetExtension(this.DocFileName).ToLowerInvariant(); if (ext == ".cso" || ext == ".fxc") { this.SelectedShaderBlob = this.Library.CreateBlobFromFile(this.DocFileName, IntPtr.Zero); this.DocKind = DocumentKind.CompiledObject; this.DisassembleSelectedShaderBlob(); } else { this.DocKind = (ext == ".ll") ? DocumentKind.AsmText : DocumentKind.HlslText; try { this.CodeBox.Text = System.IO.File.ReadAllText(this.DocFileName); } catch (System.IO.IOException) { this.mruManager.HandleFileFail(this.DocFileName); throw; } } this.DocModified = false; this.mruManager.HandleFileLoad(this.DocFileName); this.mruManager.SaveToFile(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { this.HandleOpenUI(null); } private void exportCompiledObjectToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show(this, "There is no compiled shader blob available for exporting."); return; } using (SaveFileDialog dialog = new SaveFileDialog()) { dialog.DefaultExt = ".cso"; if (!String.IsNullOrEmpty(this.DocFileName)) { dialog.FileName = this.DocFileName; if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.DocFileName))) { dialog.FileName += ".cso"; } } dialog.Filter = "Compiled Shader Object Files (*.cso;*.fxc)|*.cso;*.fxc|All Files (*.*)|*.*"; dialog.ValidateNames = true; if (dialog.ShowDialog(this) != DialogResult.OK) return; System.IO.File.WriteAllBytes(dialog.FileName, GetBytesFromBlob(this.SelectedShaderBlob)); } } private void quickFindToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase target = (this.DeepActiveControl as TextBoxBase); if (target == null) return; if (findDialog == null) { this.findDialog = new FindDialog(); this.findDialog.Disposed += (_sender, _e) => { this.findDialog = null; }; } if (target.SelectionLength < 128) this.findDialog.FindText = target.SelectedText; else this.findDialog.FindText = ""; this.findDialog.Target = target; if (this.findDialog.Visible) { this.findDialog.Focus(); } else { this.findDialog.Show(this); } } #endregion Menu item handlers. private static bool IsDxilTarget(string target) { // ps_6_0 // 012345 int major; if (target != null && target.Length == 6) if (Int32.TryParse(new string(target[3], 1), out major)) return major >= 6; if (target.StartsWith("lib")) if (Int32.TryParse(new string(target[4], 1), out major)) return major >= 6; return false; } private void CompileDocument() { this.DisassemblyTextBox.Font = this.CodeBox.Font; this.ASTDumpBox.Font = this.CodeBox.Font; SelectionHighlightData.ClearAnyFromRtb(this.CodeBox); var library = this.Library; // Switch modes. Can probably be better. DocumentKind localKind = this.DocKind; string text = null; if (localKind == DocumentKind.HlslText || this.DocKind == DocumentKind.AsmText) { text = this.CodeBox.Text; if (String.IsNullOrEmpty(text)) { return; } // Make some obvious changes. if (text[0] == ';') { localKind = DocumentKind.AsmText; } else if (text[0] == '/') { localKind = DocumentKind.HlslText; } } if (localKind == DocumentKind.HlslText) { var source = this.CreateBlobForText(text); string fileName = "hlsl.hlsl"; HlslFileVariables fileVars = GetFileVars(); bool isDxil = IsDxilTarget(fileVars.Target); IDxcCompiler compiler = isDxil ? HlslDxcLib.CreateDxcCompiler() : null; { string[] arguments = fileVars.Arguments; if (isDxil) { try { var result = compiler.Compile(source, fileName, fileVars.Entry, fileVars.Target, arguments, arguments.Length, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { this.SelectedShaderBlob = result.GetResult(); this.DisassembleSelectedShaderBlob(); } else { this.colorizationService.ClearColorization(this.DisassemblyTextBox); this.DisassemblyTextBox.Text = GetStringFromBlob(result.GetErrors()); } } catch (Exception e) { DisassemblyTextBox.Text = e.ToString(); } } else { this.colorizationService.ClearColorization(this.DisassemblyTextBox); IDxcBlob code, errorMsgs; uint flags = 0; const uint D3DCOMPILE_DEBUG = 1; if (fileVars.Arguments.Contains("/Zi")) flags = D3DCOMPILE_DEBUG; int hr = D3DCompiler.D3DCompiler.D3DCompile(text, text.Length, fileName, null, 0, fileVars.Entry, fileVars.Target, flags, 0, out code, out errorMsgs); if (hr != 0) { if (errorMsgs != null) { this.DisassemblyTextBox.Text = GetStringFromBlob(errorMsgs); } else { this.DisassemblyTextBox.Text = "Compilation filed with 0x" + hr.ToString("x"); } return; } IDxcBlob disassembly; unsafe { IntPtr buf = new IntPtr(code.GetBufferPointer()); hr = D3DCompiler.D3DCompiler.D3DDisassemble(buf, code.GetBufferSize(), 0, null, out disassembly); this.DisassemblyTextBox.Text = GetStringFromBlob(disassembly); } this.SelectedShaderBlob = code; } } // AST Dump - defer to avoid another parse pass pendingASTDump = () => { try { List<string> args = new List<string>(); args.Add("-ast-dump"); args.AddRange(tbOptions.Text.Split()); var result = compiler.Compile(source, fileName, fileVars.Entry, fileVars.Target, args.ToArray(), args.Count, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { this.ASTDumpBox.Text = GetStringFromBlob(result.GetResult()); } else { this.ASTDumpBox.Text = GetStringFromBlob(result.GetErrors()); } } catch (Exception e) { this.ASTDumpBox.Text = e.ToString(); } }; if (AnalysisTabControl.SelectedTab == ASTTabPage) { pendingASTDump(); pendingASTDump = null; } if (this.diagnosticDetailsGrid != null) { this.RefreshDiagnosticDetails(); } } else if (localKind == DocumentKind.CompiledObject) { this.CodeBox.Text = "Cannot compile a shader object."; return; } else if (localKind == DocumentKind.AsmText) { var source = this.CreateBlobForText(text); var assembler = HlslDxcLib.CreateDxcAssembler(); var result = assembler.AssembleToContainer(source); if (result.GetStatus() == 0) { this.SelectedShaderBlob = result.GetResult(); this.DisassembleSelectedShaderBlob(); // TODO: run validation on this shader blob } else { this.DisassemblyTextBox.Text = GetStringFromBlob(result.GetErrors()); } return; } } class RtbColorization { private RichTextBox rtb; private NumericRanges colored; private AsmColorizer colorizer; private string text; public RtbColorization(RichTextBox rtb, string text) { this.rtb = rtb; this.colorizer = new AsmColorizer(); this.text = text; this.colored = new NumericRanges(); } public void Start() { this.rtb.SizeChanged += Rtb_SizeChanged; this.rtb.HScroll += Rtb_SizeChanged; this.rtb.VScroll += Rtb_SizeChanged; this.ColorizeVisibleRegion(); } public void Stop() { this.rtb.SizeChanged -= Rtb_SizeChanged; this.rtb.HScroll -= Rtb_SizeChanged; this.rtb.VScroll -= Rtb_SizeChanged; } private void Rtb_SizeChanged(object sender, EventArgs e) { this.ColorizeVisibleRegion(); } private void ColorizeVisibleRegion() { int firstCharIdx = rtb.GetCharIndexFromPosition(new Point(0, 0)); firstCharIdx = rtb.GetFirstCharIndexFromLine(rtb.GetLineFromCharIndex(firstCharIdx)); int lastCharIdx = rtb.GetCharIndexFromPosition(new Point(rtb.ClientSize)); NumericRange visibleRange = new NumericRange(firstCharIdx, lastCharIdx + 1); if (this.colored.Contains(visibleRange)) { return; } var doc = GetTextDocument(rtb); using (new RichTextBoxEditAction(rtb)) { foreach (var idxRange in this.colored.ListGaps(visibleRange)) { this.colored.Add(idxRange); foreach (var range in this.colorizer.GetColorRanges(this.text, idxRange.Lo, idxRange.Hi - 1)) { if (range.RangeKind == AsmRangeKind.WS) continue; if (range.Start + range.Length < firstCharIdx) continue; if (lastCharIdx < range.Start) return; Color color; switch (range.RangeKind) { case AsmRangeKind.Comment: color = Color.DarkGreen; break; case AsmRangeKind.LLVMTypeName: case AsmRangeKind.Keyword: case AsmRangeKind.Instruction: color = Color.Blue; break; case AsmRangeKind.StringConstant: color = Color.DarkRed; break; case AsmRangeKind.Metadata: color = Color.DarkOrange; break; default: color = Color.Black; break; } SetStartLengthColor(doc, range.Start, range.Length, color); } } } } } class RtbColorizationService { private Dictionary<RichTextBox, RtbColorization> instances = new Dictionary<RichTextBox, RtbColorization>(); public void ClearColorization(RichTextBox rtb) { SetColorization(rtb, null); } public void SetColorization(RichTextBox rtb, RtbColorization colorization) { RtbColorization existing; if (instances.TryGetValue(rtb, out existing) && existing != null) { existing.Stop(); } instances[rtb] = colorization; if (colorization != null) colorization.Start(); } } RtbColorizationService colorizationService = new RtbColorizationService(); private void DisassembleSelectedShaderBlob() { this.DisassemblyTextBox.Font = this.CodeBox.Font; var compiler = HlslDxcLib.CreateDxcCompiler(); try { var dis = compiler.Disassemble(this.SelectedShaderBlob); string disassemblyText = GetStringFromBlob(dis); RichTextBox rtb = this.DisassemblyTextBox; this.DisassemblyTextBox.Text = disassemblyText; this.colorizationService.SetColorization(rtb, new RtbColorization(rtb, disassemblyText)); } catch (Exception e) { this.DisassemblyTextBox.Text = "Unable to disassemble selected shader.\r\n" + e.ToString(); } } private void HandleException(Exception exception) { HandleException(exception, "Exception " + exception.GetType().Name); } private void HandleException(Exception exception, string caption) { MessageBox.Show(this, exception.ToString(), caption); } private static Dictionary<string, string> ParseFirstLineOptions(string line) { Dictionary<string, string> result = new Dictionary<string, string>(); int start = line.IndexOf("-*-"); if (start < 0) return result; int end = line.IndexOf("-*-", start + 3); if (end < 0) return result; string[] nameValuePairs = line.Substring(start + 3, (end - start - 3)).Split(';'); foreach (string pair in nameValuePairs) { int separator = pair.IndexOf(':'); if (separator < 0) continue; string name = pair.Substring(0, separator).Trim(); string value = pair.Substring(separator + 1).Trim(); result[name] = value; } return result; } class HlslFileVariables { [Description("Editing mode for the file, typically hlsl")] public string Mode { get; set; } [Description("Name of the entry point function")] public string Entry { get; set; } [Description("Shader model target")] public string Target { get; set; } [Description("Arguments for compilation")] public string[] Arguments { get; set; } [Description("Whether the variables where obtained from the text file")] public bool SetFromText { get; private set; } public static HlslFileVariables FromText(string text) { HlslFileVariables result = new HlslFileVariables(); int lineEnd = text.IndexOf('\n'); if (lineEnd > 0) text = text.Substring(0, lineEnd); Dictionary<string, string> options = ParseFirstLineOptions(text); result.SetFromText = options.Count > 0; result.Mode = GetValueOrDefault(options, "mode", "hlsl"); result.Entry = GetValueOrDefault(options, "hlsl-entry", "main"); result.Target = GetValueOrDefault(options, "hlsl-target", "ps_6_0"); result.Arguments = GetValueOrDefault(options, "hlsl-args", "").Split(' ').Select(a => a.Trim()).ToArray(); return result; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("-*- "); sb.AppendFormat("mode: {0}; ", this.Mode); sb.AppendFormat("hlsl-entry: {0}; ", this.Entry); sb.AppendFormat("hlsl-target: {0}; ", this.Target); if (this.Arguments.Length > 0) { sb.AppendFormat("hlsl-args: {0}; ", String.Join(" ", this.Arguments)); } sb.Append("-*-"); return sb.ToString(); } } internal bool AutoDisassemble { get { return this.autoDisassemble; } set { this.autoDisassemble = value; this.autoUpdateToolStripMenuItem.Checked = value; if (value) { this.CompileDocument(); } } } private void UpdateWindowText() { string text = ""; if (this.DocModified) text = "* "; if (!String.IsNullOrEmpty(this.DocFileName)) { text += System.IO.Path.GetFileName(this.DocFileName); } else { text += "Untitled"; } text += " - " + AppName; this.Text = text; } internal DocumentKind DocKind { get { return this.documentKind; } set { this.documentKind = value; switch (value) { case DocumentKind.AsmText: this.CodeBox.Enabled = true; break; case DocumentKind.HlslText: this.CodeBox.Enabled = true; break; case DocumentKind.CompiledObject: this.CodeBox.Enabled = false; break; } } } internal string DocFileName { get { return this.docFileName; } set { this.docFileName = value; this.UpdateWindowText(); } } internal bool DocModified { get { return this.docModified; } set { if (this.docModified != value) { this.docModified = value; this.UpdateWindowText(); } } } internal IDxcLibrary Library { get { return (library ?? (library = HlslDxcLib.CreateDxcLibrary())); } } internal bool ShowCodeColor { get { return ColorMenuItem.Checked; } set { ColorMenuItem.Checked = value; } } internal bool ShowReferences { get { return ColorMenuItem.Checked; } set { ColorMenuItem.Checked = value; } } internal IDxcTranslationUnit GetTU() { if (this.lastTU == null) { if (this.isense == null) { this.isense = HlslDxcLib.CreateDxcIntelliSense(); } this.lastIndex = this.isense.CreateIndex(); IDxcUnsavedFile[] unsavedFiles = new IDxcUnsavedFile[] { new TrivialDxcUnsavedFile("hlsl.hlsl", this.CodeBox.Text) }; HlslFileVariables fileVars = GetFileVars(); this.lastTU = this.lastIndex.ParseTranslationUnit("hlsl.hlsl", fileVars.Arguments, fileVars.Arguments.Length, unsavedFiles, (uint)unsavedFiles.Length, (uint)DxcTranslationUnitFlags.DxcTranslationUnitFlags_UseCallerThread); } return this.lastTU; } private HlslFileVariables GetFileVars() { HlslFileVariables fileVars = HlslFileVariables.FromText(this.CodeBox.Text); if (fileVars.SetFromText) { tbEntry.Text = fileVars.Entry; cbProfile.Text = fileVars.Target; tbOptions.Text = string.Join(" ", fileVars.Arguments); } else { fileVars.Arguments = tbOptions.Text.Split(); fileVars.Entry = tbEntry.Text; fileVars.Target = cbProfile.Text; } return fileVars; } private string GetCodeWithFileVars() { HlslFileVariables fileVars = GetFileVars(); string codeText = CodeBox.Text; if (fileVars.SetFromText) { int firstEnd = codeText.IndexOf('\n'); if (firstEnd == 0) { codeText = "// " + fileVars.ToString(); } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText.Substring(firstEnd + 1); } } else { codeText = "// " + fileVars.ToString() + "\r\n" + codeText; } return codeText; } internal void InvalidateTU() { this.lastTU = null; this.lastIndex = null; this.pendingASTDump = null; } private IDxcBlobEncoding CreateBlobForCodeText() { return CreateBlobForText(this.CodeBox.Text); } private IDxcBlobEncoding CreateBlobForText(string text) { return CreateBlobForText(this.Library, text); } public static IDxcBlobEncoding CreateBlobForText(IDxcLibrary library, string text) { if (String.IsNullOrEmpty(text)) { return null; } const UInt32 CP_UTF16 = 1200; var source = library.CreateBlobWithEncodingOnHeapCopy(text, (UInt32)(text.Length * 2), CP_UTF16); return source; } private void CodeBox_SelectionChanged(object sender, System.EventArgs e) { if (!this.ShowReferences && !this.ShowCodeColor) { return; } IDxcTranslationUnit tu = this.GetTU(); if (tu == null) { return; } RichTextBox rtb = this.CodeBox; SelectionHighlightData data = SelectionHighlightData.FromRtb(rtb); int start = this.CodeBox.SelectionStart; if (this.ShowReferences && rtb.SelectionLength > 0) { return; } var doc = GetTextDocument(rtb); var mainFile = tu.GetFile(tu.GetFileName()); using (new RichTextBoxEditAction(rtb)) { data.ClearFromRtb(rtb); if (this.ShowCodeColor) { // Basic tokenization. IDxcToken[] tokens; uint tokenCount; IDxcSourceRange range = this.isense.GetRange( tu.GetLocationForOffset(mainFile, 0), tu.GetLocationForOffset(mainFile, (uint)this.CodeBox.TextLength)); tu.Tokenize(range, out tokens, out tokenCount); if (tokens != null) { foreach (var t in tokens) { switch (t.GetKind()) { case DxcTokenKind.Keyword: uint line, col, offset, endOffset; IDxcFile file; t.GetLocation().GetSpellingLocation(out file, out line, out col, out offset); t.GetExtent().GetEnd().GetSpellingLocation(out file, out line, out col, out endOffset); SetStartLengthColor(doc, (int)offset, (int)(endOffset - offset), Color.Blue); break; } } } } if (this.ShowReferences) { var loc = tu.GetLocationForOffset(mainFile, (uint)start); var locCursor = tu.GetCursorForLocation(loc); uint resultLength; IDxcCursor[] cursors; locCursor.FindReferencesInFile(mainFile, 0, 100, out resultLength, out cursors); for (int i = 0; i < cursors.Length; ++i) { uint startOffset, endOffset; GetRangeOffsets(cursors[i].GetExtent(), out startOffset, out endOffset); data.Add((int)startOffset, (int)(endOffset - startOffset)); } data.ApplyToRtb(rtb, Color.LightGray); this.TheStatusStripLabel.Text = locCursor.GetCursorKind().ToString(); } } } private static void GetRangeOffsets(IDxcSourceRange range, out uint start, out uint end) { IDxcSourceLocation l; IDxcFile file; uint line, col; l = range.GetStart(); l.GetSpellingLocation(out file, out line, out col, out start); l = range.GetEnd(); l.GetSpellingLocation(out file, out line, out col, out end); } private void CodeBox_TextChanged(object sender, EventArgs e) { if (this.DocKind == DocumentKind.CompiledObject) return; if (e != null) this.DocModified = true; this.InvalidateTU(); if (this.AutoDisassemble) this.CompileDocument(); } private string GetStringFromBlob(IDxcBlob blob) { return GetStringFromBlob(this.Library, blob); } public static string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob) { unsafe { blob = library.GetBlobAstUf16(blob); return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2)); } } private byte[] GetBytesFromBlob(IDxcBlob blob) { unsafe { byte* pMem = (byte*)blob.GetBufferPointer(); uint size = blob.GetBufferSize(); byte[] result = new byte[size]; fixed (byte* pTarget = result) { for (uint i = 0; i < size; ++i) pTarget[i] = pMem[i]; } return result; } } private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.SelectAll(); return; } } private void undoToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Undo(); return; } } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Cut(); return; } } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.Copy(); return; } ListBox lb = this.DeepActiveControl as ListBox; if (lb != null) { if (lb.SelectedItems.Count > 0) { string content; if (lb.SelectedItems.Count == 1) { content = lb.SelectedItem.ToString(); } else { StringBuilder sb = new StringBuilder(); foreach (var item in lb.SelectedItems) { sb.AppendLine(item.ToString()); } content = sb.ToString(); } Clipboard.SetText(content, TextDataFormat.UnicodeText); } return; } } private Control DeepActiveControl { get { Control result = this; while (result is IContainerControl) { result = ((IContainerControl)result).ActiveControl; } return result; } } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { RichTextBox rtb = this.DeepActiveControl as RichTextBox; if (rtb != null) { // Handle the container format. if (Clipboard.ContainsData(ContainerData.DataFormat.Name)) { object o = Clipboard.GetData(ContainerData.DataFormat.Name); rtb.SelectedText = ContainerData.DataObjectToString(o); } else { rtb.Paste(DataFormats.GetFormat(DataFormats.UnicodeText)); } return; } TextBoxBase tb = this.ActiveControl as TextBoxBase; if (tb != null) { tb.Paste(); return; } } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { TextBoxBase tb = this.DeepActiveControl as TextBoxBase; if (tb != null) { tb.SelectedText = ""; return; } } private void goToToolStripMenuItem_Click(object sender, EventArgs e) { int lastIndex = this.CodeBox.TextLength; int lastLine = this.CodeBox.GetLineFromCharIndex(lastIndex - 1); int currentLine = this.CodeBox.GetLineFromCharIndex(this.CodeBox.SelectionStart); using (GoToDialog dialog = new GoToDialog()) { dialog.MaxLineNumber = lastLine + 1; dialog.LineNumber = currentLine + 1; if (dialog.ShowDialog(this) == DialogResult.OK) { this.CodeBox.Select(this.CodeBox.GetFirstCharIndexFromLine(dialog.LineNumber - 1), 0); } } } private void ResetDefaultPassesButton_Click(object sender, EventArgs e) { this.ResetDefaultPasses(); } private static bool IsDisassemblyTokenChar(char c) { return char.IsLetterOrDigit(c) || c == '@' || c == '%' || c == '$'; } private static bool IsTokenLeftBoundary(string text, int i) { // Whether there is a token boundary between text[i] and text[i-1]. if (i == 0) return true; if (i >= text.Length - 1) return true; char cPrior = text[i - 1]; char c = text[i]; return !IsDisassemblyTokenChar(cPrior) && IsDisassemblyTokenChar(c); } private static bool IsTokenRightBoundary(string text, int i) { if (i == 0) return true; if (i >= text.Length - 1) return true; char cPrior = text[i - 1]; char c = text[i]; return IsDisassemblyTokenChar(cPrior) && !IsDisassemblyTokenChar(c); } private static int ColorToCOLORREF(Color value) { // 0x00bbggrr. int result = value.R | (value.G << 8) | (value.B << 16); return result; } private static Tom.ITextRange SetStartLengthColor(Tom.ITextDocument doc, int start, int length, Color color) { Tom.ITextRange range = doc.Range(start, start + length); Tom.ITextFont font = range.Font; font.ForeColor = ColorToCOLORREF(color); return range; } private static void SetStartLengthBackColor(Tom.ITextRange range, Color color) { Tom.ITextFont font = range.Font; font.BackColor = ColorToCOLORREF(color); } private static Tom.ITextRange SetStartLengthBackColor(Tom.ITextDocument doc, int start, int length, Color color) { Tom.ITextRange range = doc.Range(start, start + length); SetStartLengthBackColor(range, color); return range; } private static Regex dbgLineRegEx; private static Regex DbgLineRegEx { get { return (dbgLineRegEx = dbgLineRegEx ?? new Regex(@"line: (\d+)")); } } private static Regex dbgColRegEx; private static Regex DbgColRegEx { get { return (dbgColRegEx = dbgColRegEx ?? new Regex(@"column: (\d+)")); } } private static void HandleDebugMetadata(string dbgLine, RichTextBox sourceBox) { Match lineMatch = DbgLineRegEx.Match(dbgLine); if (!lineMatch.Success) { return; } int lineVal = Int32.Parse(lineMatch.Groups[1].Value) - 1; int targetStart = sourceBox.GetFirstCharIndexFromLine(lineVal); int targetEnd = sourceBox.GetFirstCharIndexFromLine(lineVal + 1); Match colMatch = DbgColRegEx.Match(dbgLine); if (colMatch.Success) { targetStart += Int32.Parse(colMatch.Groups[1].Value) - 1; } var highlights = SelectionHighlightData.FromRtb(sourceBox); highlights.ClearFromRtb(sourceBox); highlights.Add(targetStart, targetEnd - targetStart); highlights.ApplyToRtb(sourceBox, Color.Yellow); sourceBox.SelectionStart = targetStart; sourceBox.ScrollToCaret(); } private static void HandleDebugTokenOnDisassemblyLine(RichTextBox rtb, RichTextBox sourceBox) { // Get the line. string[] lines = rtb.Lines; string line = lines[rtb.GetLineFromCharIndex(rtb.SelectionStart)]; Regex re = new Regex(@"!dbg !(\d+)"); Match m = re.Match(line); if (!m.Success) { return; } string val = m.Groups[1].Value; int dbgMetadata = Int32.Parse(val); for (int dbgLineIndex = lines.Length - 1; dbgLineIndex >= 0;) { string dbgLine = lines[dbgLineIndex]; if (dbgLine.StartsWith("!")) { int dbgIdx = Int32.Parse(dbgLine.Substring(1, dbgLine.IndexOf(' ') - 1)); if (dbgIdx == dbgMetadata) { HandleDebugMetadata(dbgLine, sourceBox); return; } else if (dbgIdx < dbgMetadata) { return; } else { dbgLineIndex -= (dbgIdx - dbgMetadata); } } else { --dbgLineIndex; } } } public static void HandleCodeSelectionChanged(RichTextBox rtb, RichTextBox sourceBox) { SelectionHighlightData data = SelectionHighlightData.FromRtb(rtb); SelectionExpandResult expand = SelectionExpandResult.Expand(rtb); if (expand.IsEmpty) return; string token = expand.Token; if (sourceBox != null && token == "dbg") { HandleDebugTokenOnDisassemblyLine(rtb, sourceBox); } if (data.SelectedToken == token) return; string text = expand.Text; // OK, time to do work. using (new RichTextBoxEditAction(rtb)) { data.SelectedToken = token; data.ClearFromRtb(rtb); int match = text.IndexOf(token); while (match != -1) { data.Add(match, token.Length); match += token.Length; match = text.IndexOf(token, match); } data.ApplyToRtb(rtb, Color.LightPink); } } private void DisassemblyTextBox_SelectionChanged(object sender, EventArgs e) { HandleCodeSelectionChanged((RichTextBox)sender, this.CodeBox); } private string PassToPassString(IDxcOptimizerPass pass) { return pass.GetOptionName() + OptDescSeparator + pass.GetDescription(); } private string PassStringToBanner(string value) { int separator = value.IndexOf(OptDescSeparator); if (separator >= 0) value = value.Substring(0, separator); return value; } private static string PassStringToOption(string value) { int separator = value.IndexOf(OptDescSeparator); if (separator >= 0) value = value.Substring(0, separator); return "-" + value; } private void AnalysisTabControl_Selecting(object sender, TabControlCancelEventArgs e) { if (e.TabPage == this.OptimizerTabPage) { if (passesLoaded) { return; } this.ResetDefaultPasses(); } if (e.TabPage == this.ASTTabPage) { if (pendingASTDump != null) { pendingASTDump(); pendingASTDump = null; } } } private void ResetDefaultPasses() { IDxcOptimizer opt = HlslDxcLib.CreateDxcOptimizer(); if (!this.passesLoaded) { int passCount = opt.GetAvailablePassCount(); PassInfo[] localInfos = new PassInfo[passCount]; for (int i = 0; i < passCount; ++i) { localInfos[i] = PassInfo.FromOptimizerPass(opt.GetAvailablePass(i)); } localInfos = localInfos.OrderBy(p => p.Name).ToArray(); this.passInfos = localInfos.ToList(); this.AvailablePassesBox.Items.AddRange(localInfos); this.passesLoaded = true; } List<string> args; try { HlslFileVariables fileVars = GetFileVars(); args = fileVars.Arguments.Where(a => !String.IsNullOrWhiteSpace(a)).ToList(); } catch (Exception) { args = new List<string>() { "/Od" }; } args.Add("/Odump"); IDxcCompiler compiler = HlslDxcLib.CreateDxcCompiler(); IDxcOperationResult optDumpResult = compiler.Compile(CreateBlobForText("[RootSignature(\"\")]float4 main() : SV_Target { return 0; }"), "hlsl.hlsl", "main", "ps_6_0", args.ToArray(), args.Count, null, 0, null); IDxcBlob optDumpBlob = optDumpResult.GetResult(); string optDumpText = GetStringFromBlob(optDumpBlob); this.AddSelectedPassesFromText(optDumpText, true); } private void AddSelectedPassesFromText(string optDumpText, bool replace) { List<object> defaultPasses = new List<object>(); foreach (string line in optDumpText.Split('\n')) { if (line.StartsWith("#")) continue; string lineTrim = line.Trim(); if (String.IsNullOrEmpty(lineTrim)) continue; lineTrim = line.TrimStart('-'); int argSepIndex = lineTrim.IndexOf(','); string passName = argSepIndex > 0 ? lineTrim.Substring(0, argSepIndex) : lineTrim; PassInfo passInfo = this.passInfos.FirstOrDefault(p => p.Name == passName); if (passInfo == null) { defaultPasses.Add(lineTrim); continue; } PassInfoWithValues passWithValues = new PassInfoWithValues(passInfo); if (argSepIndex > 0) { bool problemFound = false; string[] parts = lineTrim.Split(','); for (int i = 1; i < parts.Length; ++i) { string[] nameValue = parts[i].Split('='); PassArgInfo argInfo = passInfo.Args.FirstOrDefault(a => a.Name == nameValue[0]); if (argInfo == null) { problemFound = true; break; } passWithValues.Values.Add(new PassArgValueInfo() { Arg = argInfo, Value = (nameValue.Length == 1) ? null : nameValue[1] }); } if (problemFound) { defaultPasses.Add(lineTrim); continue; } } defaultPasses.Add(passWithValues); } if (replace) { this.SelectedPassesBox.Items.Clear(); } this.SelectedPassesBox.Items.AddRange(defaultPasses.ToArray()); } public static string[] CreatePassOptions(IEnumerable<string> passes, bool analyze, bool printAll) { List<string> result = new List<string>(); if (analyze) result.Add("-analyze"); if (printAll) result.Add("-print-module:start"); bool inOptFn = false; foreach (var itemText in passes) { result.Add(PassStringToOption(itemText)); if (itemText == "opt-fn-passes") { inOptFn = true; } else if (itemText.StartsWith("opt-") && itemText.EndsWith("-passes")) { inOptFn = false; } if (printAll && !inOptFn) { result.Add("-hlsl-passes-pause"); result.Add("-print-module:" + itemText); } } return result.ToArray(); } private string[] CreatePassOptions(bool analyze, bool printAll) { return CreatePassOptions(this.SelectedPassesBox.Items.ToStringEnumerable(), analyze, printAll); } private void RunPassesButton_Click(object sender, EventArgs e) { // TODO: consider accepting DXIL in the code editor as well // Do a high-level only compile. HighLevelCompileResult compile = RunHighLevelCompile(); if (compile.Blob == null) { MessageBox.Show("Failed to compile: " + compile.ResultText); return; } string[] options = CreatePassOptions(this.AnalyzeCheckBox.Checked, false); OptimizeResult opt = RunOptimize(this.Library, options, compile.Blob); if (!opt.Succeeded) { MessageBox.Show("Failed to optimize: " + opt.ResultText); return; } Form form = new Form(); RichTextBox rtb = new RichTextBox(); LogContextMenuHelper helper = new LogContextMenuHelper(rtb); rtb.Dock = DockStyle.Fill; rtb.Font = this.CodeBox.Font; rtb.ContextMenu = new ContextMenu( new MenuItem[] { new MenuItem("Show Graph", helper.ShowGraphClick) }); rtb.SelectionChanged += DisassemblyTextBox_SelectionChanged; rtb.Text = opt.ResultText; form.Controls.Add(rtb); form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } private void SelectPassUpButton_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; if (selectedIndex == -1 || selectedIndex == 0) return; object o = lb.Items[selectedIndex - 1]; lb.Items.RemoveAt(selectedIndex - 1); lb.Items.Insert(selectedIndex, o); } private void SelectPassDownButton_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; if (selectedIndex == -1 || selectedIndex == lb.Items.Count - 1) return; object o = lb.Items[selectedIndex + 1]; lb.Items.RemoveAt(selectedIndex + 1); lb.Items.Insert(selectedIndex, o); } private void AvailablePassesBox_DoubleClick(object sender, EventArgs e) { ListBox lb = (ListBox)sender; if (lb.SelectedItems.Count == 0) return; foreach (var item in lb.SelectedItems) this.SelectedPassesBox.Items.Add(new PassInfoWithValues((PassInfo)item)); } private void SelectedPassesBox_DoubleClick(object sender, EventArgs e) { for (int x = SelectedPassesBox.SelectedIndices.Count - 1; x >= 0; x--) { int idx = SelectedPassesBox.SelectedIndices[x]; SelectedPassesBox.Items.RemoveAt(idx); } } private void AddPrintModuleButton_Click(object sender, EventArgs e) { // Known, very handy. this.SelectedPassesBox.Items.Add("print-module" + OptDescSeparator + "Print module to stderr"); } private void SelectedPassesBox_KeyUp(object sender, KeyEventArgs e) { ListBox lb = (ListBox)sender; if (e.KeyCode == Keys.Delete) { for (int x = SelectedPassesBox.SelectedIndices.Count - 1; x >= 0; x--) { int idx = SelectedPassesBox.SelectedIndices[x]; SelectedPassesBox.Items.RemoveAt(idx); } e.Handled = true; return; } } private void autoUpdateToolStripMenuItem_Click(object sender, EventArgs e) { this.AutoDisassemble = !this.AutoDisassemble; } private static string GetValueOrDefault(Dictionary<string, string> d, string name, string defaultValue) { string result; if (!d.TryGetValue(name, out result)) result = defaultValue; return result; } /// <summary>Helper class to handle the context menu of operations log.</summary> public class LogContextMenuHelper { public RichTextBox Rtb { get; set; } public LogContextMenuHelper(RichTextBox rtb) { this.Rtb = rtb; } public void ShowGraphClick(object sender, EventArgs e) { SelectionExpandResult s = SelectionExpandResult.Expand(this.Rtb); if (s.IsEmpty) return; if (s.Token == "digraph") { int nextStart = s.Text.IndexOf('{', s.SelectionEnd); if (nextStart < 0) return; int closing = FindBalanced('{', '}', s.Text, nextStart); if (closing < 0) return; // See file history for a version that inserted the image in-line with graph. // The svg/web browser approach provides zooming and more interactivity. string graphText = s.Text.Substring(s.SelectionStart, closing - s.SelectionStart); ShowDot(graphText); } } static public void ShowDot(string graphText) { string path = System.IO.Path.GetTempFileName(); string outPath = path + ".svg"; try { System.IO.File.WriteAllText(path, graphText); string svgData = RunDot(path, DotOutFormat.Svg, null); Form browserForm = new Form(); TrackBar zoomControl = new TrackBar(); zoomControl.Minimum = 10; zoomControl.Maximum = 400; zoomControl.Value = 100; zoomControl.Dock = DockStyle.Top; zoomControl.Text = "zoom"; WebBrowser browser = new WebBrowser(); browser.Dock = DockStyle.Fill; browser.DocumentText = svgData; browserForm.Controls.Add(browser); browserForm.Controls.Add(zoomControl); zoomControl.ValueChanged += (_, __) => { if (browser.Document != null && browser.Document.DomDocument != null) { dynamic o = browser.Document.DomDocument; o.documentElement.style.zoom = String.Format("{0}%", zoomControl.Value); } }; browserForm.Text = "graph"; browserForm.Show(); } catch (DotProgram.CannotFindDotException cfde) { MessageBox.Show(cfde.Message, "Unable to find dot.exe", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { DeleteIfExists(path); } } internal static void DeleteIfExists(string path) { if (System.IO.File.Exists(path)) System.IO.File.Delete(path); } internal static string RunDot(string inputFile, DotOutFormat format, string outFile) { DotProgram program = new DotProgram(); program.InFilePath = inputFile; program.OutFilePath = outFile; program.OutFormat = format; return program.StartAndWaitForExit(); } internal static int FindBalanced(char open, char close, string text, int start) { // return exclusive end System.Diagnostics.Debug.Assert(text[start] == open); int level = 1; int result = start + 1; int end = text.Length; while (result < end && level != 0) { if (text[result] == open) level++; if (text[result] == close) level--; result++; } return (result == end) ? -1 : result; } } internal enum DotOutFormat { Svg, Png } class DotProgram { private string fileName; private Dictionary<string, string> options; internal class CannotFindDotException : InvalidOperationException { internal CannotFindDotException(string message) : base(message) { } } public DotProgram() { this.options = new Dictionary<string, string>(); this.options["-Nfontname"] = "Consolas"; this.options["-Efontname"] = "Tahoma"; } public static IEnumerable<string> DotFileNameCandidates() { // Look in a few known places. string path = Environment.GetEnvironmentVariable("PATH"); string[] partPaths = path.Split(';'); foreach (var partPath in partPaths) { yield return System.IO.Path.Combine(partPath, "bin\\dot.exe"); } string progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (!String.IsNullOrEmpty(progPath)) { yield return System.IO.Path.Combine(progPath, "Graphviz2.38\\bin\\dot.exe"); } progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); yield return System.IO.Path.Combine(progPath, "Graphviz2.38\\bin\\dot.exe"); } public static string FindDotFileName() { StringBuilder sb = new StringBuilder(); sb.AppendLine("Cannot find dot.exe in any of these locations."); foreach (string result in DotFileNameCandidates()) { sb.AppendLine(result); if (System.IO.File.Exists(result)) return result; } throw new CannotFindDotException(sb.ToString()); } public string BuildArguments() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("-T{0}", this.OutFormat.ToString().ToLowerInvariant()); foreach (var pair in this.Options) { sb.AppendFormat(" {0}={1}", pair.Key, pair.Value); } if (!String.IsNullOrEmpty(this.OutFilePath)) { sb.AppendFormat(" -o{0}", this.OutFilePath); } sb.AppendFormat(" {0}", this.InFilePath); return sb.ToString(); } public string FileName { get { if (String.IsNullOrEmpty(this.fileName)) { this.fileName = FindDotFileName(); } return this.fileName; } set { this.fileName = value; } } public string InFilePath { get; set; } public IDictionary<string, string> Options { get { return this.options; } } public string OutFilePath { get; set; } public DotOutFormat OutFormat { get; set; } public System.Diagnostics.Process Start() { System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(this.FileName, this.BuildArguments()); psi.CreateNoWindow = true; psi.RedirectStandardOutput = String.IsNullOrEmpty(this.OutFilePath); psi.UseShellExecute = false; return System.Diagnostics.Process.Start(psi); } public string StartAndWaitForExit() { using (System.Diagnostics.Process p = this.Start()) { string result = p.StandardOutput.ReadToEnd(); p.WaitForExit(); int code = p.ExitCode; if (code > 0) { throw new Exception("dot.exe failed with code " + code); } return result; } } } /// <summary>Helper class to expand a short selection into something more useful.</summary> class SelectionExpandResult { public int SelectionStart { get; set; } public int SelectionEnd { get; set; } public string Text { get; set; } public string Token { get; set; } public bool IsEmpty { get { return SelectionEnd - 1 == SelectionStart; } } internal static SelectionExpandResult Empty() { return new SelectionExpandResult() { SelectionStart = 0, SelectionEnd = 1 }; } internal static SelectionExpandResult Expand(RichTextBox rtb) { string text = rtb.Text; int selStart = rtb.SelectionStart; int selLength = rtb.SelectionLength; int tokenStart = selStart; int tokenEnd = selStart; if (tokenStart < text.Length && !char.IsLetterOrDigit(text[tokenStart])) return Empty(); // check last token case tokenEnd++; // it's a letter or digit, so it's at least one offset while (tokenStart > 0 && !IsTokenLeftBoundary(text, tokenStart)) tokenStart--; while (tokenEnd < text.Length && !IsTokenRightBoundary(text, tokenEnd)) tokenEnd++; if (tokenEnd - 1 == tokenStart) return Empty(); string token = text.Substring(tokenStart, tokenEnd - tokenStart); return new SelectionExpandResult() { SelectionEnd = tokenEnd, SelectionStart = tokenStart, Text = text, Token = token }; } } /// <summary>Helper class to record editor highlights.</summary> class SelectionHighlightData { public static SelectionHighlightData FromRtb(RichTextBox rtb) { SelectionHighlightData result = (SelectionHighlightData)rtb.Tag; if (result == null) { result = new SelectionHighlightData(); rtb.Tag = result; } return result; } public static void ClearAnyFromRtb(RichTextBox rtb) { SelectionHighlightData data = (SelectionHighlightData)rtb.Tag; if (data != null) data.ClearFromRtb(rtb); } public void Add(int start, int length) { this.StartLengthHighlights.Add(new Tuple<int, int>(start, length)); } public void ApplyToRtb(RichTextBox rtb, Color color) { Tom.ITextDocument doc = GetTextDocument(rtb); foreach (var pair in this.StartLengthHighlights) { this.HighlightRanges.Add(SetStartLengthBackColor(doc, pair.Item1, pair.Item2, color)); } } public void ClearFromRtb(RichTextBox rtb) { Tom.ITextDocument doc = GetTextDocument(rtb); for (int i = 0; i < this.HighlightRanges.Count; ++i) { SetStartLengthBackColor(HighlightRanges[i], rtb.BackColor); } this.StartLengthHighlights.Clear(); this.HighlightRanges.Clear(); } private List<Tom.ITextRange> HighlightRanges = new List<Tom.ITextRange>(); public List<Tuple<int, int>> StartLengthHighlights = new List<Tuple<int, int>>(); public string SelectedToken; } [System.Runtime.InteropServices.Guid("00020d00-0000-0000-c000-000000000046")] interface IRichEditOle { } private const int WM_USER = 0x0400; private const int EM_GETOLEINTERFACE = (WM_USER + 60); [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref IRichEditOle lParam); internal static Tom.ITextDocument GetTextDocument(RichTextBox rtb) { IRichEditOle ole = null; SendMessage(rtb.Handle, EM_GETOLEINTERFACE, IntPtr.Zero, ref ole); return ole as Tom.ITextDocument; } /// <summary>Helper class to suppress events and restore selection.</summary> class RichTextBoxEditAction : IDisposable { private const int EM_SETEVENTMASK = (WM_USER + 69); private const int EM_GETSCROLLPOS = (WM_USER + 221); private const int EM_SETSCROLLPOS = (WM_USER + 222); private const int WM_SETREDRAW = 0x0b; private RichTextBox rtb; private bool readOnly; private IntPtr eventMask; [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [System.Runtime.InteropServices.DllImport( "user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Point lParam); internal RichTextBoxEditAction(RichTextBox rtb) { this.rtb = rtb; this.readOnly = rtb.ReadOnly; this.eventMask = (IntPtr)SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero); SendMessage(rtb.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); this.rtb.ReadOnly = false; } public void Dispose() { SendMessage(rtb.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, this.eventMask); this.rtb.ReadOnly = this.readOnly; } } private void SelectNodeWithOffset(TreeView view, TreeNode node, int offset) { bool foundBetter; do { foundBetter = false; foreach (TreeNode child in node.Nodes) { TreeNodeRange r = child.Tag as TreeNodeRange; if (r != null && r.Contains(offset)) { node = child; foundBetter = true; break; } } } while (foundBetter); view.SelectedNode = node; } private void bitstreamToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show(this, "No shader blob selected. Try compiling a file."); return; } DisplayBitstream(ContainerData.BlobToBytes(this.SelectedShaderBlob), "Bitstream Viewer - Selected Shader"); } private void bitstreamFromClipboardToolStripMenuItem_Click(object sender, EventArgs e) { if (!Clipboard.ContainsData(ContainerData.DataFormat.Name)) { MessageBox.Show(this, "No shader blob on clipboard. Try pasting from the optimizer view."); return; } DisplayBitstream(ContainerData.DataObjectToBytes(Clipboard.GetData(ContainerData.DataFormat.Name)), "Bitstream Viewer - Clipboard"); } private void DisplayBitstream(byte[] bytes, string title) { StatusBar statusBar = new StatusBar(); statusBar.Dock = DockStyle.Bottom; BinaryViewControl binaryView = new BinaryViewControl(); TreeView treeView = new TreeView(); treeView.Dock = DockStyle.Fill; treeView.AfterSelect += (eSender, treeViewEventArgs) => { TreeNodeRange r = treeViewEventArgs.Node.Tag as TreeNodeRange; if (r == null) { binaryView.SetSelection(0, 0); statusBar.ResetText(); } else { binaryView.SetSelection(r.Offset, r.Length); statusBar.Text = String.Format("Bits {0}-{1} (length {2})", r.Offset, r.Offset + r.Length, r.Length); } }; BuildBitstreamNodes(bytes, treeView.Nodes); binaryView.BitClick += (eSender, bitArgs) => { int offset = bitArgs.BitOffset; SelectNodeWithOffset(treeView, treeView.Nodes[0], offset); }; binaryView.BitMouseMove += (eSender, bitArgs) => { int offset = bitArgs.BitOffset; int byteOffset = offset / 8; byte b = bytes[byteOffset]; string toolTipText = String.Format("Byte @ 0x{0:x} = 0x{1:x} = {2}", byteOffset, b, b); TheToolTip.SetToolTip(binaryView, toolTipText); }; Panel binaryPanel = new Panel(); binaryPanel.Dock = DockStyle.Fill; binaryPanel.AutoScroll = true; binaryPanel.Controls.Add(binaryView); SplitContainer container = new SplitContainer(); container.Orientation = Orientation.Vertical; container.Panel1.Controls.Add(treeView); container.Panel2.Controls.Add(binaryPanel); container.Dock = DockStyle.Fill; Form form = new Form(); form.Text = title; form.Controls.Add(container); form.Controls.Add(statusBar); binaryView.Bytes = bytes; form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } #region Bitstream generation. private static void BuildBitstreamNodes(byte[] bytes, TreeNodeCollection nodes) { TreeNode root; if (bytes[0] == 'D' && bytes[1] == 'X' && bytes[2] == 'B' && bytes[3] == 'C') { root = RangeNode("Content: DXBC"); BuildBitstreamForDXBC(bytes, root); } else { root = RangeNode("Content: Unknown", 0, bytes.Length); } nodes.Add(root); AddBitstreamOffsets(root); } private static void AddBitstreamOffsets(TreeNode node) { TreeNodeRange r = node.Tag as TreeNodeRange; if (r == null) { int offset = -1; int length = 0; foreach (TreeNode child in node.Nodes) { AddBitstreamOffsets(child); TreeNodeRange childRange = child.Tag as TreeNodeRange; Debug.Assert(childRange != null); if (offset == -1) { offset = childRange.Offset; length = childRange.Length; } else { Debug.Assert(offset <= childRange.Offset); int lastBit = childRange.Offset + childRange.Length; length = Math.Max(length, lastBit - offset); } } node.Tag = new TreeNodeRange(offset, length); } } private static void BuildBitstreamForDXBC(byte[] bytes, TreeNode root) { int offset = 0; TreeNode header = RangeNode("Header"); root.Nodes.Add(header); string signature; header.Nodes.Add(RangeNodeASCII(bytes, "Signature", ref offset, 4, out signature)); header.Nodes.Add(RangeNodeBytes("Hash", ref offset, 16 * 8)); ushort verMajor, verMinor; header.Nodes.Add(RangeNodeUInt16(bytes, "VerMajor", ref offset, out verMajor)); header.Nodes.Add(RangeNodeUInt16(bytes, "VerMinor", ref offset, out verMinor)); uint containerSize, partCount; header.Nodes.Add(RangeNodeUInt32(bytes, "ContainerSize", ref offset, out containerSize)); header.Nodes.Add(RangeNodeUInt32(bytes, "PartCount", ref offset, out partCount)); uint[] partOffsets = new uint[partCount]; TreeNode partOffsetTable = RangeNode("Part Offsets"); root.Nodes.Add(partOffsetTable); for (uint i = 0; i < partCount; i++) { uint partSize; partOffsetTable.Nodes.Add(RangeNodeUInt32(bytes, "Part Offset #" + i, ref offset, out partSize)); partOffsets[i] = partSize; } TreeNode partsNode = RangeNode("Parts"); root.Nodes.Add(partsNode); for (uint i = 0; i < partCount; i++) { offset = (int)(8 * partOffsets[i]); TreeNode partNode = RangeNode("Part #" + i); TreeNode headerNode = RangeNode("Header"); string partCC; UInt32 partSize; headerNode.Nodes.Add(RangeNodeASCII(bytes, "PartFourCC", ref offset, 4, out partCC)); headerNode.Nodes.Add(RangeNodeUInt32(bytes, "PartSize", ref offset, out partSize)); partNode.Nodes.Add(headerNode); if (partCC == "DXIL") { BuildBitstreamForDXIL(bytes, offset, partNode); } else if (partCC == "ISGN" || partCC == "OSGN" || partCC == "PSGN" || partCC == "ISG1" || partCC == "OSG1" || partCC == "PSG1") { BuildBitstreamForSignature(bytes, offset, partNode, partCC); } partsNode.Nodes.Add(partNode); } } private static void BuildBitstreamForSignature(byte[] bytes, int offset, TreeNode root, string partName) { // DxilProgramSignature bool hasStream = partName.Last() == '1'; bool hasMinprec = hasStream; int startOffset = offset; uint paramCount, paramOffset; root.Nodes.Add(RangeNodeUInt32(bytes, "ParamCount", ref offset, out paramCount)); root.Nodes.Add(RangeNodeUInt32(bytes, "ParamOffset", ref offset, out paramOffset)); if (paramOffset != 8) return; // padding here not yet implemented for (int i = 0; i < paramCount; i++) { TreeNode paramNode = RangeNode("Param #" + i); // DxilProgramSignatureElement uint stream, semanticIndex, semanticName, systemValue, compType, register, minprec; ushort pad; byte mask, maskUsage; if (hasStream) paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Stream", ref offset, out stream)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SemanticName", ref offset, out semanticName)); // Now go read the string. if (semanticName != 0) { StringBuilder sb = new StringBuilder(); int nameOffset = startOffset / 8 + (int)semanticName; while (bytes[nameOffset] != 0) { sb.Append((char)bytes[nameOffset]); nameOffset++; } paramNode.Text += " - " + sb.ToString(); } paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SemanticIndex", ref offset, out semanticIndex)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "SystemValue", ref offset, out systemValue)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "CompType", ref offset, out compType)); paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Register", ref offset, out register)); paramNode.Nodes.Add(RangeNodeUInt8(bytes, "Mask", ref offset, out mask)); paramNode.Nodes.Add(RangeNodeUInt8(bytes, "MaskUsage", ref offset, out maskUsage)); paramNode.Nodes.Add(RangeNodeUInt16(bytes, "Pad", ref offset, out pad)); if (hasMinprec) { paramNode.Nodes.Add(RangeNodeUInt32(bytes, "Minprecision", ref offset, out minprec)); } root.Nodes.Add(paramNode); } } private static void BuildBitstreamForDXIL(byte[] bytes, int offset, TreeNode root) { TreeNode header = RangeNode("DxilProgramHeader"); uint programVersion, programSize, dxilVersion, bcOffset, bcSize; string magic; TreeNode verNode = RangeNodeUInt32(bytes, "ProgramVersion", ref offset, out programVersion); verNode.Text += " - " + DescribeProgramVersion(programVersion); header.Nodes.Add(verNode); header.Nodes.Add(RangeNodeUInt32(bytes, "SizeInUint32", ref offset, out programSize)); int programOffset = offset; header.Nodes.Add(RangeNodeASCII(bytes, "Magic", ref offset, 4, out magic)); header.Nodes.Add(RangeNodeUInt32(bytes, "DXIL Version", ref offset, out dxilVersion)); header.Nodes.Add(RangeNodeUInt32(bytes, "Bitcode Offset", ref offset, out bcOffset)); header.Nodes.Add(RangeNodeUInt32(bytes, "Bitcode Size", ref offset, out bcSize)); int bitcodeOffset = (int)(programOffset + bcOffset * 8); offset = bitcodeOffset; root.Nodes.Add(header); TreeNode bcNode = RangeNode("DXIL bitcode"); try { DxilBitcodeReader.BuildTree(bytes, ref offset, (int)(bcSize * 8), bcNode); } catch (Exception e) { bcNode.Text += e.Message; } root.Nodes.Add(bcNode); } private static string DescribeProgramVersion(UInt32 programVersion) { uint kind, major, minor; kind = ((programVersion & 0xffff0000) >> 16); major = (programVersion & 0xf0) >> 4; minor = (programVersion & 0xf); string[] shaderKinds = "Pixel,Vertex,Geometry,Hull,Domain,Compute".Split(','); return shaderKinds[kind] + " " + major + "." + minor; } private static string DescribeProgramVersionShort(UInt32 programVersion) { uint kind, major, minor; kind = ((programVersion & 0xffff0000) >> 16); major = (programVersion & 0xf0) >> 4; minor = (programVersion & 0xf); string[] shaderKinds = "ps,vs,gs,hs,ds,cs".Split(','); return shaderKinds[kind] + "_" + major + "_" + minor; } private static TreeNode RangeNode(string text) { return new TreeNode(text); } private static TreeNode RangeNode(string text, int offset, int length) { TreeNode result = new TreeNode(text); result.Tag = new TreeNodeRange(offset, length); return result; } private static TreeNode RangeNodeASCII(byte[] bytes, string text, ref int offset, int charLength, out string value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; char[] valueChars = new char[charLength]; for (int i = 0; i < charLength; ++i) { valueChars[i] = (char)bytes[byteOffset + i]; } value = new string(valueChars); TreeNode result = RangeNode(text + ": '" + value + "'", offset, charLength * 8); offset += charLength * 8; return result; } private static uint ReadArrayBits(byte[] bytes, int offset, int length) { uint value = 0; int byteOffset = offset / 8; int bitOffset = offset % 8; for (int i = 0; i < length; ++i) { uint bit = (bytes[byteOffset] & (uint)(1 << bitOffset)) >> bitOffset; value |= bit << i; ++bitOffset; if (bitOffset == 8) { byteOffset++; bitOffset = 0; } } return value; } private static TreeNode RangeNodeBits(byte[] bytes, string text, ref int offset, int length, out uint value) { System.Diagnostics.Debug.Assert(length > 0 && length <= 32, "Cannot return zero or more than BitsInWord bits!"); TreeNode result = RangeNode(text, offset, length); value = ReadArrayBits(bytes, offset, length); offset += length; return result; } private static TreeNode RangeNodeVBR(byte[] bytes, string text, ref int offset, int length, out uint value) { value = ReadArrayBits(bytes, offset, length); if ((value & (1 << (length - 1))) == 0) { TreeNode result = RangeNode(text + ": " + value, offset, length); offset += length; return result; } else { throw new NotImplementedException(); } } private static TreeNode RangeNodeBytes(string text, ref int offset, int length) { TreeNode result = RangeNode(text, offset, length); offset += length; return result; } private static TreeNode RangeNodeUInt8(byte[] bytes, string text, ref int offset, out byte value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = bytes[byteOffset]; TreeNode result = RangeNode(text + ": " + value, offset, 8); offset += 8; return result; } private static TreeNode RangeNodeUInt16(byte[] bytes, string text, ref int offset, out UInt16 value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = (ushort)((bytes[byteOffset]) + (bytes[byteOffset + 1] << 8)); TreeNode result = RangeNode(text + ": " + value, offset, 16); offset += 16; return result; } private static TreeNode RangeNodeUInt32(byte[] bytes, string text, ref int offset, out UInt32 value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; value = (uint)((bytes[byteOffset]) | (bytes[byteOffset + 1] << 8) | (bytes[byteOffset + 2] << 16) | (bytes[byteOffset + 3] << 24)); TreeNode result = RangeNode(text + ": " + value, offset, 32); offset += 32; return result; } #endregion Bitstream generation. private bool IsOKToOverwriteContent() { if (!this.DocModified) return true; return MessageBox.Show(this, "Are you sure you want to lose your changes?", "Changes Pending", MessageBoxButtons.YesNo) == DialogResult.Yes; } private void fileToolStripMenuItem_DropDownOpening(object sender, EventArgs e) { this.RefreshMRUMenu(this.mruManager, this.recentFilesToolStripMenuItem); } private void EditorForm_Load(object sender, EventArgs e) { this.mruManager = new MRUManager(); this.mruManager.LoadFromFile(); this.settingsManager = new SettingsManager(); this.settingsManager.LoadFromFile(); this.CheckSettingsForDxcLibrary(); } private void RefreshMRUMenu(MRUManager mru, ToolStripMenuItem parent) { parent.DropDownItems.Clear(); foreach (var item in mru.Paths) { EventHandler MRUHandler = (_sender, _args) => { if (!System.IO.File.Exists(item)) { MessageBox.Show("File not found"); return; } this.HandleOpenUI(item); }; parent.DropDownItems.Add(item, null, MRUHandler); } } private static IEnumerable<DiagnosticDetail> EnumerateDiagnosticDetails(DxcDiagnosticDisplayOptions options, IDxcTranslationUnit tu) { uint count = tu.GetNumDiagnostics(); for (uint i = 0; i < count; ++i) { uint errorCode; uint errorLine; uint errorColumn; string errorFile; uint errorOffset; uint errorLength; string errorMessage; tu.GetDiagnosticDetails(i, options, out errorCode, out errorLine, out errorColumn, out errorFile, out errorOffset, out errorLength, out errorMessage); yield return new DiagnosticDetail() { ErrorCode = (int)errorCode, ErrorLine = (int)errorLine, ErrorColumn = (int)errorColumn, ErrorFile = errorFile, ErrorOffset = (int)errorOffset, ErrorLength = (int)errorLength, ErrorMessage = errorMessage, }; } } private static List<DiagnosticDetail> ListDiagnosticDetails(DxcDiagnosticDisplayOptions options, IDxcTranslationUnit tu) { return EnumerateDiagnosticDetails(options, tu).ToList(); } private void RefreshDiagnosticDetails() { if (this.diagnosticDetailsGrid == null) { return; } IDxcTranslationUnit tu = this.GetTU(); if (tu == null) { return; } DxcDiagnosticDisplayOptions options = this.isense.GetDefaultDiagnosticDisplayOptions(); this.diagnosticDetails = ListDiagnosticDetails(options, tu); this.diagnosticDetailsGrid.DataSource = this.diagnosticDetails; this.diagnosticDetailsGrid.Columns["ErrorCode"].Visible = false; this.diagnosticDetailsGrid.Columns["ErrorLength"].Visible = false; this.diagnosticDetailsGrid.Columns["ErrorOffset"].Visible = false; } private void DiagnosticDetailsGridDoubleClick(object sender, EventArgs e) { if (this.diagnosticDetailsGrid.SelectedRows.Count == 0) return; DiagnosticDetail detail = this.diagnosticDetailsGrid.SelectedRows[0].DataBoundItem as DiagnosticDetail; if (detail == null) return; this.CodeBox.Select(detail.ErrorOffset, detail.ErrorLength); this.CodeBox.Select(); } class PassArgumentControls { public PassArgInfo ArgInfo { get; set; } public Label PromptLabel { get; set; } public TextBox ValueControl { get; set; } public Label DescriptionLabel { get; set; } public IEnumerable<Control> Controls { get { yield return PromptLabel; yield return ValueControl; yield return DescriptionLabel; } } public static PassArgumentControls FromArg(PassArgInfo arg) { PassArgumentControls result = new MainNs.EditorForm.PassArgumentControls() { ArgInfo = arg, PromptLabel = new Label() { Text = arg.Name, UseMnemonic = true, }, DescriptionLabel = new Label() { Text = arg.Description, UseMnemonic = false, }, ValueControl = new TextBox() { }, }; if (result.DescriptionLabel.Text == "None") { result.DescriptionLabel.Visible = false; } return result; } } private int LayoutVertical(Control container, IEnumerable<Control> controls, int top, int pad) { int result = top; int controlWidth = container.ClientSize.Width - pad * 2; foreach (var c in controls) { if (!c.Visible) continue; c.Top = result; c.Left = pad; c.Width = controlWidth; c.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; result += c.Height; result += pad; container.Controls.Add(c); } return result; } private void RemoveListBoxItems(ListBox listbox, int startIndex, int endIndexExclusive) { for (int i = endIndexExclusive - 1; i >= startIndex; --i) { listbox.Items.RemoveAt(i); } } private void PassPropertiesMenuItem_Click(object sender, EventArgs e) { ListBox lb = this.SelectedPassesBox; int selectedIndex = lb.SelectedIndex; PassInfoWithValues passInfoValues = lb.SelectedItem as PassInfoWithValues; if (passInfoValues == null) { return; } PassInfo passInfo = passInfoValues.PassInfo; string title = String.Format("{0} properties", passInfo.Name); if (passInfo.Args.Length == 0) { MessageBox.Show(this, "No properties available to set.", title); return; } using (Form form = new Form()) { var argControls = passInfo.Args.Select(p => PassArgumentControls.FromArg(p)).ToDictionary(c => c.ArgInfo); foreach (var val in passInfoValues.Values) argControls[val.Arg].ValueControl.Text = val.Value; int lastTop = LayoutVertical(form, argControls.Values.SelectMany(c => c.Controls), 8, 8); form.ShowInTaskbar = false; form.MinimizeBox = false; form.MaximizeBox = false; form.Text = title; Button okButton = new Button() { Anchor = AnchorStyles.Bottom | AnchorStyles.Right, DialogResult = DialogResult.OK, Text = "OK", Top = lastTop, }; okButton.Left = form.ClientSize.Width - 8 - okButton.Width; form.Controls.Add(okButton); form.AcceptButton = okButton; if (form.ShowDialog(this) == DialogResult.OK) { passInfoValues.Values.Clear(); // Add options with values. foreach (var argValues in argControls.Values) { if (String.IsNullOrEmpty(argValues.ValueControl.Text)) continue; passInfoValues.Values.Add(new PassArgValueInfo() { Arg = argValues.ArgInfo, Value = argValues.ValueControl.Text }); } lb.Items.RemoveAt(selectedIndex); lb.Items.Insert(selectedIndex, passInfoValues); lb.SelectedIndex = selectedIndex; } } } private void copyAllToolStripMenuItem_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); foreach (var o in this.SelectedPassesBox.Items) sb.AppendLine(o.ToString()); Clipboard.SetText(sb.ToString()); } private void renderToolStripMenuItem_Click(object sender, EventArgs e) { this.RenderLogBox.Clear(); string payloadText = GetShaderOpPayload(); if (this.settingsManager.ExternalRenderEnabled) { string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "dndxc-ext-render.xml"); try { System.IO.File.WriteAllText(path, payloadText); } catch (Exception writeErr) { HandleException(writeErr, "Unable to write render input to " + path); return; } try { string arguments = this.settingsManager.ExternalRenderCommand; arguments = arguments.Replace("%in", path); var process = System.Diagnostics.Process.Start("cmd.exe", "/c " + arguments); if (process != null) { process.Dispose(); } } catch (Exception runErr) { HandleException(runErr, "Unable to run external render command."); return; } return; } try { this.hlslHost.EnsureActive(); } catch (Exception startErr) { HandleException(startErr, "Unable to start HLSLHost.exe."); return; } try { SendHostMessageAndLogReply(HlslHost.HhMessageId.StartRendererMsgId); this.AnalysisTabControl.SelectedTab = RenderViewTabPage; this.hlslHost.SetParentHwnd(RenderViewTabPage.Handle); this.hlslHost.SendHostMessagePlay(payloadText); System.Windows.Forms.Timer t = new Timer(); t.Interval = 1000; t.Tick += (_, __) => { t.Dispose(); if (!this.TopSplitContainer.Panel2Collapsed) { this.RenderLogBox.Font = this.CodeBox.Font; this.DrainHostLog(); } }; t.Start(); } catch (Exception runError) { System.Diagnostics.Debug.WriteLine(runError); this.hlslHost.IsActive = false; this.HandleException(runError, "Unable to render"); } } private string GetShaderOpPayload() { string fullText = this.CodeBox.Text; string xml = GetShaderOpXmlFragment(fullText); return HlslHost.GetShaderOpPayload(fullText, xml); } private static readonly string ShaderOpStartMarker = "#if SHADER_OP_XML"; private static readonly string ShaderOpStopMarker = "#endif"; private static string GetShaderOpXmlFragment(string text) { int start = text.IndexOf(ShaderOpStartMarker); if (start == -1) throw new InvalidOperationException("Cannot for '" + ShaderOpStartMarker + "' marker"); start += ShaderOpStartMarker.Length; int end = text.IndexOf(ShaderOpStopMarker, start); if (end == -1) throw new InvalidOperationException("Cannot for '" + ShaderOpStopMarker + "' marker"); return text.Substring(start, end - start).Trim(); } private void SendHostMessageAndLogReply(HlslHost.HhMessageId kind) { this.hlslHost.SendHostMessage(kind); LogReply(this.hlslHost.GetReply()); } private HlslHost.HhMessageReply LogReply(HlslHost.HhMessageReply reply) { if (reply == null) return null; string log = HlslHost.GetLogReplyText(reply); if (!String.IsNullOrWhiteSpace(log)) { this.RenderLogBox.AppendText(log + "\r\n"); } return reply; } private void DrainHostLog() { try { this.hlslHost.SendHostMessage(HlslHost.HhMessageId.ReadLogMsgId); for (;;) { if (this.LogReply(this.hlslHost.GetReply()) == null) return; } } catch (Exception hostErr) { this.TheStatusStripLabel.Text = "Unable to contact host."; this.RenderLogBox.AppendText(hostErr.Message); } } private void outputToolStripMenuItem_Click(object sender, EventArgs e) { this.TopSplitContainer.Panel2Collapsed = !this.TopSplitContainer.Panel2Collapsed; if (!this.hlslHost.IsActive) return; this.RenderLogBox.Font = this.CodeBox.Font; this.DrainHostLog(); } private void EditorForm_FormClosing(object sender, FormClosingEventArgs e) { // Consider prompting to save. } private void EditorForm_FormClosed(object sender, FormClosedEventArgs e) { this.hlslHost.IsActive = false; } private void FontGrowToolStripMenuItem_Click(object sender, EventArgs e) { Control target = this.DeepActiveControl; if (target == null) return; target.Font = new Font(target.Font.FontFamily, target.Font.Size * 1.1f); } private void FontShrinkToolStripMenuItem_Click(object sender, EventArgs e) { Control target = this.DeepActiveControl; if (target == null) return; target.Font = new Font(target.Font.FontFamily, target.Font.Size / 1.1f); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { Form form = new Form(); PropertyGrid grid = new PropertyGrid(); grid.SelectedObject = this.settingsManager; grid.Dock = DockStyle.Fill; form.Controls.Add(grid); form.FormClosing += (_, __) => { this.settingsManager.SaveToFile(); this.CheckSettingsForDxcLibrary(); }; form.ShowDialog(this); } private void CheckSettingsForDxcLibrary() { try { if (String.IsNullOrWhiteSpace(this.settingsManager.ExternalLib)) { HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn(); } else { HlslDxcLib.DxcCreateInstanceFn = HlslDxcLib.LoadDxcCreateInstance( this.settingsManager.ExternalLib, this.settingsManager.ExternalFunction); } } catch (Exception e) { HandleException(e); } } private void colorToolStripMenuItem_Click(object sender, EventArgs e) { this.ColorMenuItem.Checked = !this.ColorMenuItem.Checked; CodeBox_SelectionChanged(sender, e); } private void rewriterToolStripMenuItem_Click(object sender, EventArgs e) { IDxcRewriter rewriter = HlslDxcLib.CreateDxcRewriter(); IDxcBlobEncoding code = CreateBlobForCodeText(); IDxcRewriteResult rewriterResult = rewriter.RewriteUnchangedWithInclude(code, "input.hlsl", null, 0, library.CreateIncludeHandler(), 0); IDxcBlobEncoding rewriteBlob = rewriterResult.GetRewrite(); string rewriteText = GetStringFromBlob(rewriteBlob); RewriterOutputTextBox.Text = rewriteText; AnalysisTabControl.SelectTab(RewriterOutputTabPage); } private void rewriteNobodyToolStripMenuItem_Click(object sender, EventArgs e) { IDxcRewriter rewriter = HlslDxcLib.CreateDxcRewriter(); IDxcBlobEncoding code = CreateBlobForCodeText(); IDxcRewriteResult rewriterResult = rewriter.RewriteUnchangedWithInclude(code, "input.hlsl", null, 0, library.CreateIncludeHandler(), 1); IDxcBlobEncoding rewriteBlob = rewriterResult.GetRewrite(); string rewriteText = GetStringFromBlob(rewriteBlob); RewriterOutputTextBox.Text = rewriteText; AnalysisTabControl.SelectTab(RewriterOutputTabPage); } private IEnumerable<string> EnumerateDiaCandidates() { string progPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\DIA SDK\bin\amd64\msdia140.dll"); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\Common7\IDE\msdia140.dll"); yield return System.IO.Path.Combine(progPath, @"Microsoft Visual Studio\2017\Community\Common7\IDE\msdia120.dll"); } private string SuggestDiaRegistration() { foreach (string path in EnumerateDiaCandidates()) { if (System.IO.File.Exists(path)) { return "Consider registering with this command:\r\n" + "regsvr32 \"" + path + "\""; } } return null; } private void debugInformationToolStripMenuItem_Click(object sender, EventArgs e) { if (this.SelectedShaderBlob == null) { MessageBox.Show("Compile or load a shader to view debug information."); return; } this.ClearDiaUnimplementedFlags(); IDxcBlob debugInfoBlob; dia2.IDiaDataSource dataSource; uint dfcc; IDxcContainerReflection r = HlslDxcLib.CreateDxcContainerReflection(); r.Load(this.SelectedShaderBlob); if (IsDxilTarget(this.selectedShaderBlobTarget)) { dataSource = HlslDxcLib.CreateDxcDiaDataSource(); dfcc = DFCC_ILDB; } else { try { dataSource = new dia2.DiaDataSource() as dia2.IDiaDataSource; } catch (System.Runtime.InteropServices.COMException ce) { const int REGDB_E_CLASSNOTREG = -2147221164; if (ce.HResult == REGDB_E_CLASSNOTREG) { string suggestion = SuggestDiaRegistration(); string message = "Unable to create dia object."; if (suggestion != null) message += "\r\n" + suggestion; MessageBox.Show(this, message); } else { HandleException(ce); } return; } dfcc = DFCC_SPDB; } uint index; int hr = r.FindFirstPartKind(dfcc, out index); if (hr < 0) { MessageBox.Show("Debug information not found in container."); return; } debugInfoBlob = r.GetPartContent(index); try { dataSource.loadDataFromIStream(Library.CreateStreamFromBlobReadOnly(debugInfoBlob)); string s = dataSource.get_lastError(); if (!String.IsNullOrEmpty(s)) { MessageBox.Show("Failure to load stream: " + s); return; } } catch (Exception ex) { HandleException(ex); return; } var session = dataSource.openSession(); var tables = session.getEnumTables(); uint count = tables.get_Count(); StringBuilder output = new StringBuilder(); output.AppendLine("* Tables"); bool isFirstTable = true; for (uint i = 0; i < count; ++i) { var table = tables.Item(i); if (isFirstTable) isFirstTable = false; else output.AppendLine(); output.AppendLine("** " + table.get_name()); int itemCount = table.get_Count(); output.AppendLine("Record count: " + itemCount); for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { object o = table.Item((uint)itemIdx); if (TryDumpDiaObject(o as dia2.IDiaSymbol, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSourceFile, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaLineNumber, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaInjectedSource, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSectionContrib, output)) continue; if (TryDumpDiaObject(o as dia2.IDiaSegment, output)) continue; } } if (debugInfoTabPage == null) { this.debugInfoTabPage = new TabPage("Debug Info"); this.debugInfoControl = new RichTextBox() { Dock = DockStyle.Fill, Font = this.CodeBox.Font, ReadOnly = true }; this.AnalysisTabControl.TabPages.Add(this.debugInfoTabPage); this.debugInfoTabPage.Controls.Add(this.debugInfoControl); } this.debugInfoControl.Text = output.ToString(); this.AnalysisTabControl.SelectedTab = this.debugInfoTabPage; } private bool TryDumpDiaObject<TIface>(TIface o, StringBuilder sb) { if (o == null) return false; DumpDiaObject(o, sb); return true; } private void ClearDiaUnimplementedFlags() { foreach (var item in TypeWriters) foreach (var writer in item.Value) writer.Unimplemented = false; } private void DumpDiaObject<TIface>(TIface o, StringBuilder sb) { Type type = typeof(TIface); bool hasLine = false; List<DiaTypePropertyWriter> writers; if (SymTagEnumValues == null) { SymTagEnumValues = Enum.GetNames(typeof(dia2.SymTagEnum)); } if (!TypeWriters.TryGetValue(type, out writers)) { writers = new List<DiaTypePropertyWriter>(); foreach (System.Reflection.MethodInfo mi in type.GetMethods()) { Func<string, object, StringBuilder, bool> writer; if (mi.GetParameters().Length > 0) continue; string propertyName = mi.Name; if (!propertyName.StartsWith("get_")) continue; propertyName = propertyName.Substring(4); Type returnType = mi.ReturnType; if (returnType == typeof(string)) writer = WriteDiaValueString; else if (returnType == typeof(uint) && propertyName == "symTag") writer = WriteDiaValueSymTag; else if (returnType == typeof(uint)) writer = WriteDiaValueUInt32; else if (returnType == typeof(UInt64)) writer = WriteDiaValueUInt64; else if (returnType == typeof(bool)) writer = WriteDiaValueBool; else writer = WriteDiaValueAny; writers.Add(new DiaTypePropertyWriter() { MI = mi, PropertyName = propertyName, Writer = writer }); } TypeWriters[type] = writers; } foreach (var writer in writers) { if (writer.Write(o, sb)) hasLine = true; } if (hasLine) sb.AppendLine(); } private static Dictionary<Type, List<DiaTypePropertyWriter>> TypeWriters = new Dictionary<Type, List<DiaTypePropertyWriter>>(); internal static string[] SymTagEnumValues; class DiaTypePropertyWriter { public static object[] EmptyParams = new object[0]; public bool Unimplemented; public System.Reflection.MethodInfo MI; public string PropertyName; public Func<string, object, StringBuilder, bool> Writer; internal bool Write(object instance, StringBuilder sb) { if (Unimplemented) return false; try { object value = MI.Invoke(instance, EmptyParams); return Writer(PropertyName, value, sb); } catch (System.Reflection.TargetInvocationException tie) { if (tie.InnerException is NotImplementedException) { this.Unimplemented = true; } return false; } catch (System.Runtime.InteropServices.COMException) { return false; } } } private static bool WriteDiaValueAny(string propertyName, object propertyValue, StringBuilder sb) { if (null == propertyValue) return false; if (System.Runtime.InteropServices.Marshal.IsComObject(propertyValue)) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(Convert.ToString(propertyValue)); sb.AppendLine(); return true; } private static bool WriteDiaValueSymTag(string propertyName, object propertyValueObj, StringBuilder sb) { uint tag = (uint)propertyValueObj; sb.Append(propertyName); sb.Append(": "); sb.AppendLine(SymTagEnumValues[tag]); return true; } private static bool WriteDiaValueBool(string propertyName, object propertyValueObj, StringBuilder sb) { bool propertyValue = (bool)propertyValueObj; if (false == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueUInt32(string propertyName, object propertyValueObj, StringBuilder sb) { uint propertyValue = (uint)propertyValueObj; if (0 == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueUInt64(string propertyName, object propertyValueObj, StringBuilder sb) { UInt64 propertyValue = (UInt64)propertyValueObj; if (0 == propertyValue) return false; sb.Append(propertyName); sb.Append(": "); sb.Append(propertyValue); sb.AppendLine(); return true; } private static bool WriteDiaValueString(string propertyName, object propertyValueObj, StringBuilder sb) { string propertyValue = (string)propertyValueObj; if (String.IsNullOrEmpty(propertyValue)) return false; sb.Append(propertyName); sb.Append(": "); sb.AppendLine(propertyValue); return true; } private void PastePassesMenuItem_Click(object sender, EventArgs e) { if (!Clipboard.ContainsText()) { MessageBox.Show(this, "The clipboard does not contain pass information.", "Unable to paste passes"); return; } string passes = Clipboard.GetText(TextDataFormat.UnicodeText); try { passes = passes.Replace("\r\n", "\n"); AddSelectedPassesFromText(passes, false); } catch (Exception ex) { this.HandleException(ex); } } private void DeleteAllPassesMenuItem_Click(object sender, EventArgs e) { this.SelectedPassesBox.Items.Clear(); } public class AssembleResult { public IDxcBlob Blob { get; set; } public string ResultText { get; set; } public bool Succeeded { get; set; } } public class HighLevelCompileResult { public IDxcBlob Blob { get; set; } public string ResultText { get; set; } } public class OptimizeResult { public IDxcBlob Module { get; set; } public string ResultText { get; set; } public bool Succeeded { get; set; } } public static AssembleResult RunAssembly(IDxcLibrary library, IDxcBlob source) { IDxcBlob resultBlob = null; string resultText = ""; bool succeeded; var assembler = HlslDxcLib.CreateDxcAssembler(); var result = assembler.AssembleToContainer(source); if (result.GetStatus() == 0) { resultBlob = result.GetResult(); succeeded = true; } else { resultText = GetStringFromBlob(library, result.GetErrors()); succeeded = false; } return new AssembleResult() { Blob = resultBlob, ResultText = resultText, Succeeded = succeeded }; } public HighLevelCompileResult RunHighLevelCompile() { IDxcCompiler compiler = HlslDxcLib.CreateDxcCompiler(); string fileName = "hlsl.hlsl"; HlslFileVariables fileVars = GetFileVars(); List<string> args = new List<string>(); args.Add("-fcgl"); args.AddRange(tbOptions.Text.Split()); string resultText = ""; IDxcBlob source = null; { try { var result = compiler.Compile(this.CreateBlobForCodeText(), fileName, fileVars.Entry, fileVars.Target, args.ToArray(), args.Count, null, 0, library.CreateIncludeHandler()); if (result.GetStatus() == 0) { source = result.GetResult(); } else { resultText = GetStringFromBlob(result.GetErrors()); } } catch (System.ArgumentException e) { MessageBox.Show(this, $"{e.Message}.", "Invalid form entry"); } } return new HighLevelCompileResult() { Blob = source, ResultText = resultText }; } public static OptimizeResult RunOptimize(IDxcLibrary library, string[] options, string source) { return RunOptimize(library, options, CreateBlobForText(library, source)); } public static OptimizeResult RunOptimize(IDxcLibrary library, string[] options, IDxcBlob source) { IDxcOptimizer opt = HlslDxcLib.CreateDxcOptimizer(); IDxcBlob module = null; string resultText = ""; IDxcBlobEncoding text; bool succeeded = true; try { opt.RunOptimizer(source, options, options.Length, out module, out text); resultText = GetStringFromBlob(library, text); } catch (Exception optException) { succeeded = false; resultText = "Failed to run optimizer: " + optException.Message; } return new OptimizeResult() { Module = module, ResultText = resultText, Succeeded = succeeded }; } private void InteractiveEditorButton_Click(object sender, EventArgs e) { // Do a high-level only compile. HighLevelCompileResult compile = RunHighLevelCompile(); if (compile.Blob == null) { MessageBox.Show("Failed to compile: " + compile.ResultText); return; } string[] options = CreatePassOptions(false, true); OptimizeResult opt = RunOptimize(this.Library, options, compile.Blob); if (!opt.Succeeded) { MessageBox.Show("Failed to optimize: " + opt.ResultText); return; } OptEditorForm form = new OptEditorForm(); form.CodeFont = this.CodeBox.Font; form.HighLevelSource = compile.Blob; form.Library = this.Library; form.Sections = TextSection.EnumerateSections(new string[] { "MODULE-PRINT", "Phase:" }, opt.ResultText).ToArray(); form.StartPosition = FormStartPosition.CenterParent; form.Show(this); } private void CodeBox_HelpRequested(object sender, HelpEventArgs hlpevent) { RichTextBox rtb = this.CodeBox; SelectionExpandResult expand = SelectionExpandResult.Expand(rtb); if (expand.IsEmpty) return; string readmeText; using (System.IO.StreamReader reader = new System.IO.StreamReader(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("MainNs.README.md"))) { readmeText = reader.ReadToEnd(); } this.HelpControl.Text = readmeText; (this.HelpTabPage.Parent as TabControl).SelectedTab = this.HelpTabPage; int pos = readmeText.IndexOf(expand.Token, StringComparison.InvariantCultureIgnoreCase); if (pos >= 0) { this.HelpControl.Select(pos, 0); this.HelpControl.ScrollToCaret(); } } } public static class RichTextBoxExt { public static void AppendLine(this RichTextBox rtb, string line, Color c) { rtb.SelectionBackColor = c; rtb.AppendText(line); rtb.AppendText("\r\n"); } public static void AppendLines(this RichTextBox rtb, string prefix, string[] lines, int start, int length, Color c) { for (int i = start; i < (start + length); ++i) { rtb.AppendLine(prefix + lines[i], c); } } public static IEnumerable<string> ToStringEnumerable(this ListBox.ObjectCollection collection) { foreach (var item in collection) yield return item.ToString(); } } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/GoToDialog.cs
/////////////////////////////////////////////////////////////////////////////// // // // GoToDialog.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MainNs { public partial class GoToDialog : Form { public GoToDialog() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void GoToDialog_Load(object sender, EventArgs e) { } public int LineNumber { get { int result; if (!int.TryParse(this.GoToBox.Text, out result)) { result = 0; } return result; } set { this.GoToBox.Text = value.ToString(); } } private int maxLineNumber; public int MaxLineNumber { get { return this.maxLineNumber; } set { this.maxLineNumber = value; this.GoToLabel.Text = "&Line number (1 - " + value.ToString() + "):"; } } } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/EditorModels.cs
/////////////////////////////////////////////////////////////////////////////// // // // EditorModels.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides support for model classes used by the editor UI. // // // /////////////////////////////////////////////////////////////////////////////// using DotNetDxc; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Xml.Linq; namespace MainNs { public class DiagnosticDetail { [DisplayName("Error")] public int ErrorCode { get; set; } [DisplayName("Line")] public int ErrorLine { get; set; } [DisplayName("Column")] public int ErrorColumn { get; set; } [DisplayName("File")] public string ErrorFile { get; set; } [DisplayName("Offset")] public int ErrorOffset { get; set; } [DisplayName("Length")] public int ErrorLength { get; set; } [DisplayName("Message")] public string ErrorMessage { get; set; } } [DebuggerDisplay("{Name}")] class PassArgInfo { public string Name { get; set; } public string Description { get; set; } public PassInfo PassInfo { get; set; } public override string ToString() { return Name; } } [DebuggerDisplay("{Arg.Name} = {Value}")] class PassArgValueInfo { public PassArgInfo Arg { get; set; } public string Value { get; set; } public override string ToString() { if (String.IsNullOrEmpty(Value)) return Arg.Name; return Arg.Name + "=" + Value; } } [DebuggerDisplay("{Name}")] class PassInfo { public string Name { get; set; } public string Description { get; set; } public PassArgInfo[] Args { get; set; } public static PassInfo FromOptimizerPass(IDxcOptimizerPass pass) { PassInfo result = new PassInfo() { Name = pass.GetOptionName(), Description = pass.GetDescription() }; PassArgInfo[] args = new PassArgInfo[pass.GetOptionArgCount()]; for (int i = 0; i < pass.GetOptionArgCount(); ++i) { PassArgInfo info = new PassArgInfo() { Name = pass.GetOptionArgName((uint)i), Description = pass.GetOptionArgDescription((uint)i), PassInfo = result }; args[i] = info; } result.Args = args; return result; } public override string ToString() { return Name; } } class PassInfoWithValues { public PassInfoWithValues(PassInfo pass) { this.PassInfo = pass; this.Values = new List<PassArgValueInfo>(); } public PassInfo PassInfo { get; set; } public List<PassArgValueInfo> Values { get; set; } public override string ToString() { string result = this.PassInfo.Name; if (this.Values.Count == 0) return result; result += String.Concat(this.Values.Select(v => "," + v.ToString())); return result; } } class MRUManager { #region Private fields. private List<string> MRUFiles = new List<string>(); #endregion Private fields. #region Constructors. public MRUManager() { this.MaxCount = 8; this.MRUPath = System.IO.Path.Combine( System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dndxc", "mru.txt"); } #endregion Constructors. #region Public properties. public int MaxCount { get; set; } public string MRUPath { get; set; } public IEnumerable<string> Paths { get { return this.MRUFiles; } } #endregion Public properties. #region Public methods. public void LoadFromFile() { this.LoadFromFile(this.MRUPath); } public void LoadFromFile(string path) { if (!System.IO.File.Exists(path)) return; this.MRUFiles = System.IO.File.ReadAllLines(path).ToList(); } public void SaveToFile() { this.SaveToFile(this.MRUPath); } public void SaveToFile(string path) { string dirName = System.IO.Path.GetDirectoryName(path); if (!System.IO.Directory.Exists(dirName)) System.IO.Directory.CreateDirectory(dirName); System.IO.File.WriteAllLines(path, this.MRUFiles); } public void HandleFileLoad(string path) { this.HandleFileSave(path); } public void HandleFileSave(string path) { path = System.IO.Path.GetFullPath(path); int index = this.MRUFiles.IndexOf(path); if (index >= 0) this.MRUFiles.RemoveAt(index); this.MRUFiles.Insert(0, path); while (this.MRUFiles.Count > this.MaxCount) this.MRUFiles.RemoveAt(this.MRUFiles.Count - 1); } public void HandleFileFail(string path) { path = System.IO.Path.GetFullPath(path); int index = this.MRUFiles.IndexOf(path); if (index >= 0) this.MRUFiles.RemoveAt(index); } #endregion Public methods. } /// <summary>Use this class to represent a range of int values.</summary> [DebuggerDisplay("{Lo} - {Hi}")] struct NumericRange { /// <summary>Low range, inclusive.</summary> public int Lo; /// <summary>High range, exclusive.</summary> public int Hi; public NumericRange(int lo, int hi) { this.Lo = lo; this.Hi = hi; } public bool Equals(NumericRange other) { return this.IsEmpty && other.IsEmpty || this.Lo == other.Lo && this.Hi == other.Hi; } public override bool Equals(object other) { return other is NumericRange && Equals((NumericRange)other); } public override int GetHashCode() { return this.Lo | (this.Hi & 0xffff) << 16; } public static bool operator==(NumericRange left, NumericRange right) { return left.Equals(right); } public static bool operator !=(NumericRange left, NumericRange right) { return !left.Equals(right); } public bool IsEmpty { get { return Lo == Hi; } } public bool Contains(int val) { return (Lo <= val && val < Hi); } public bool Contains(NumericRange range) { return (Lo <= range.Lo && range.Hi <= Hi); } public bool IsAdjacent(NumericRange other) { return !this.IsEmpty && !other.IsEmpty && (other.Hi == this.Lo || this.Hi == other.Lo); } public bool IsDisjoint(NumericRange other) { return this.Hi <= other.Lo || other.Hi <= this.Lo; } public bool Subtract(NumericRange other, out NumericRange reminder) { // If empty, nothing to subtract. reminder = new NumericRange(); if (this.IsEmpty || other.IsEmpty) { return false; } // If disjoint, result is unchanged. if (IsDisjoint(other)) { return false; } // If fully contained, result is empty. if (other.Contains(this)) { this.Lo = 0; this.Hi = 0; return true; } // If only low edge is contained, the high segment is a reminder. if (other.Contains(this.Lo) && !other.Contains(this.Hi - 1)) { this.Lo = other.Hi; return true; } // If only high edge is contained, the low segment is a reminder. if (other.Contains(this.Hi - 1) && !other.Contains(this.Lo)) { this.Hi = other.Lo; return true; } // In this case, the other result is contained within, so the // subtraction produces two segments: 'this' keeps the low end, // and 'reminder' takes the high end. reminder.Hi = this.Hi; this.Hi = other.Lo; reminder.Lo = other.Hi; return true; } public bool TryCoalesce(NumericRange other, out NumericRange coalesced) { // If either is empty, position is meaningless. // Coalescing can happen unless disjoint. if (this.IsEmpty || other.IsEmpty || (IsDisjoint(other) && !IsAdjacent(other))) { coalesced = new NumericRange(); return false; } int newLo = Math.Min(this.Lo, other.Lo); int newHi = Math.Max(this.Hi, other.Hi); coalesced = new NumericRange(newLo, newHi); return true; } public override string ToString() { return this.Lo.ToString() + "-" + this.Hi.ToString(); } } /// <summary>Use this class to represent multiple ranges that can be implicitly coalesced and split.</summary> class NumericRanges : IEnumerable<NumericRange> { /// <summary>Ordered ranges.</summary> private List<NumericRange> ranges = new List<NumericRange>(); public void Add(int lo, int hi) { if (lo == hi) return; // Trivial common case - appending to last. if (this.ranges.Count > 0) { NumericRange range = this.ranges[this.ranges.Count - 1]; if (range.Lo <= lo && lo <= range.Hi) { if (hi <= range.Hi) { return; // already contained } this.ranges[this.ranges.Count - 1] = new NumericRange(range.Lo, hi); return; } } // To keep this simple, add the new range by lo end, then coalesce. bool added = false; int coalesce = 0; for (int i = 0; i < ranges.Count; ++i) { if (lo < ranges[i].Lo) { // Comes prior to this range. ranges.Insert(i, new NumericRange(lo, hi)); added = true; coalesce = i - 1; break; } if (hi <= ranges[i].Hi) { // Fully overlapped. return; } } if (!added) { ranges.Add(new NumericRange(lo, hi)); coalesce = ranges.Count - 2; } // Coalesce a few items ahead from our starting point. coalesce = Math.Max(0, coalesce); for (int i = coalesce; i < coalesce + 2;) { int next = i + 1; if (next >= ranges.Count) return; NumericRange range; if (ranges[i].TryCoalesce(ranges[next], out range)) { ranges[i] = range; ranges.RemoveAt(next); } else { ++i; } } } public void Add(NumericRange range) { Add(range.Lo, range.Hi); } public void Clear() { this.ranges.Clear(); } public bool Contains(NumericRange range) { foreach (var r in ranges) { if (range.Hi < r.Lo) { break; } if (r.Contains(range)) { return true; } } return false; } public bool IsEmpty { get { return this.ranges.Count == 0; } } public IEnumerator<NumericRange> GetEnumerator() { return this.ranges.GetEnumerator(); } public NumericRanges ListGaps(NumericRange range) { NumericRanges result = new NumericRanges(); result.Add(range); foreach (var r in ranges) { result.Remove(r); } return result; } public void Remove(NumericRange range) { for (int i = 0; i < ranges.Count;) { NumericRange r = ranges[i]; if (range.Hi < r.Lo) return; NumericRange remainder; if (r.Subtract(range, out remainder)) { if (r.IsEmpty) { ranges.RemoveAt(i); } else { ranges[i] = r; if (!remainder.IsEmpty) { ranges.Insert(i + 1, remainder); } } } else { i++; } } } IEnumerator IEnumerable.GetEnumerator() { return this.ranges.GetEnumerator(); } public override string ToString() { return String.Join(",", ranges.Select(r => r.ToString())); } } class SettingsManager { #region Private fields. private XDocument doc = new XDocument(); #endregion Private fields. #region Constructors. public SettingsManager() { this.doc = new XDocument(new XElement("settings")); this.SettingsPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dndxc.settings.xml"); } #endregion Constructors. #region Public properties. internal string SettingsPath { get; set; } [Description("The name of an external DLL implementing the compiler.")] public string ExternalLib { get { return this.GetPathTextOrDefault("", "external", "lib"); } set { this.SetPathText(value, "external", "lib"); } } [Description("The name of the factory function export on the external DLL implementing the compiler.")] public string ExternalFunction { get { return this.GetPathTextOrDefault("", "external", "fun"); } set { this.SetPathText(value, "external", "fun"); } } [Description("The command to run in place of View | Render, replacing %in with XML path.")] public string ExternalRenderCommand { get { return this.GetPathTextOrDefault("", "external-render", "command"); } set { this.SetPathText(value, "external-render", "command"); } } [Description("Whether to use an external render tool.")] public bool ExternalRenderEnabled { get { return bool.Parse(this.GetPathTextOrDefault("false", "external-render", "enabled")); } set { this.SetPathText(value.ToString(), "external-render", "enabled"); } } #endregion Public properties. #region Public methods. public void LoadFromFile() { this.LoadFromFile(this.SettingsPath); } public void LoadFromFile(string path) { if (!System.IO.File.Exists(path)) return; this.doc = XDocument.Load(path); } public void SaveToFile() { this.SaveToFile(this.SettingsPath); } public void SaveToFile(string path) { string dirName = System.IO.Path.GetDirectoryName(path); if (!System.IO.Directory.Exists(dirName)) System.IO.Directory.CreateDirectory(dirName); this.doc.Save(path); } #endregion Public methods. #region Private methods. private string GetPathTextOrDefault(string defaultValue, params string[] paths) { var element = this.doc.Root; foreach (string path in paths) { element = element.Element(XName.Get(path)); if (element == null) return defaultValue; } return element.Value; } private void SetPathText(string value, params string[] paths) { var element = this.doc.Root; foreach (string path in paths) { var next = element.Element(XName.Get(path)); if (next == null) { next = new XElement(XName.Get(path)); element.Add(next); } element = next; } element.Value = value; } #endregion Private methods. } class ContainerData { public static System.Windows.Forms.DataFormats.Format DataFormat = System.Windows.Forms.DataFormats.GetFormat("DXBC"); public static string BlobToBase64(IDxcBlob blob) { return System.Convert.ToBase64String(BlobToBytes(blob)); } public static byte[] BlobToBytes(IDxcBlob blob) { byte[] bytes; unsafe { char* pBuffer = blob.GetBufferPointer(); uint size = blob.GetBufferSize(); bytes = new byte[size]; IntPtr ptr = new IntPtr(pBuffer); System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, (int)size); } return bytes; } public static byte[] DataObjectToBytes(object data) { System.IO.Stream stream = data as System.IO.Stream; if (stream == null) return null; byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); return bytes; } public static string DataObjectToString(object data) { byte[] bytes = DataObjectToBytes(data); if (bytes == null) return ""; return System.Convert.ToBase64String(bytes); } } #if FALSE public class NumericRangesTests { public static void Assert(bool condition) { Debug.Assert(condition); } private static NumericRange NR(int lo, int hi) { return new NumericRange(lo, hi); } public static void Run() { NumericRange empty = new NumericRange(); Assert(empty.IsEmpty); NumericRange n = new NumericRange(); Assert(!n.Contains(0)); n.Hi = 1; Assert(n.Contains(0)); Assert(!n.Contains(1)); Assert(n.IsDisjoint(new NumericRange())); Assert(n.IsDisjoint(new NumericRange(1, 2))); NumericRange remainder; // Subtract - empty cases Assert(false == n.Subtract(empty, out remainder)); Assert(remainder.IsEmpty); Assert(false == empty.Subtract(n, out remainder)); // Subtract - disjoint Assert(false == NR(0, 3).Subtract(NR(3, 5), out remainder)); n = NR(0, 3); // Subtract - contained Assert(n.Subtract(NR(0, 4), out remainder)); Assert(n.IsEmpty); // Subtract - partial overlaps n = NR(10, 12); Assert(n.Subtract(NR(8, 11), out remainder)); Assert(n == NR(11, 12)); Assert(remainder.IsEmpty); n = NR(10, 12); Assert(n.Subtract(NR(11, 12), out remainder)); Assert(n == NR(10, 11)); Assert(remainder.IsEmpty); n = NR(10, 21); Assert(n.Subtract(NR(13, 17), out remainder)); Assert(n == NR(10, 13)); Assert(remainder == NR(17, 21)); // Coalesce - no-ops. NumericRange coalesced; n = NR(10, 21); Assert(false == n.TryCoalesce(NR(0, 9), out coalesced)); Assert(false == n.TryCoalesce(empty, out coalesced)); Assert(n.TryCoalesce(NR(0, 10), out coalesced)); Assert(coalesced == NR(0, 21)); n = NR(10, 21); Assert(n.TryCoalesce(NR(0, 100), out coalesced)); Assert(coalesced == NR(0, 100)); NumericRanges r = new NumericRanges(); Assert(r.IsEmpty); r.Add(0, 10); Assert(r.ToString() == "0-10"); r.Add(0, 4); Assert(r.ToString() == "0-10"); r.Add(20, 20); Assert(r.ToString() == "0-10"); r.Add(20, 30); Assert(r.ToString() == "0-10,20-30"); r.Add(10, 20); Assert(r.ToString() == "0-30"); r.Add(30, 32); Assert(r.ToString() == "0-32"); r.Clear(); Assert(r.ToString() == ""); r.Add(NR(0, 10)); r.Add(NR(20, 30)); var gaps = r.ListGaps(NR(0, 40)).ToList(); Assert(gaps[0] == NR(10, 20)); Assert(gaps[1] == NR(30, 40)); } } #endif }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/Program.cs
/////////////////////////////////////////////////////////////////////////////// // // // Program.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides an entry point for a console program to exercise dxcompiler. // // // /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using DotNetDxc; namespace MainNs { class Program { static string TakeNextArg(string[] args, ref int idx) { if (idx >= args.Length) return null; string result = args[idx]; idx++; return result; } static void ShowHelp() { Console.WriteLine("Prints out the color information for each token in a file."); Console.WriteLine(); Console.WriteLine("USAGE:"); Console.WriteLine(" dndxc.exe [-w] [-s width height] filename.hlsl"); Console.WriteLine(); Console.WriteLine("Options:"); Console.WriteLine(" -w window user interface mode"); Console.WriteLine(" -s set window width and height in pixels"); } [STAThread] static int Main(string[] args) { string firstArg = (args.Length < 1) ? "-w" : args[0]; if (firstArg == "-?" || firstArg == "/?" || firstArg == "-help") { ShowHelp(); return 1; } int width = -1, height = -1; bool showWindow = args.Length == 0; for (int i = 0; i < args.Length;) { if (args[i] == "-w") { showWindow = true; i++; continue; } if (args[i] == "-s") { i++; string widthText = TakeNextArg(args, ref i); string heightText = TakeNextArg(args, ref i); if (widthText == null || heightText == null || !Int32.TryParse(widthText, out width) || !Int32.TryParse(heightText, out height)) { ShowHelp(); return 1; } } } if (showWindow) { var form = new EditorForm(); if (width > 0) { //form.ClientSize = new System.Drawing.Size(width, height); form.Size = new System.Drawing.Size(width, height); } form.ShowDialog(); return 0; } PrintOutTokenColors(args[0]); return 0; } static void PrintOutTokenColors(string path) { IDxcIntelliSense isense; try { isense = HlslDxcLib.CreateDxcIntelliSense(); } catch (System.DllNotFoundException dllNotFound) { Console.WriteLine("Unable to create IntelliSense helper - DLL not found there."); Console.WriteLine(dllNotFound.ToString()); return; } catch (Exception e) { Console.WriteLine("Unable to create IntelliSense helper."); Console.WriteLine(e.ToString()); return; } IDxcIndex index = isense.CreateIndex(); string fileName = path; string fileContents = System.IO.File.ReadAllText(path); string[] commandLineArgs = new string[] { "-ferror-limit=200" }; IDxcUnsavedFile[] unsavedFiles = new IDxcUnsavedFile[] { new TrivialDxcUnsavedFile(fileName, fileContents) }; Console.WriteLine("{0}:\n{1}", fileName, fileContents); IDxcTranslationUnit tu = index.ParseTranslationUnit(fileName, commandLineArgs, commandLineArgs.Length, unsavedFiles, (uint)unsavedFiles.Length, 0); if (tu == null) { Console.WriteLine("Unable to parse translation unit"); } else { IDxcSourceRange range = tu.GetCursor().GetExtent(); IDxcToken[] tokens; uint tokenCount; tu.Tokenize(range, out tokens, out tokenCount); Console.WriteLine("{0} tokens found.", tokenCount); for (UInt32 i = 0; i < tokenCount; i++) { PrintToken(tokens[i]); } } } static string LocationToString(IDxcSourceLocation location) { IDxcFile file; UInt32 line, col, offset; location.GetSpellingLocation(out file, out line, out col, out offset); return String.Format("{0}:{1}", line, col); } static string RangeToString(IDxcSourceRange range) { return LocationToString(range.GetStart()) + "-" + LocationToString(range.GetEnd()); } static void PrintToken(IDxcToken token) { Console.WriteLine(" '{0}' of type {1} at [{2}]", token.GetSpelling(), token.GetKind().ToString(), RangeToString(token.GetExtent())); } } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/dndxc.csproj.txt
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{0A863FD1-FD94-42CF-8190-A3CA605A6459}</ProjectGuid> <OutputType>WinExe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MainNs</RootNamespace> <AssemblyName>dndxc</AssemblyName> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <WarningLevel>4</WarningLevel> <!-- Allow unsafe blocks to extract strings from blobs; might want to do this in IDxcLibrary. --> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- Typical C# projects output to bin\Release or bin\Debug depending on the configuration. --> <!-- In this case, we always output to the same location, next to where the native files are. --> <!-- We also build in every case, and only change the debug flags accordingly. --> <PlatformTarget>${DOTNET_PLATFORM_TARGET}</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <OutputPath>${DOS_STYLE_OUTPUT_DIRECTORY}\Debug\bin</OutputPath> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'RelWithDebInfo' "> <OutputPath>${DOS_STYLE_OUTPUT_DIRECTORY}\RelWithDebInfo\bin</OutputPath> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <DefineConstants>TRACE</DefineConstants> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <OutputPath>${DOS_STYLE_OUTPUT_DIRECTORY}\Release\bin</OutputPath> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <DefineConstants>TRACE</DefineConstants> </PropertyGroup> <PropertyGroup> <StartupObject /> </PropertyGroup> <PropertyGroup> <ApplicationManifest>${DOS_STYLE_SOURCE_DIR}\app.manifest</ApplicationManifest> </PropertyGroup> <PropertyGroup> <ApplicationIcon>${DOS_STYLE_SOURCE_DIR}\dxc.ico</ApplicationIcon> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Drawing" /> <Reference Include="System.Windows.Forms" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="${DOS_STYLE_SOURCE_DIR}\AsmColorizer.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\D3DCompiler.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\dia2.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\DotNetDxc.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\BinaryViewControl.cs"> <SubType>Component</SubType> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\DxilBitcodeReader.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\FindDialog.cs"> <SubType>Form</SubType> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\FindDialog.Designer.cs"> <DependentUpon>FindDialog.cs</DependentUpon> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\EditorForm.cs"> <SubType>Form</SubType> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\EditorForm.Designer.cs"> <DependentUpon>EditorForm.cs</DependentUpon> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\EditorModels.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\GoToDialog.cs"> <SubType>Form</SubType> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\GoToDialog.Designer.cs"> <DependentUpon>GoToDialog.cs</DependentUpon> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\HlslHost.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\OptEditorForm.cs"> <SubType>Form</SubType> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\OptEditorForm.Designer.cs"> <DependentUpon>OptEditorForm.cs</DependentUpon> </Compile> <Compile Include="${DOS_STYLE_SOURCE_DIR}\Tom.cs" /> <Compile Include="${DOS_STYLE_SOURCE_DIR}\Program.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="${DOS_STYLE_SOURCE_DIR}\README.md" /> <EmbeddedResource Include="${DOS_STYLE_SOURCE_DIR}\EditorForm.resx"> <DependentUpon>EditorForm.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="${DOS_STYLE_SOURCE_DIR}\FindDialog.resx"> <DependentUpon>FindDialog.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="${DOS_STYLE_SOURCE_DIR}\GoToDialog.resx"> <DependentUpon>GoToDialog.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="${DOS_STYLE_SOURCE_DIR}\OptEditorForm.resx"> <DependentUpon>OptEditorForm.cs</DependentUpon> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="${DOS_STYLE_SOURCE_DIR}\app.manifest" /> </ItemGroup> <ItemGroup> <Resource Include="${DOS_STYLE_SOURCE_DIR}\dxc.ico" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/GoToDialog.Designer.cs
/////////////////////////////////////////////////////////////////////////////// // // // GoToDialog.Designer..cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// namespace MainNs { partial class GoToDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.GoToLabel = new System.Windows.Forms.Label(); this.GoToBox = new System.Windows.Forms.TextBox(); this.OKButton = new System.Windows.Forms.Button(); this.TheCancelButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // GoToLabel // this.GoToLabel.AutoSize = true; this.GoToLabel.Location = new System.Drawing.Point(13, 13); this.GoToLabel.Name = "GoToLabel"; this.GoToLabel.Size = new System.Drawing.Size(79, 20); this.GoToLabel.TabIndex = 0; this.GoToLabel.Text = "GoToLine"; // // GoToBox // this.GoToBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.GoToBox.Location = new System.Drawing.Point(12, 36); this.GoToBox.Name = "GoToBox"; this.GoToBox.Size = new System.Drawing.Size(290, 26); this.GoToBox.TabIndex = 1; this.GoToBox.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // OKButton // this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.OKButton.Location = new System.Drawing.Point(100, 68); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(99, 28); this.OKButton.TabIndex = 2; this.OKButton.Text = "OK"; this.OKButton.UseVisualStyleBackColor = true; // // TheCancelButton // this.TheCancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.TheCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.TheCancelButton.Location = new System.Drawing.Point(205, 68); this.TheCancelButton.Name = "TheCancelButton"; this.TheCancelButton.Size = new System.Drawing.Size(97, 28); this.TheCancelButton.TabIndex = 3; this.TheCancelButton.Text = "Cancel"; this.TheCancelButton.UseVisualStyleBackColor = true; // // GoToDialog // this.AcceptButton = this.OKButton; this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.TheCancelButton; this.ClientSize = new System.Drawing.Size(314, 106); this.Controls.Add(this.TheCancelButton); this.Controls.Add(this.OKButton); this.Controls.Add(this.GoToBox); this.Controls.Add(this.GoToLabel); this.Name = "GoToDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Go To Line"; this.Load += new System.EventHandler(this.GoToDialog_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label GoToLabel; private System.Windows.Forms.TextBox GoToBox; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.Button TheCancelButton; } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/BinaryViewControl.cs
/////////////////////////////////////////////////////////////////////////////// // // // BinaryViewControl.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MainNs { public class BinaryViewControl : Control { private const int LeftMargin = 8; private const int RightMargin = 8; private const int TopMargin = 8; private const int BytesPerLine = 8; private const int BottomMargin = 8; private const int ContentGutter = 8; private const int AddressCount = 4; private byte[] bytes; private int LineCount; private float LineHeight; private float CharWidth; private int selectionOffset; private int selectionLength; private int selectionEnd; private int selectionByteOffset; private int selectionByteLength; public BinaryViewControl() { } public byte[] Bytes { get { return this.bytes; } set { this.bytes = value; this.OnBytesChanged(); } } public void SetSelection(int offset, int length) { this.selectionOffset = offset; this.selectionLength = length; this.selectionByteOffset = offset / 8; this.selectionByteLength = (offset + length) / 8 - this.selectionByteOffset; if (length % 8 > 0) this.selectionByteLength += 1; this.selectionEnd = offset + length; this.Invalidate(); } private void OnBytesChanged() { if (this.Bytes == null) return; using (Graphics g = this.CreateGraphics()) using (GraphicResources gr = new GraphicResources(g)) { SizeF sampleText = g.MeasureString("Wj", gr.Font); LineHeight = sampleText.Height; LineCount = (int)Math.Ceiling((float)this.Bytes.Length / BytesPerLine); this.Height = (int)(LineHeight * LineCount) + TopMargin + BottomMargin; this.CharWidth = sampleText.Width / 2; this.Width = (int)( LeftMargin + AddressCount * CharWidth + ContentGutter + BytesPerLine * CharWidth * 8 + ContentGutter * BytesPerLine + RightMargin); } } private static string[] NibbleBits = System.Linq.Enumerable.Range(0, 16).Select(i => NibbleAsBitString(i)).ToArray(); private static string NibbleAsBitString(int i) { char[] ch = new char[4]; ch[0] = (0 == (i & 1 << 3)) ? '0' : '1'; ch[1] = (0 == (i & 1 << 2)) ? '0' : '1'; ch[2] = (0 == (i & 1 << 1)) ? '0' : '1'; ch[3] = (0 == (i & 1)) ? '0' : '1'; return new string(ch); } private static string ByteAsBitString(byte b) { return NibbleBits[(b & 0xF0) >> 4] + NibbleBits[b & 0x0F]; } private string SelectionIntersection(string bits, int byteOffset) { // Fast cases - no selection, or no intersection. if (this.selectionLength == 0) return null; if (byteOffset < this.selectionByteOffset || this.selectionByteLength + this.selectionByteOffset < byteOffset) return null; int bitOffset = byteOffset * 8; // Last fast case: everything intersects. if (this.selectionOffset <= bitOffset && (bitOffset + 8) <= this.selectionEnd) return bits; StringBuilder sb = new StringBuilder(bits); for (int i = 0; i < 8; ++i) { // If no intersection, clear bit. if (bitOffset < this.selectionOffset || this.selectionEnd <= bitOffset) { sb[bits.Length - i - 1] = ' '; } ++bitOffset; } return sb.ToString(); } public class BitEventArgs : EventArgs { public readonly int BitOffset; public BitEventArgs(int bitOffset) { this.BitOffset = bitOffset; } } public event EventHandler<BitEventArgs> BitClick; public event EventHandler<BitEventArgs> BitMouseMove; public class HitTestResult { public int X; public int Y; public int Line; public bool AddressHit; public bool IsHit; public int BitOffset; } private HitTestResult HitTest(MouseEventArgs e) { if (this.bytes.Length == 0 || LineHeight == 0) { return new HitTestResult(); } int x = e.X; int y = e.Y; int line = (int)((y - TopMargin) / LineHeight); bool addressHit; int bitOffset = line * BytesPerLine * 8; // Remove the left margin, address and gutter. x -= LeftMargin; x -= (int)(AddressCount * CharWidth); x -= ContentGutter; if (x > 0) { addressHit = false; // See how many bytes to remove. float byteWidth = ContentGutter + CharWidth * 8; int byteCount = (int)(x / byteWidth); x -= (int)(byteCount * byteWidth); bitOffset += byteCount * 8; } else { addressHit = true; } // Snap to valid values. if (bitOffset < 0) { bitOffset = 0; } else if (bitOffset >= this.bytes.Length * 8) { bitOffset = this.bytes.Length * 8 - 1; } return new HitTestResult() { X = e.X, Y = e.Y, Line = line, AddressHit = addressHit, BitOffset = bitOffset, IsHit = true }; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); HitTestResult hitTest = HitTest(e); if (hitTest.IsHit && !hitTest.AddressHit) this.BitMouseMove(this, new BitEventArgs(hitTest.BitOffset)); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left) return; HitTestResult hitTest = HitTest(e); if (hitTest.IsHit && !hitTest.AddressHit) this.BitClick(this, new BitEventArgs(hitTest.BitOffset)); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (this.Bytes == null) return; using (GraphicResources gr = new GraphicResources(e.Graphics)) { int offset = 0; float y = TopMargin; while (offset < this.Bytes.Length) { // Start a new line. float x = LeftMargin; // Write the offset on the left margin. string offsetText = offset.ToString("X4"); e.Graphics.DrawString(offsetText, gr.Font, gr.BrushForAddress, x, y); x += AddressCount * CharWidth; for (int i = 0; i < BytesPerLine; ++i) { if (offset == this.Bytes.Length) break; byte b = this.Bytes[offset]; x += ContentGutter; string bits = ByteAsBitString(b); e.Graphics.DrawString(bits, gr.Font, gr.BrushForNonSelection, x, y); bits = SelectionIntersection(bits, offset); if (bits != null) { e.Graphics.DrawString(bits, gr.Font, gr.BrushForSelection, x, y); } x += 8 * CharWidth; offset++; } y += LineHeight; } } } class GraphicResources : IDisposable { private Font fixedFont; internal GraphicResources(Graphics graphics) { fixedFont = new Font("Consolas", 10); } public void Dispose() { fixedFont.Dispose(); } public Font Font { get { return fixedFont; } } public Brush BrushForAddress { get { return Brushes.Black; } } public Brush BrushForNonSelection { get { return Brushes.Gray; } } public Brush BrushForSelection { get { return Brushes.Black; } } } } [DebuggerDisplay("Range {Offset} +{Length}")] public class TreeNodeRange { public TreeNodeRange(int offset, int length) { Debug.Assert(length > 0); Offset = offset; Length = length; } public int Offset; public int Length; public bool Contains(int bitOffset) { return Offset <= bitOffset && bitOffset < Offset + Length; } public static TreeNode For(string text) { return new TreeNode(text); } public static TreeNode For(string text, int offset, int length) { TreeNode result = new TreeNode(text); result.Tag = new TreeNodeRange(offset, length); return result; } } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/DotNetDxc.cs
/////////////////////////////////////////////////////////////////////////////// // // // DotNetDxc.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides P/Invoke declarations for dxcompiler HLSL support. // // // /////////////////////////////////////////////////////////////////////////////// #region Namespaces. using System; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #endregion Namespaces. namespace DotNetDxc { public enum DxcGlobalOptions : uint { DxcGlobalOpt_None = 0x0, DxcGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, DxcGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, DxcGlobalOpt_ThreadBackgroundPriorityForAll } [Flags] public enum DxcValidatorFlags : uint { Default = 0, InPlaceEdit = 1, ValidMask = 1 } [Flags] public enum DxcVersionInfoFlags : uint { None = 0, Debug = 1 } /// <summary> /// A cursor representing some element in the abstract syntax tree for /// a translation unit. /// </summary> /// <remarks> /// The cursor abstraction unifies the different kinds of entities in a /// program--declaration, statements, expressions, references to declarations, /// etc.--under a single "cursor" abstraction with a common set of operations. /// Common operation for a cursor include: getting the physical location in /// a source file where the cursor points, getting the name associated with a /// cursor, and retrieving cursors for any child nodes of a particular cursor. /// <remarks> [ComImport] [Guid("1467b985-288d-4d2a-80c1-ef89c42c40bc")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcCursor { IDxcSourceRange GetExtent(); IDxcSourceLocation GetLocation(); // <summary>Describes what kind of construct this cursor refers to.</summary> DxcCursorKind GetCursorKind(); DxcCursorKindFlags GetCursorKindFlags(); IDxcCursor GetSemanticParent(); IDxcCursor GetLexicalParent(); IDxcType GetCursorType(); int GetNumArguments(); IDxcCursor GetArgumentAt(int index); IDxcCursor GetReferencedCursor(); IDxcCursor GetDefinitionCursor(); void FindReferencesInFile(IDxcFile file, UInt32 skip, UInt32 top, out uint resultLength, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface, SizeParamIndex = 3)] out IDxcCursor[] cursors); [return: MarshalAs(UnmanagedType.LPStr)] string GetSpelling(); bool IsEqualTo(IDxcCursor other); bool IsNull(); } [ComImport] [Guid("4f76b234-3659-4d33-99b0-3b0db994b564")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcDiagnostic { [return: MarshalAs(UnmanagedType.LPStr)] string FormatDiagnostic(DxcDiagnosticDisplayOptions options); DxcDiagnosticSeverity GetSeverity(); IDxcSourceLocation GetLocation(); [return: MarshalAs(UnmanagedType.LPStr)] string GetSpelling(); [return: MarshalAs(UnmanagedType.LPStr)] string GetCategoryText(); UInt32 GetNumRanges(); IDxcSourceRange GetRangeAt(UInt32 index); UInt32 GetNumFixIts(); [return: MarshalAs(UnmanagedType.LPStr)] string GetFixItAt(UInt32 index, out IDxcSourceRange range); } /// <summary> /// Use this interface to represent a file (saved or in-memory). /// </summary> [ComImport] [Guid("bb2fca9e-1478-47ba-b08c-2c502ada4895")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcFile { [return: MarshalAs(UnmanagedType.LPStr)] string GetName(); } [ComImport] [Guid("b1f99513-46d6-4112-8169-dd0d6053f17d")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcIntelliSense { IDxcIndex CreateIndex(); IDxcSourceLocation GetNullLocation(); IDxcSourceRange GetNullRange(); IDxcSourceRange GetRange(IDxcSourceLocation start, IDxcSourceLocation end); DxcDiagnosticDisplayOptions GetDefaultDiagnosticDisplayOptions(); DxcTranslationUnitFlags GetDefaultEditingTUOptions(); } /// <summary> /// Use this interface to represent the context in which translation units are parsed. /// </summary> [ComImport] [Guid("937824a0-7f5a-4815-9ba7-7fc0424f4173")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcIndex { void SetGlobalOptions(DxcGlobalOptions options); DxcGlobalOptions GetGlobalOptions(); IDxcTranslationUnit ParseTranslationUnit( [MarshalAs(UnmanagedType.LPStr)] string source_filename, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] commandLineArgs, int num_command_line_args, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface)] IDxcUnsavedFile[] unsavedFiles, uint num_unsaved_files, uint options); } /// <summary> /// Describes a location in a source file. /// </summary> [Guid("8e7ddf1c-d7d3-4d69-b286-85fccba1e0cf")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcSourceLocation { bool IsEqualTo(IDxcSourceLocation other); void GetSpellingLocation(out IDxcFile file, out UInt32 line, out UInt32 col, out UInt32 offset); } /// <summary> /// Describes a range of text in a source file. /// </summary> [ComImport] [Guid("f1359b36-a53f-4e81-b514-b6b84122a13f")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcSourceRange { bool IsNull(); IDxcSourceLocation GetStart(); IDxcSourceLocation GetEnd(); } /// <summary> /// Describes a single preprocessing token. /// </summary> [ComImport] [Guid("7f90b9ff-a275-4932-97d8-3cfd234482a2")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcToken { DxcTokenKind GetKind(); IDxcSourceLocation GetLocation(); IDxcSourceRange GetExtent(); [return: MarshalAs(UnmanagedType.LPStr)] string GetSpelling(); } [ComImport] [Guid("9677dee0-c0e5-46a1-8b40-3db3168be63d")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcTranslationUnit { IDxcCursor GetCursor(); void Tokenize(IDxcSourceRange range, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface, SizeParamIndex=2)] out IDxcToken[] tokens, out uint tokenCount); IDxcSourceLocation GetLocation(IDxcFile file, UInt32 line, UInt32 column); UInt32 GetNumDiagnostics(); IDxcDiagnostic GetDiagnosticAt(UInt32 index); IDxcFile GetFile([MarshalAs(UnmanagedType.LPStr)]string name); [return: MarshalAs(UnmanagedType.LPStr)] string GetFileName(); void Reparse( [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface)] IDxcUnsavedFile[] unsavedFiles, uint num_unsaved_files); IDxcCursor GetCursorForLocation(IDxcSourceLocation location); IDxcSourceLocation GetLocationForOffset(IDxcFile file, UInt32 offset); void GetSkippedRanges(IDxcFile file, out uint rangeCount, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface, SizeParamIndex=1)] out IDxcSourceRange[] ranges); void GetDiagnosticDetails(UInt32 index, DxcDiagnosticDisplayOptions options, out UInt32 errorCode, out UInt32 errorLine, out UInt32 errorColumn, [MarshalAs(UnmanagedType.BStr)] out string errorFile, out UInt32 errorOffset, out UInt32 errorLength, [MarshalAs(UnmanagedType.BStr)] out string errorMessage); } [ComImport] [Guid("2ec912fd-b144-4a15-ad0d-1c5439c81e46")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcType { [return: MarshalAs(UnmanagedType.LPStr)] string GetSpelling(); bool IsEqualTo(IDxcType other); }; [ComImport] [Guid("8ec00f98-07d0-4e60-9d7c-5a50b5b0017f")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcUnsavedFile { void GetFileName([MarshalAs(UnmanagedType.LPStr)] out string value); void GetContents([MarshalAs(UnmanagedType.LPStr)] out string value); void GetLength(out UInt32 length); } [ComImport] [Guid("A6E82BD2-1FD7-4826-9811-2857E797F49A")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcValidator { IDxcOperationResult Validate(IDxcBlob shader, DxcValidatorFlags flags); } [ComImport] [Guid("b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcVersionInfo { void GetVersion(out UInt32 major, out UInt32 minor); DxcVersionInfoFlags GetFlags(); } [ComImport] [Guid("c012115b-8893-4eb9-9c5a-111456ea1c45")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcRewriter { IDxcRewriteResult RemoveUnusedGlobals( IDxcBlobEncoding pSource, [MarshalAs(UnmanagedType.LPWStr)]string pEntryPoint, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct)] DXCDefine[] pDefines, uint defineCount); IDxcRewriteResult RewriteUnchanged( IDxcBlobEncoding pSource, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct)] DXCDefine[] pDefines, uint defineCount); IDxcRewriteResult RewriteUnchangedWithInclude(IDxcBlobEncoding pSource, [MarshalAs(UnmanagedType.LPWStr)] string pName, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct)] DXCDefine[] pDefines, uint defineCount, IDxcIncludeHandler includeHandler, uint rewriteOption); } [ComImport] [Guid("CEDB484A-D4E9-445A-B991-CA21CA157DC2")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcRewriteResult { uint GetStatus(); IDxcBlobEncoding GetRewrite(); IDxcBlobEncoding GetErrorBuffer(); } [StructLayout(LayoutKind.Sequential)] public struct DXCEncodedText { [MarshalAs(UnmanagedType.LPStr)] public string pText; public uint Size; public uint CodePage; //should always be UTF-8 for this use } [StructLayout(LayoutKind.Sequential)] public struct DXCDefine { [MarshalAs(UnmanagedType.LPWStr)] public string pName; [MarshalAs(UnmanagedType.LPWStr)] public string pValue; } public class TrivialDxcUnsavedFile : IDxcUnsavedFile { private readonly string fileName; private readonly string contents; public TrivialDxcUnsavedFile(string fileName, string contents) { //System.Diagnostics.Debug.Assert(fileName != null); //System.Diagnostics.Debug.Assert(contents != null); this.fileName = fileName; this.contents = contents; } public void GetFileName(out string value) { value = this.fileName; } public void GetContents(out string value) { value = this.contents; } public void GetLength(out UInt32 length) { length = (UInt32)this.contents.Length; } } public delegate int DxcCreateInstanceFn(ref Guid clsid, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object instance); public class DefaultDxcLib { [DllImport(@"dxcompiler.dll", CallingConvention = CallingConvention.StdCall)] private static extern int DxcCreateInstance( ref Guid clsid, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object instance); [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static DxcCreateInstanceFn GetDxcCreateInstanceFn() { return DxcCreateInstance; } } public class HlslDxcLib { private static Guid CLSID_DxcAssembler = new Guid("D728DB68-F903-4F80-94CD-DCCF76EC7151"); private static Guid CLSID_DxcDiaDataSource = new Guid("CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F"); private static Guid CLSID_DxcIntelliSense = new Guid("3047833c-d1c0-4b8e-9d40-102878605985"); private static Guid CLSID_DxcRewriter = new Guid("b489b951-e07f-40b3-968d-93e124734da4"); private static Guid CLSID_DxcCompiler = new Guid("73e22d93-e6ce-47f3-b5bf-f0664f39c1b0"); private static Guid CLSID_DxcLinker = new Guid("EF6A8087-B0EA-4D56-9E45-D07E1A8B7806"); private static Guid CLSID_DxcContainerReflection = new Guid("b9f54489-55b8-400c-ba3a-1675e4728b91"); private static Guid CLSID_DxcLibrary = new Guid("6245D6AF-66E0-48FD-80B4-4D271796748C"); private static Guid CLSID_DxcOptimizer = new Guid("AE2CD79F-CC22-453F-9B6B-B124E7A5204C"); private static Guid CLSID_DxcValidator = new Guid("8CA3E215-F728-4CF3-8CDD-88AF917587A1"); public static DxcCreateInstanceFn DxcCreateInstanceFn; [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError =true, CharSet=CharSet.Unicode, ExactSpelling = true)] private static extern IntPtr LoadLibraryW([MarshalAs(UnmanagedType.LPWStr)] string fileName); [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern IntPtr LoadLibraryExW([MarshalAs(UnmanagedType.LPWStr)] string fileName, IntPtr reserved, UInt32 flags); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling =true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); private const UInt32 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x0100; private const UInt32 LOAD_LIBRARY_DEFAULT_DIRS = 0x1000; public static DxcCreateInstanceFn LoadDxcCreateInstance(string dllPath, string fnName) { UInt32 flags = LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_DEFAULT_DIRS; IntPtr handle = LoadLibraryExW(dllPath, IntPtr.Zero, flags); if (handle == IntPtr.Zero) { throw new System.ComponentModel.Win32Exception(); } IntPtr fnPtr = GetProcAddress(handle, fnName); return (DxcCreateInstanceFn)Marshal.GetDelegateForFunctionPointer(fnPtr, typeof(DxcCreateInstanceFn)); } private static int DxcCreateInstance( ref Guid clsid, ref Guid iid, out object instance) { return DxcCreateInstanceFn(ref clsid, ref iid, out instance); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcAssembler CreateDxcAssembler() { Guid classId = CLSID_DxcAssembler; Guid interfaceId = typeof(IDxcAssembler).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcAssembler)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcCompiler CreateDxcCompiler() { Guid classId = CLSID_DxcCompiler; Guid interfaceId = typeof(IDxcCompiler).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcCompiler)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcLinker CreateDxcLinker() { Guid classId = CLSID_DxcLinker; Guid interfaceId = typeof(IDxcLinker).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcLinker)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcContainerReflection CreateDxcContainerReflection() { Guid classId = CLSID_DxcContainerReflection; Guid interfaceId = typeof(IDxcContainerReflection).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcContainerReflection)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static dia2.IDiaDataSource CreateDxcDiaDataSource() { Guid classId = CLSID_DxcDiaDataSource; Guid interfaceId = typeof(dia2.IDiaDataSource).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (dia2.IDiaDataSource)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcLibrary CreateDxcLibrary() { Guid classId = CLSID_DxcLibrary; Guid interfaceId = typeof(IDxcLibrary).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcLibrary)result; } // No inlining means that if DxcCreateInstance is not available for any reason, this // method will throw an exception (rather than possibly propagating) - caller should // guard against failures from this call. [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcIntelliSense CreateDxcIntelliSense() { Guid classId = CLSID_DxcIntelliSense; Guid interfaceId = typeof(IDxcIntelliSense).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcIntelliSense)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcOptimizer CreateDxcOptimizer() { Guid classId = CLSID_DxcOptimizer; Guid interfaceId = typeof(IDxcOptimizer).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcOptimizer)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcRewriter CreateDxcRewriter() { Guid classId = CLSID_DxcRewriter; Guid interfaceId = typeof(IDxcRewriter).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcRewriter)result; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static IDxcValidator CreateDxcValidator() { Guid classId = CLSID_DxcValidator; Guid interfaceId = typeof(IDxcValidator).GUID; object result; DxcCreateInstance(ref classId, ref interfaceId, out result); return (IDxcValidator)result; } } [Flags] public enum DxcCursorKindFlags : uint { None = 0, Declaration = 0x1, Reference = 0x2, Expression = 0x4, Statement = 0x8, Attribute = 0x10, Invalid = 0x20, TranslationUnit = 0x40, Preprocessing = 0x80, Unexposed = 0x100, } /// <summary> /// The kind of language construct in a translation unit that a cursor refers to. /// </summary> public enum DxcCursorKind : uint { /** * \brief A declaration whose specific kind is not exposed via this * interface. * * Unexposed declarations have the same operations as any other kind * of declaration; one can extract their location information, * spelling, find their definitions, etc. However, the specific kind * of the declaration is not reported. */ DxcCursor_UnexposedDecl = 1, /** \brief A C or C++ struct. */ DxcCursor_StructDecl = 2, /** \brief A C or C++ union. */ DxcCursor_UnionDecl = 3, /** \brief A C++ class. */ DxcCursor_ClassDecl = 4, /** \brief An enumeration. */ DxcCursor_EnumDecl = 5, /** * \brief A field (in C) or non-static data member (in C++) in a * struct, union, or C++ class. */ DxcCursor_FieldDecl = 6, /** \brief An enumerator constant. */ DxcCursor_EnumConstantDecl = 7, /** \brief A function. */ DxcCursor_FunctionDecl = 8, /** \brief A variable. */ DxcCursor_VarDecl = 9, /** \brief A function or method parameter. */ DxcCursor_ParmDecl = 10, /** \brief An Objective-C \@interface. */ DxcCursor_ObjCInterfaceDecl = 11, /** \brief An Objective-C \@interface for a category. */ DxcCursor_ObjCCategoryDecl = 12, /** \brief An Objective-C \@protocol declaration. */ DxcCursor_ObjCProtocolDecl = 13, /** \brief An Objective-C \@property declaration. */ DxcCursor_ObjCPropertyDecl = 14, /** \brief An Objective-C instance variable. */ DxcCursor_ObjCIvarDecl = 15, /** \brief An Objective-C instance method. */ DxcCursor_ObjCInstanceMethodDecl = 16, /** \brief An Objective-C class method. */ DxcCursor_ObjCClassMethodDecl = 17, /** \brief An Objective-C \@implementation. */ DxcCursor_ObjCImplementationDecl = 18, /** \brief An Objective-C \@implementation for a category. */ DxcCursor_ObjCCategoryImplDecl = 19, /** \brief A typedef */ DxcCursor_TypedefDecl = 20, /** \brief A C++ class method. */ DxcCursor_CXXMethod = 21, /** \brief A C++ namespace. */ DxcCursor_Namespace = 22, /** \brief A linkage specification, e.g. 'extern "C"'. */ DxcCursor_LinkageSpec = 23, /** \brief A C++ constructor. */ DxcCursor_Constructor = 24, /** \brief A C++ destructor. */ DxcCursor_Destructor = 25, /** \brief A C++ conversion function. */ DxcCursor_ConversionFunction = 26, /** \brief A C++ template type parameter. */ DxcCursor_TemplateTypeParameter = 27, /** \brief A C++ non-type template parameter. */ DxcCursor_NonTypeTemplateParameter = 28, /** \brief A C++ template template parameter. */ DxcCursor_TemplateTemplateParameter = 29, /** \brief A C++ function template. */ DxcCursor_FunctionTemplate = 30, /** \brief A C++ class template. */ DxcCursor_ClassTemplate = 31, /** \brief A C++ class template partial specialization. */ DxcCursor_ClassTemplatePartialSpecialization = 32, /** \brief A C++ namespace alias declaration. */ DxcCursor_NamespaceAlias = 33, /** \brief A C++ using directive. */ DxcCursor_UsingDirective = 34, /** \brief A C++ using declaration. */ DxcCursor_UsingDeclaration = 35, /** \brief A C++ alias declaration */ DxcCursor_TypeAliasDecl = 36, /** \brief An Objective-C \@synthesize definition. */ DxcCursor_ObjCSynthesizeDecl = 37, /** \brief An Objective-C \@dynamic definition. */ DxcCursor_ObjCDynamicDecl = 38, /** \brief An access specifier. */ DxcCursor_CXXAccessSpecifier = 39, DxcCursor_FirstDecl = DxcCursor_UnexposedDecl, DxcCursor_LastDecl = DxcCursor_CXXAccessSpecifier, /* References */ DxcCursor_FirstRef = 40, /* Decl references */ DxcCursor_ObjCSuperClassRef = 40, DxcCursor_ObjCProtocolRef = 41, DxcCursor_ObjCClassRef = 42, /** * \brief A reference to a type declaration. * * A type reference occurs anywhere where a type is named but not * declared. For example, given: * * \code * typedef unsigned size_type; * size_type size; * \endcode * * The typedef is a declaration of size_type (DxcCursor_TypedefDecl), * while the type of the variable "size" is referenced. The cursor * referenced by the type of size is the typedef for size_type. */ DxcCursor_TypeRef = 43, DxcCursor_CXXBaseSpecifier = 44, /** * \brief A reference to a class template, function template, template * template parameter, or class template partial specialization. */ DxcCursor_TemplateRef = 45, /** * \brief A reference to a namespace or namespace alias. */ DxcCursor_NamespaceRef = 46, /** * \brief A reference to a member of a struct, union, or class that occurs in * some non-expression context, e.g., a designated initializer. */ DxcCursor_MemberRef = 47, /** * \brief A reference to a labeled statement. * * This cursor kind is used to describe the jump to "start_over" in the * goto statement in the following example: * * \code * start_over: * ++counter; * * goto start_over; * \endcode * * A label reference cursor refers to a label statement. */ DxcCursor_LabelRef = 48, /// <summary> /// A reference to a set of overloaded functions or function templates /// that has not yet been resolved to a specific function or function template. /// </summary> /// <remarks> /// An overloaded declaration reference cursor occurs in C++ templates where /// a dependent name refers to a function. /// </remarks> DxcCursor_OverloadedDeclRef = 49, /** * \brief A reference to a variable that occurs in some non-expression * context, e.g., a C++ lambda capture list. */ DxcCursor_VariableRef = 50, DxcCursor_LastRef = DxcCursor_VariableRef, /* Error conditions */ DxcCursor_FirstInvalid = 70, DxcCursor_InvalidFile = 70, DxcCursor_NoDeclFound = 71, DxcCursor_NotImplemented = 72, DxcCursor_InvalidCode = 73, DxcCursor_LastInvalid = DxcCursor_InvalidCode, /* Expressions */ DxcCursor_FirstExpr = 100, /** * \brief An expression whose specific kind is not exposed via this * interface. * * Unexposed expressions have the same operations as any other kind * of expression; one can extract their location information, * spelling, children, etc. However, the specific kind of the * expression is not reported. */ DxcCursor_UnexposedExpr = 100, /** * \brief An expression that refers to some value declaration, such * as a function, varible, or enumerator. */ DxcCursor_DeclRefExpr = 101, /** * \brief An expression that refers to a member of a struct, union, * class, Objective-C class, etc. */ DxcCursor_MemberRefExpr = 102, /** \brief An expression that calls a function. */ DxcCursor_CallExpr = 103, /** \brief An expression that sends a message to an Objective-C object or class. */ DxcCursor_ObjCMessageExpr = 104, /** \brief An expression that represents a block literal. */ DxcCursor_BlockExpr = 105, /** \brief An integer literal. */ DxcCursor_IntegerLiteral = 106, /** \brief A floating point number literal. */ DxcCursor_FloatingLiteral = 107, /** \brief An imaginary number literal. */ DxcCursor_ImaginaryLiteral = 108, /** \brief A string literal. */ DxcCursor_StringLiteral = 109, /** \brief A character literal. */ DxcCursor_CharacterLiteral = 110, /** \brief A parenthesized expression, e.g. "(1)". * * This AST node is only formed if full location information is requested. */ DxcCursor_ParenExpr = 111, /** \brief This represents the unary-expression's (except sizeof and * alignof). */ DxcCursor_UnaryOperator = 112, /** \brief [C99 6.5.2.1] Array Subscripting. */ DxcCursor_ArraySubscriptExpr = 113, /** \brief A builtin binary operation expression such as "x + y" or * "x <= y". */ DxcCursor_BinaryOperator = 114, /** \brief Compound assignment such as "+=". */ DxcCursor_CompoundAssignOperator = 115, /** \brief The ?: ternary operator. */ DxcCursor_ConditionalOperator = 116, /** \brief An explicit cast in C (C99 6.5.4) or a C-style cast in C++ * (C++ [expr.cast]), which uses the syntax (Type)expr. * * For example: (int)f. */ DxcCursor_CStyleCastExpr = 117, /** \brief [C99 6.5.2.5] */ DxcCursor_CompoundLiteralExpr = 118, /** \brief Describes an C or C++ initializer list. */ DxcCursor_InitListExpr = 119, /** \brief The GNU address of label extension, representing &&label. */ DxcCursor_AddrLabelExpr = 120, /** \brief This is the GNU Statement Expression extension: ({int X=4; X;}) */ DxcCursor_StmtExpr = 121, /** \brief Represents a C11 generic selection. */ DxcCursor_GenericSelectionExpr = 122, /** \brief Implements the GNU __null extension, which is a name for a null * pointer constant that has integral type (e.g., int or long) and is the same * size and alignment as a pointer. * * The __null extension is typically only used by system headers, which define * NULL as __null in C++ rather than using 0 (which is an integer that may not * match the size of a pointer). */ DxcCursor_GNUNullExpr = 123, /** \brief C++'s static_cast<> expression. */ DxcCursor_CXXStaticCastExpr = 124, /** \brief C++'s dynamic_cast<> expression. */ DxcCursor_CXXDynamicCastExpr = 125, /** \brief C++'s reinterpret_cast<> expression. */ DxcCursor_CXXReinterpretCastExpr = 126, /** \brief C++'s const_cast<> expression. */ DxcCursor_CXXConstCastExpr = 127, /** \brief Represents an explicit C++ type conversion that uses "functional" * notion (C++ [expr.type.conv]). * * Example: * \code * x = int(0.5); * \endcode */ DxcCursor_CXXFunctionalCastExpr = 128, /** \brief A C++ typeid expression (C++ [expr.typeid]). */ DxcCursor_CXXTypeidExpr = 129, /** \brief [C++ 2.13.5] C++ Boolean Literal. */ DxcCursor_CXXBoolLiteralExpr = 130, /** \brief [C++0x 2.14.7] C++ Pointer Literal. */ DxcCursor_CXXNullPtrLiteralExpr = 131, /** \brief Represents the "this" expression in C++ */ DxcCursor_CXXThisExpr = 132, /** \brief [C++ 15] C++ Throw Expression. * * This handles 'throw' and 'throw' assignment-expression. When * assignment-expression isn't present, Op will be null. */ DxcCursor_CXXThrowExpr = 133, /** \brief A new expression for memory allocation and constructor calls, e.g: * "new CXXNewExpr(foo)". */ DxcCursor_CXXNewExpr = 134, /** \brief A delete expression for memory deallocation and destructor calls, * e.g. "delete[] pArray". */ DxcCursor_CXXDeleteExpr = 135, /** \brief A unary expression. */ DxcCursor_UnaryExpr = 136, /** \brief An Objective-C string literal i.e. @"foo". */ DxcCursor_ObjCStringLiteral = 137, /** \brief An Objective-C \@encode expression. */ DxcCursor_ObjCEncodeExpr = 138, /** \brief An Objective-C \@selector expression. */ DxcCursor_ObjCSelectorExpr = 139, /** \brief An Objective-C \@protocol expression. */ DxcCursor_ObjCProtocolExpr = 140, /** \brief An Objective-C "bridged" cast expression, which casts between * Objective-C pointers and C pointers, transferring ownership in the process. * * \code * NSString *str = (__bridge_transfer NSString *)CFCreateString(); * \endcode */ DxcCursor_ObjCBridgedCastExpr = 141, /** \brief Represents a C++0x pack expansion that produces a sequence of * expressions. * * A pack expansion expression contains a pattern (which itself is an * expression) followed by an ellipsis. For example: * * \code * template<typename F, typename ...Types> * void forward(F f, Types &&...args) { * f(static_cast<Types&&>(args)...); * } * \endcode */ DxcCursor_PackExpansionExpr = 142, /** \brief Represents an expression that computes the length of a parameter * pack. * * \code * template<typename ...Types> * struct count { * static const unsigned value = sizeof...(Types); * }; * \endcode */ DxcCursor_SizeOfPackExpr = 143, /* \brief Represents a C++ lambda expression that produces a local function * object. * * \code * void abssort(float *x, unsigned N) { * std::sort(x, x + N, * [](float a, float b) { * return std::abs(a) < std::abs(b); * }); * } * \endcode */ DxcCursor_LambdaExpr = 144, /** \brief Objective-c Boolean Literal. */ DxcCursor_ObjCBoolLiteralExpr = 145, /** \brief Represents the "self" expression in a ObjC method. */ DxcCursor_ObjCSelfExpr = 146, DxcCursor_LastExpr = DxcCursor_ObjCSelfExpr, /* Statements */ DxcCursor_FirstStmt = 200, /** * \brief A statement whose specific kind is not exposed via this * interface. * * Unexposed statements have the same operations as any other kind of * statement; one can extract their location information, spelling, * children, etc. However, the specific kind of the statement is not * reported. */ DxcCursor_UnexposedStmt = 200, /** \brief A labelled statement in a function. * * This cursor kind is used to describe the "start_over:" label statement in * the following example: * * \code * start_over: * ++counter; * \endcode * */ DxcCursor_LabelStmt = 201, /** \brief A group of statements like { stmt stmt }. * * This cursor kind is used to describe compound statements, e.g. function * bodies. */ DxcCursor_CompoundStmt = 202, /** \brief A case statement. */ DxcCursor_CaseStmt = 203, /** \brief A default statement. */ DxcCursor_DefaultStmt = 204, /** \brief An if statement */ DxcCursor_IfStmt = 205, /** \brief A switch statement. */ DxcCursor_SwitchStmt = 206, /** \brief A while statement. */ DxcCursor_WhileStmt = 207, /** \brief A do statement. */ DxcCursor_DoStmt = 208, /** \brief A for statement. */ DxcCursor_ForStmt = 209, /** \brief A goto statement. */ DxcCursor_GotoStmt = 210, /** \brief An indirect goto statement. */ DxcCursor_IndirectGotoStmt = 211, /** \brief A continue statement. */ DxcCursor_ContinueStmt = 212, /** \brief A break statement. */ DxcCursor_BreakStmt = 213, /** \brief A return statement. */ DxcCursor_ReturnStmt = 214, /** \brief A GCC inline assembly statement extension. */ DxcCursor_GCCAsmStmt = 215, DxcCursor_AsmStmt = DxcCursor_GCCAsmStmt, /** \brief Objective-C's overall \@try-\@catch-\@finally statement. */ DxcCursor_ObjCAtTryStmt = 216, /** \brief Objective-C's \@catch statement. */ DxcCursor_ObjCAtCatchStmt = 217, /** \brief Objective-C's \@finally statement. */ DxcCursor_ObjCAtFinallyStmt = 218, /** \brief Objective-C's \@throw statement. */ DxcCursor_ObjCAtThrowStmt = 219, /** \brief Objective-C's \@synchronized statement. */ DxcCursor_ObjCAtSynchronizedStmt = 220, /** \brief Objective-C's autorelease pool statement. */ DxcCursor_ObjCAutoreleasePoolStmt = 221, /** \brief Objective-C's collection statement. */ DxcCursor_ObjCForCollectionStmt = 222, /** \brief C++'s catch statement. */ DxcCursor_CXXCatchStmt = 223, /** \brief C++'s try statement. */ DxcCursor_CXXTryStmt = 224, /** \brief C++'s for (* : *) statement. */ DxcCursor_CXXForRangeStmt = 225, /** \brief Windows Structured Exception Handling's try statement. */ DxcCursor_SEHTryStmt = 226, /** \brief Windows Structured Exception Handling's except statement. */ DxcCursor_SEHExceptStmt = 227, /** \brief Windows Structured Exception Handling's finally statement. */ DxcCursor_SEHFinallyStmt = 228, /** \brief A MS inline assembly statement extension. */ DxcCursor_MSAsmStmt = 229, /** \brief The null satement ";": C99 6.8.3p3. * * This cursor kind is used to describe the null statement. */ DxcCursor_NullStmt = 230, /** \brief Adaptor class for mixing declarations with statements and * expressions. */ DxcCursor_DeclStmt = 231, /** \brief OpenMP parallel directive. */ DxcCursor_OMPParallelDirective = 232, DxcCursor_LastStmt = DxcCursor_OMPParallelDirective, /** * \brief Cursor that represents the translation unit itself. * * The translation unit cursor exists primarily to act as the root * cursor for traversing the contents of a translation unit. */ DxcCursor_TranslationUnit = 300, /* Attributes */ DxcCursor_FirstAttr = 400, /** * \brief An attribute whose specific kind is not exposed via this * interface. */ DxcCursor_UnexposedAttr = 400, DxcCursor_IBActionAttr = 401, DxcCursor_IBOutletAttr = 402, DxcCursor_IBOutletCollectionAttr = 403, DxcCursor_CXXFinalAttr = 404, DxcCursor_CXXOverrideAttr = 405, DxcCursor_AnnotateAttr = 406, DxcCursor_AsmLabelAttr = 407, DxcCursor_PackedAttr = 408, DxcCursor_LastAttr = DxcCursor_PackedAttr, /* Preprocessing */ DxcCursor_PreprocessingDirective = 500, DxcCursor_MacroDefinition = 501, DxcCursor_MacroExpansion = 502, DxcCursor_MacroInstantiation = DxcCursor_MacroExpansion, DxcCursor_InclusionDirective = 503, DxcCursor_FirstPreprocessing = DxcCursor_PreprocessingDirective, DxcCursor_LastPreprocessing = DxcCursor_InclusionDirective, /* Extra Declarations */ /** * \brief A module import declaration. */ DxcCursor_ModuleImportDecl = 600, DxcCursor_FirstExtraDecl = DxcCursor_ModuleImportDecl, DxcCursor_LastExtraDecl = DxcCursor_ModuleImportDecl }; /// <summary>Describes a kind of token.</summary> public enum DxcTokenKind : uint { /// <summary>A token that contains some kind of punctuation.</summary> Punctuation = 0, /// <summary>A language keyword.</summary> Keyword = 1, /// <summary>An identifier (that is not a keyword).</summary> Identifier = 2, /// <summary>A numeric, string, or character literal.</summary> Literal = 3, /// <summary>A comment.</summary> Comment = 4, /// <summary>An unknown token (possibly known to a future version).</summary> Unknown = 5, /// <summary>The token matches a built-in type.</summary> BuiltInType = 6, }; public enum DxcDiagnosticDisplayOptions : uint { // Display the source-location information where the diagnostic was located. DxcDiagnostic_DisplaySourceLocation = 0x01, // If displaying the source-location information of the diagnostic, // also include the column number. DxcDiagnostic_DisplayColumn = 0x02, // If displaying the source-location information of the diagnostic, // also include information about source ranges in a machine-parsable format. DxcDiagnostic_DisplaySourceRanges = 0x04, // Display the option name associated with this diagnostic, if any. DxcDiagnostic_DisplayOption = 0x08, // Display the category number associated with this diagnostic, if any. DxcDiagnostic_DisplayCategoryId = 0x10, // Display the category name associated with this diagnostic, if any. DxcDiagnostic_DisplayCategoryName = 0x20 }; public enum DxcDiagnosticSeverity { // A diagnostic that has been suppressed, e.g., by a command-line option. DxcDiagnostic_Ignored = 0, // This diagnostic is a note that should be attached to the previous (non-note) diagnostic. DxcDiagnostic_Note = 1, // This diagnostic indicates suspicious code that may not be wrong. DxcDiagnostic_Warning = 2, // This diagnostic indicates that the code is ill-formed. DxcDiagnostic_Error = 3, // This diagnostic indicates that the code is ill-formed such that future // parser rec unlikely to produce useful results. DxcDiagnostic_Fatal = 4 }; public enum DxcTranslationUnitFlags : uint { // Used to indicate that no special translation-unit options are needed. DxcTranslationUnitFlags_None = 0x0, // Used to indicate that the parser should construct a "detailed" // preprocessing record, including all macro definitions and instantiations. DxcTranslationUnitFlags_DetailedPreprocessingRecord = 0x01, // Used to indicate that the translation unit is incomplete. DxcTranslationUnitFlags_Incomplete = 0x02, // Used to indicate that the translation unit should be built with an // implicit precompiled header for the preamble. DxcTranslationUnitFlags_PrecompiledPreamble = 0x04, // Used to indicate that the translation unit should cache some // code-completion results with each reparse of the source file. DxcTranslationUnitFlags_CacheCompletionResults = 0x08, // Used to indicate that the translation unit will be serialized with // SaveTranslationUnit. DxcTranslationUnitFlags_ForSerialization = 0x10, // DEPRECATED DxcTranslationUnitFlags_CXXChainedPCH = 0x20, // Used to indicate that function/method bodies should be skipped while parsing. DxcTranslationUnitFlags_SkipFunctionBodies = 0x40, // Used to indicate that brief documentation comments should be // included into the set of code completions returned from this translation // unit. DxcTranslationUnitFlags_IncludeBriefCommentsInCodeCompletion = 0x80, // Used to indicate that compilation should occur on the caller's thread. DxcTranslationUnitFlags_UseCallerThread = 0x800, }; [ComImport] [Guid("8BA5FB08-5195-40e2-AC58-0D989C3A0102")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcBlob { [PreserveSig] unsafe char* GetBufferPointer(); [PreserveSig] UInt32 GetBufferSize(); } [ComImport] [Guid("8BA5FB08-5195-40e2-AC58-0D989C3A0102")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcBlobEncoding : IDxcBlob { System.UInt32 GetEncoding(out bool unknown, out UInt32 codePage); } [ComImport] [Guid("CEDB484A-D4E9-445A-B991-CA21CA157DC2")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcOperationResult { Int32 GetStatus(); IDxcBlob GetResult(); IDxcBlobEncoding GetErrors(); } [ComImport] [Guid("7f61fc7d-950d-467f-b3e3-3c02fb49187c")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcIncludeHandler { IDxcBlob LoadSource(string fileName); } [ComImport] [Guid("091f7a26-1c1f-4948-904b-e6e3a8a771d5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcAssembler { IDxcOperationResult AssembleToContainer(IDxcBlob source); } [ComImport] [Guid("8c210bf3-011f-4422-8d70-6f9acb8db617")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcCompiler { IDxcOperationResult Compile(IDxcBlob source, string sourceName, string entryPoint, string targetProfile, [MarshalAs(UnmanagedType.LPArray, ArraySubType =UnmanagedType.LPWStr)] string[] arguments, int argCount, DXCDefine[] defines, int defineCount, IDxcIncludeHandler includeHandler); IDxcOperationResult Preprocess(IDxcBlob source, string sourceName, string[] arguments, int argCount, DXCDefine[] defines, int defineCount, IDxcIncludeHandler includeHandler); IDxcBlobEncoding Disassemble(IDxcBlob source); } [ComImport] [Guid("d2c21b26-8350-4bdc-976a-331ce6f4c54c")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcContainerReflection { void Load(IDxcBlob container); uint GetPartCount(); uint GetPartKind(uint idx); IDxcBlob GetPartContent(uint idx); [PreserveSig] int FindFirstPartKind(uint kind, out uint result); [return: MarshalAs(UnmanagedType.Interface, IidParameterIndex = 1)] object GetPartReflection(uint idx, Guid iid); } [ComImport] [Guid("e5204dc7-d18c-4c3c-bdfb-851673980fe7")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcLibrary { void SetMalloc(object malloc); IDxcBlob CreateBlobFromBlob(IDxcBlob blob, UInt32 offset, UInt32 length); IDxcBlobEncoding CreateBlobFromFile(string fileName, System.IntPtr codePage); IDxcBlobEncoding CreateBlobWithEncodingFromPinned(byte[] text, UInt32 size, UInt32 codePage); // IDxcBlobEncoding CreateBlobWithEncodingOnHeapCopy(IntrPtr text, UInt32 size, UInt32 codePage); IDxcBlobEncoding CreateBlobWithEncodingOnHeapCopy(string text, UInt32 size, UInt32 codePage); IDxcBlobEncoding CreateBlobWithEncodingOnMalloc(string text, object malloc, UInt32 size, UInt32 codePage); IDxcIncludeHandler CreateIncludeHandler(); System.Runtime.InteropServices.ComTypes.IStream CreateStreamFromBlobReadOnly(IDxcBlob blob); IDxcBlobEncoding GetBlobAstUf8(IDxcBlob blob); IDxcBlobEncoding GetBlobAstUf16(IDxcBlob blob); } [ComImport] [Guid("F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcLinker : IDxcCompiler { // Register a library with name to ref it later. int RegisterLibrary(string libName, IDxcBlob library); int Link( string entryName, string targetProfile, [MarshalAs(UnmanagedType.LPArray, ArraySubType =UnmanagedType.LPWStr)] string[] libNames, int libCount, [MarshalAs(UnmanagedType.LPArray, ArraySubType =UnmanagedType.LPWStr)] string[] pArguments, int argCount, out IDxcOperationResult result ); } [ComImport] [Guid("AE2CD79F-CC22-453F-9B6B-B124E7A5204C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcOptimizerPass { [return: MarshalAs(UnmanagedType.LPWStr)] string GetOptionName(); [return: MarshalAs(UnmanagedType.LPWStr)] string GetDescription(); uint GetOptionArgCount(); [return: MarshalAs(UnmanagedType.LPWStr)] string GetOptionArgName(uint argIndex); [return: MarshalAs(UnmanagedType.LPWStr)] string GetOptionArgDescription(uint argIndex); } [ComImport] [Guid("25740E2E-9CBA-401B-9119-4FB42F39F270")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxcOptimizer { int GetAvailablePassCount(); IDxcOptimizerPass GetAvailablePass(int index); void RunOptimizer(IDxcBlob source, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] options, int optionCount, out IDxcBlob outputModule, out IDxcBlobEncoding outputText); } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/CMakeLists.txt
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} ) file(TO_NATIVE_PATH "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}" DOS_STYLE_OUTPUT_DIRECTORY) file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}" DOS_STYLE_SOURCE_DIR) if (CMAKE_C_COMPILER_ARCHITECTURE_ID MATCHES "x64" ) set ( DOTNET_PLATFORM_TARGET "x64" ) elseif (CMAKE_GENERATOR STREQUAL "Visual Studio 12" ) set ( DOTNET_PLATFORM_TARGET "x86" ) else () set ( DOTNET_PLATFORM_TARGET "AnyCPU" ) endif () configure_file(dndxc.csproj.txt dndxc.csproj) include_external_msproject( dndxc ${CMAKE_CURRENT_BINARY_DIR}/dndxc.csproj TYPE FAE04EC0-301F-11D3-BF4B-00C04F79EFBC) set_target_properties(dndxc PROPERTIES FOLDER "Clang executables")
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/OptEditorForm.Designer.cs
namespace MainNs { partial class OptEditorForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TopContainer = new System.Windows.Forms.SplitContainer(); this.PassesListBox = new System.Windows.Forms.ListBox(); this.WorkContainer = new System.Windows.Forms.SplitContainer(); this.CodeBox = new System.Windows.Forms.RichTextBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.LeftButton = new System.Windows.Forms.RadioButton(); this.DiffButton = new System.Windows.Forms.RadioButton(); this.RightButton = new System.Windows.Forms.RadioButton(); this.ApplyChangesButton = new System.Windows.Forms.Button(); this.CopyContainerButton = new System.Windows.Forms.Button(); this.btnSaveAll = new System.Windows.Forms.Button(); this.btnViewCFGOnly = new System.Windows.Forms.Button(); this.LogBox = new System.Windows.Forms.RichTextBox(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.TopContainer)).BeginInit(); this.TopContainer.Panel1.SuspendLayout(); this.TopContainer.Panel2.SuspendLayout(); this.TopContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.WorkContainer)).BeginInit(); this.WorkContainer.Panel1.SuspendLayout(); this.WorkContainer.Panel2.SuspendLayout(); this.WorkContainer.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // TopContainer // this.TopContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.TopContainer.Location = new System.Drawing.Point(0, 0); this.TopContainer.Name = "TopContainer"; // // TopContainer.Panel1 // this.TopContainer.Panel1.Controls.Add(this.PassesListBox); // // TopContainer.Panel2 // this.TopContainer.Panel2.Controls.Add(this.WorkContainer); this.TopContainer.Size = new System.Drawing.Size(1497, 901); this.TopContainer.SplitterDistance = 498; this.TopContainer.TabIndex = 0; // // PassesListBox // this.PassesListBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PassesListBox.FormattingEnabled = true; this.PassesListBox.Location = new System.Drawing.Point(0, 0); this.PassesListBox.Name = "PassesListBox"; this.PassesListBox.Size = new System.Drawing.Size(498, 901); this.PassesListBox.TabIndex = 0; this.PassesListBox.SelectedIndexChanged += new System.EventHandler(this.PassesListBox_SelectedIndexChanged); // // WorkContainer // this.WorkContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.WorkContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.WorkContainer.Location = new System.Drawing.Point(0, 0); this.WorkContainer.Name = "WorkContainer"; this.WorkContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; // // WorkContainer.Panel1 // this.WorkContainer.Panel1.Controls.Add(this.CodeBox); this.WorkContainer.Panel1.Controls.Add(this.flowLayoutPanel1); // // WorkContainer.Panel2 // this.WorkContainer.Panel2.Controls.Add(this.LogBox); this.WorkContainer.Size = new System.Drawing.Size(995, 901); this.WorkContainer.SplitterDistance = 824; this.WorkContainer.TabIndex = 0; // // CodeBox // this.CodeBox.Dock = System.Windows.Forms.DockStyle.Fill; this.CodeBox.Location = new System.Drawing.Point(0, 32); this.CodeBox.Name = "CodeBox"; this.CodeBox.Size = new System.Drawing.Size(995, 792); this.CodeBox.TabIndex = 1; this.CodeBox.Text = ""; this.CodeBox.SelectionChanged += new System.EventHandler(this.CodeBox_SelectionChanged); this.CodeBox.TextChanged += new System.EventHandler(this.CodeBox_TextChanged); // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.flowLayoutPanel1.Controls.Add(this.LeftButton); this.flowLayoutPanel1.Controls.Add(this.DiffButton); this.flowLayoutPanel1.Controls.Add(this.RightButton); this.flowLayoutPanel1.Controls.Add(this.ApplyChangesButton); this.flowLayoutPanel1.Controls.Add(this.CopyContainerButton); this.flowLayoutPanel1.Controls.Add(this.btnSaveAll); this.flowLayoutPanel1.Controls.Add(this.btnViewCFGOnly); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(995, 32); this.flowLayoutPanel1.TabIndex = 0; // // LeftButton // this.LeftButton.AutoSize = true; this.LeftButton.Location = new System.Drawing.Point(3, 3); this.LeftButton.Name = "LeftButton"; this.LeftButton.Size = new System.Drawing.Size(56, 26); this.LeftButton.TabIndex = 0; this.LeftButton.Text = "Left"; this.LeftButton.UseVisualStyleBackColor = true; this.LeftButton.CheckedChanged += new System.EventHandler(this.LeftButton_CheckedChanged); // // DiffButton // this.DiffButton.AutoSize = true; this.DiffButton.Checked = true; this.DiffButton.Location = new System.Drawing.Point(65, 3); this.DiffButton.Name = "DiffButton"; this.DiffButton.Size = new System.Drawing.Size(54, 26); this.DiffButton.TabIndex = 1; this.DiffButton.TabStop = true; this.DiffButton.Text = "Diff"; this.DiffButton.UseVisualStyleBackColor = true; this.DiffButton.CheckedChanged += new System.EventHandler(this.LeftButton_CheckedChanged); // // RightButton // this.RightButton.AutoSize = true; this.RightButton.Location = new System.Drawing.Point(125, 3); this.RightButton.Name = "RightButton"; this.RightButton.Size = new System.Drawing.Size(63, 26); this.RightButton.TabIndex = 2; this.RightButton.Text = "Right"; this.RightButton.UseVisualStyleBackColor = true; this.RightButton.CheckedChanged += new System.EventHandler(this.LeftButton_CheckedChanged); // // ApplyChangesButton // this.ApplyChangesButton.Enabled = false; this.ApplyChangesButton.Location = new System.Drawing.Point(194, 3); this.ApplyChangesButton.Name = "ApplyChangesButton"; this.ApplyChangesButton.Size = new System.Drawing.Size(98, 23); this.ApplyChangesButton.TabIndex = 3; this.ApplyChangesButton.Text = "Apply Changes"; this.ApplyChangesButton.UseVisualStyleBackColor = true; this.ApplyChangesButton.Click += new System.EventHandler(this.ApplyChangesButton_Click); // // CopyContainerButton // this.CopyContainerButton.Location = new System.Drawing.Point(298, 3); this.CopyContainerButton.Name = "CopyContainerButton"; this.CopyContainerButton.Size = new System.Drawing.Size(98, 23); this.CopyContainerButton.TabIndex = 4; this.CopyContainerButton.Text = "Copy Container"; this.CopyContainerButton.UseVisualStyleBackColor = true; this.CopyContainerButton.Click += new System.EventHandler(this.CopyContainerButton_Click); // // btnSaveAll // this.btnSaveAll.Location = new System.Drawing.Point(402, 3); this.btnSaveAll.Name = "btnSaveAll"; this.btnSaveAll.Size = new System.Drawing.Size(107, 26); this.btnSaveAll.TabIndex = 5; this.btnSaveAll.Text = "SaveAllPasses"; this.btnSaveAll.UseVisualStyleBackColor = true; this.btnSaveAll.Click += new System.EventHandler(this.btnSaveAll_Click); // // btnViewCFGOnly // this.btnViewCFGOnly.Location = new System.Drawing.Point(515, 3); this.btnViewCFGOnly.Name = "btnViewCFGOnly"; this.btnViewCFGOnly.Size = new System.Drawing.Size(105, 26); this.btnViewCFGOnly.TabIndex = 6; this.btnViewCFGOnly.Text = "ViewCFGOnly"; this.btnViewCFGOnly.UseVisualStyleBackColor = true; this.btnViewCFGOnly.Click += new System.EventHandler(this.btnViewCFGOnly_Click); // // LogBox // this.LogBox.Dock = System.Windows.Forms.DockStyle.Fill; this.LogBox.Location = new System.Drawing.Point(0, 0); this.LogBox.Name = "LogBox"; this.LogBox.Size = new System.Drawing.Size(995, 73); this.LogBox.TabIndex = 0; this.LogBox.Text = ""; // // OptEditorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1497, 901); this.Controls.Add(this.TopContainer); this.Name = "OptEditorForm"; this.Text = "Optimizer Editor"; this.Load += new System.EventHandler(this.OptEditorForm_Load); this.TopContainer.Panel1.ResumeLayout(false); this.TopContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.TopContainer)).EndInit(); this.TopContainer.ResumeLayout(false); this.WorkContainer.Panel1.ResumeLayout(false); this.WorkContainer.Panel1.PerformLayout(); this.WorkContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.WorkContainer)).EndInit(); this.WorkContainer.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer TopContainer; private System.Windows.Forms.SplitContainer WorkContainer; private System.Windows.Forms.ListBox PassesListBox; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.RadioButton LeftButton; private System.Windows.Forms.RadioButton DiffButton; private System.Windows.Forms.RadioButton RightButton; private System.Windows.Forms.Button ApplyChangesButton; private System.Windows.Forms.RichTextBox CodeBox; private System.Windows.Forms.RichTextBox LogBox; private System.Windows.Forms.Button CopyContainerButton; private System.Windows.Forms.Button btnSaveAll; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.Button btnViewCFGOnly; } }
0
repos/DirectXShaderCompiler/tools/clang/tools
repos/DirectXShaderCompiler/tools/clang/tools/dotnetc/DxilBitcodeReader.cs
/////////////////////////////////////////////////////////////////////////////// // // // DxilBitcodeReader.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// using DotNetDxc; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MainNs { enum StandardWidths { BlockIDWidth = 8, // We use VBR-8 for block IDs. CodeLenWidth = 4, // Codelen are VBR-4. BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block. }; // The standard abbrev namespace always has a way to exit a block, enter a // nested block, define abbrevs, and define an unabbreviated record. enum FixedAbbrevIDs { END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode. ENTER_SUBBLOCK = 1, /// DEFINE_ABBREV - Defines an abbrev for the current block. It consists /// of a vbr5 for # operand infos. Each operand info is emitted with a /// single bit to indicate if it is a literal encoding. If so, the value is /// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed /// by the info value as a vbr5 if needed. DEFINE_ABBREV = 2, // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by // a vbr6 for the # operands, followed by vbr6's for each operand. UNABBREV_RECORD = 3, // This is not a code, this is a marker for the first abbrev assignment. FIRST_APPLICATION_ABBREV = 4 }; /// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO /// block, which contains metadata about other blocks in the file. enum StandardBlockIDs { /// BLOCKINFO_BLOCK is used to define metadata about blocks, for example, /// standard abbrevs that should be available to all blocks of a specified /// ID. BLOCKINFO_BLOCK_ID = 0, // Block IDs 1-7 are reserved for future expansion. FIRST_APPLICATION_BLOCKID = 8 }; /// BlockInfoCodes - The blockinfo block contains metadata about user-defined /// blocks. enum BlockInfoCodes { // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd // block, instead of the BlockInfo block. BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#] BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name] BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME: // [id, name] }; public static class ByteArrayExtensions { public static int size<T>(this List<T> list) { return list.Count(); } public static bool empty<T>(this IEnumerable<T> list) { return list.Count() == 0; } public static void push_back<T>(this List<T> list, T element) { list.Add(element); } public static void resize<T>(this List<T> list, int size) { if (list.Count > size) list.RemoveRange(size, list.Count - size); else while (list.Count < size) list.Add(default(T)); } public static void clear<T>(this List<T> list) { list.Clear(); } public static TreeNode RangeNodeASCII(this byte[] bytes, string text, ref int offset, int charLength, out string value) { System.Diagnostics.Debug.Assert(offset % 8 == 0, "else NYI"); int byteOffset = offset / 8; char[] valueChars = new char[charLength]; for (int i = 0; i < charLength; ++i) { valueChars[i] = (char)bytes[byteOffset + i]; } value = new string(valueChars); TreeNode result = TreeNodeRange.For(text + ": '" + value + "'", offset, charLength * 8); offset += charLength * 8; return result; } } public class BitCodeAbbrevOp { public enum EncKind { Fixed = 1, // A fixed width field, Val specifies number of bits. VBR = 2, // A VBR field where Val specifies the width of each chunk. Array = 3, // A sequence of fields, next field species elt encoding. Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._]. Blob = 5 // 32-bit aligned array of 8-bit characters. } public BitCodeAbbrevOp(UInt64 val) { this.Val = val; this.IsLiteral = true; } public BitCodeAbbrevOp(EncKind K) : this(K, 0) { } public BitCodeAbbrevOp(EncKind K, UInt64 val) { this.Val = val; this.IsLiteral = false; this.Enc = K; } public UInt64 Val; public bool IsLiteral; public EncKind Enc; public bool isEncoding() { return !IsLiteral; } public EncKind getEncoding() { return Enc; } public bool hasEncodingData() { return hasEncodingData(getEncoding()); } public static bool hasEncodingData(EncKind E) { switch (E) { case EncKind.Fixed: case EncKind.VBR: return true; case EncKind.Array: case EncKind.Char6: case EncKind.Blob: return false; } throw new Exception("Invalid encoding"); } /// isChar6 - Return true if this character is legal in the Char6 encoding. public static bool isChar6(char C) { if (C >= 'a' && C <= 'z') return true; if (C >= 'A' && C <= 'Z') return true; if (C >= '0' && C <= '9') return true; if (C == '.' || C == '_') return true; return false; } public static uint EncodeChar6(char C) { if (C >= 'a' && C <= 'z') return (uint)C - 'a'; if (C >= 'A' && C <= 'Z') return (uint)C - 'A' + 26; if (C >= '0' && C <= '9') return (uint)C - '0' + 26 + 26; if (C == '.') return 62; if (C == '_') return 63; throw new Exception("Not a value Char6 character!"); } public static char DecodeChar6(uint V) { //assert((V & ~63) == 0 && "Not a Char6 encoded character!"); if (V < 26) return (char)(V + 'a'); if (V < 26 + 26) return (char)(V - 26 + 'A'); if (V < 26 + 26 + 10) return (char)(V - 26 - 26 + '0'); if (V == 62) return '.'; if (V == 63) return '_'; throw new Exception("Not a value Char6 character!"); } } public class BitCodeAbbrev { public readonly List<BitCodeAbbrevOp> OperandList = new List<BitCodeAbbrevOp>(); public int getNumOperandInfos() { return OperandList.Count; } } public class BlockScope { public BlockScope(uint prevCodeSize) { this.PrevCodeSize = prevCodeSize; } public readonly uint PrevCodeSize; public readonly List<BitCodeAbbrev> PrevAbbrevs = new List<BitCodeAbbrev>(); } public class DxilBitstreamReader { private readonly byte[] bytes; private readonly int length; private readonly int startOffset; /// <summary> /// This contains information emitted to BLOCKINFO_BLOCK blocks. These /// describe abbreviations that all blocks of the specified ID inherit. /// </summary> public class BlockInfo { public uint BlockID; public List<BitCodeAbbrev> Abbrevs = new List<BitCodeAbbrev>(); public string Name; public List<KeyValuePair<uint, string>> RecordNames = new List<KeyValuePair<uint, string>>(); }; private List<BlockInfo> BlockInfoRecords = new List<BlockInfo>(); /// This is set to true if we don't care about the block/record name /// information in the BlockInfo block. Only llvm-bcanalyzer uses this. public bool IgnoreBlockInfoNames; // always set to false for bitstream visualization public DxilBitstreamReader(byte[] bytes, int startOffset, int length) { // startOffset is reported in bits, this.bytes = bytes; this.startOffset = startOffset; this.length = length; } /// <summary>Gets the byte offset in underlying buffer, for analysis.</summary> public uint GetStartOffset() { return (uint)this.startOffset; } public bool isValidAddress(uint offset) { return offset < length; } public uint readBytes(byte[] BArray, uint size, uint address) { uint BytesRead = size; uint BufferSize = (uint)this.length; if (address >= BufferSize) return 0; uint End = address + BytesRead; if (End > BufferSize) End = BufferSize; //assert(static_cast<int64_t>(End - Address) >= 0); BytesRead = End - address; Array.Copy(this.bytes, address + this.startOffset, BArray, 0, BytesRead); //memcpy(Buf, address + FirstChar, BytesRead); return BytesRead; } //===--------------------------------------------------------------------===// // Block Manipulation //===--------------------------------------------------------------------===// /// Return true if we've already read and processed the block info block for /// this Bitstream. We only process it for the first cursor that walks over /// it. public bool hasBlockInfoRecords() { return BlockInfoRecords.Count > 0; } /// If there is block info for the specified ID, return it, otherwise return /// null. public BlockInfo getBlockInfo(uint BlockID) { for (int i = 0; i < this.BlockInfoRecords.Count; i++) if (this.BlockInfoRecords[i].BlockID == BlockID) return this.BlockInfoRecords[i]; return null; } public BlockInfo getOrCreateBlockInfo(uint BlockID) { BlockInfo result = getBlockInfo(BlockID); if (result != null) return result; result = new BlockInfo(); result.BlockID = BlockID; this.BlockInfoRecords.Add(result); return result; } /// Takes block info from the other bitstream reader. /// /// This is a "take" operation because BlockInfo records are non-trivial, and /// indeed rather expensive. void takeBlockInfo(DxilBitstreamReader Other) { this.BlockInfoRecords = Other.BlockInfoRecords; } } public struct BitstreamEntry { public enum EntryKind { Error, // Malformed bitcode was found. EndBlock, // We've reached the end of the current block, (or the end of the // file, which is treated like a series of EndBlock records. SubBlock, // This is the start of a new subblock of a specific ID. Record // This is a record with a specific AbbrevID. } public EntryKind Kind; public uint ID; public static BitstreamEntry getError() { BitstreamEntry E = new BitstreamEntry() { Kind = EntryKind.Error }; return E; } public static BitstreamEntry getEndBlock() { BitstreamEntry E = new BitstreamEntry() { Kind = EntryKind.EndBlock }; return E; } public static BitstreamEntry getSubBlock(uint ID) { BitstreamEntry E = new BitstreamEntry() { Kind = EntryKind.SubBlock, ID = ID }; return E; } public static BitstreamEntry getRecord(uint AbbrevID) { BitstreamEntry E = new BitstreamEntry() { Kind = EntryKind.Record, ID = AbbrevID }; return E; } }; public class DxilBitstreamCursor { // word_t == 32-bits DxilBitcodeReader log; DxilBitstreamReader BitStream; uint NextChar; // The size of the bicode. 0 if we don't know it yet. uint Size; /// This is the current data we have pulled from the stream but have not /// returned to the client. This is specifically and intentionally defined to /// follow the word size of the host machine for efficiency. We use word_t in /// places that are aware of this to make it perfectly explicit what is going /// on. uint CurWord; /// This is the number of bits in CurWord that are valid. This is always from /// [0...bits_of(size_t)-1] inclusive. uint BitsInCurWord; // This is the declared size of code values used for the current block, in // bits. uint CurCodeSize; /// Abbrevs installed at in this block. List<BitCodeAbbrev> CurAbbrevs = new List<BitCodeAbbrev>(); public class Block { public uint PrevCodeSize; public List<BitCodeAbbrev> PrevAbbrevs = new List<BitCodeAbbrev>(); public Block(uint PCS) { this.PrevCodeSize = PCS; } } /// This tracks the codesize of parent blocks. List<Block> BlockScope = new List<Block>(); const uint MaxChunkSize = 4 * 8; public DxilBitstreamCursor(DxilBitstreamReader reader, DxilBitcodeReader log) { this.log = log; init(reader); } private void init(DxilBitstreamReader R) { freeState(); BitStream = R; NextChar = 0; Size = 0; BitsInCurWord = 0; CurCodeSize = 2; } /// <summary>Gets the bit offset in underlying byte buffer, for analysis.</summary> public uint GetOffset() { return this.BitStream.GetStartOffset() * 8 + (uint)GetCurrentBitNo(); //GetCurrentBitNo //return (32 - this.BitsInCurWord) + this.NextChar * 8 + this.BitStream.GetStartOffset() * 8; } void freeState() { CurAbbrevs.Clear(); BlockScope.Clear(); } bool canSkipToPos(uint pos) { // pos can be skipped to if it is a valid address or one byte past the end. return pos == 0 || BitStream.isValidAddress(pos - 1); } public bool AtEndOfStream() { if (BitsInCurWord != 0) return false; if (Size != 0) return Size == NextChar; fillCurWord(); return BitsInCurWord == 0; } /// Return the number of bits used to encode an abbrev #. uint getAbbrevIDWidth() { return CurCodeSize; } const uint CHAR_BIT = 8; /// Return the bit # of the bit we are reading. public UInt64 GetCurrentBitNo() { return NextChar * CHAR_BIT - BitsInCurWord; } DxilBitstreamReader getBitStreamReader() { return BitStream; } /// Flags that modify the behavior of advance(). [Flags] public enum advance_flags { None = 0, /// If this flag is used, the advance() method does not automatically pop /// the block scope when the end of a block is reached. AF_DontPopBlockAtEnd = 1, /// If this flag is used, abbrev entries are returned just like normal /// records. AF_DontAutoprocessAbbrevs = 2 }; public BitstreamEntry advance() { return advance(advance_flags.None); } public string AbbrevIDName(uint code) { string result = "#" + code; switch (code) { case END_BLOCK: result += "=END_BLOCK"; break; case ENTER_SUBBLOCK: result += "=ENTER_SUBBLOCK"; break; case DEFINE_ABBREV: result += "=DEFINE_ABBREV"; break; } return result; } /// Advance the current bitstream, returning the next entry in the stream. public BitstreamEntry advance(advance_flags Flags) { for (;;) { uint codeStart = this.GetOffset(); uint Code = ReadCode(); log.NR_SE_Leaf("BlockCode: " + AbbrevIDName(Code), codeStart, this.GetOffset()); if (Code == (uint)(FixedAbbrevIDs.END_BLOCK)) { // Pop the end of the block unless Flags tells us not to. if (advance_flags.AF_DontPopBlockAtEnd != (Flags & advance_flags.AF_DontPopBlockAtEnd) && ReadBlockEnd()) return BitstreamEntry.getError(); return BitstreamEntry.getEndBlock(); } if (Code == (uint)(FixedAbbrevIDs.ENTER_SUBBLOCK)) return BitstreamEntry.getSubBlock(ReadSubBlockID()); if (Code == (uint)(FixedAbbrevIDs.DEFINE_ABBREV) && (advance_flags.AF_DontAutoprocessAbbrevs != (Flags & advance_flags.AF_DontAutoprocessAbbrevs))) { // We read and accumulate abbrev's, the client can't do anything with // them anyway. ReadAbbrevRecord(); continue; } return BitstreamEntry.getRecord(Code); } } public BitstreamEntry advanceSkippingSubblocks() { return advanceSkippingSubblocks(advance_flags.None); } /// This is a convenience function for clients that don't expect any /// subblocks. This just skips over them automatically. public BitstreamEntry advanceSkippingSubblocks(advance_flags Flags) { for (;;) { // If we found a normal entry, return it. BitstreamEntry Entry = advance(Flags); if (Entry.Kind != BitstreamEntry.EntryKind.SubBlock) return Entry; // If we found a sub-block, just skip over it and check the next entry. if (SkipBlock()) return BitstreamEntry.getError(); } } const uint sizeof_word_t = 4; /// Reset the stream to the specified bit number. public void JumpToBit(UInt64 BitNo) { uint ByteNo = (uint)(BitNo / 8) & ~(sizeof_word_t - 1); uint WordBitNo = (uint)(BitNo & (sizeof_word_t * 8 - 1)); //assert(canSkipToPos(ByteNo) && "Invalid location"); // Move the cursor to the right word. NextChar = ByteNo; BitsInCurWord = 0; // Skip over any bits that are already consumed. if (WordBitNo != 0) Read(WordBitNo); } void fillCurWord() { if (Size != 0 && NextChar >= Size) throw new Exception("Unexpected end of file"); // Read the next word from the stream. byte[] BArray = new byte[sizeof_word_t]; uint BytesRead = BitStream.readBytes(BArray, sizeof_word_t, NextChar); // If we run out of data, stop at the end of the stream. if (BytesRead == 0) { Size = NextChar; return; } if (Size > 0) throw new NotImplementedException(); //CurWord = // support::endian::read<word_t, support::little, support::unaligned>( // Array); CurWord = (uint)(BArray[0] | (BArray[1] << 8) | (BArray[2] << 16) | (BArray[3] << 24)); NextChar += BytesRead; BitsInCurWord = BytesRead * 8; } public uint Read(uint NumBits) { const uint BitsInWord = MaxChunkSize; //assert(NumBits && NumBits <= BitsInWord && // "Cannot return zero or more than BitsInWord bits!"); const uint Mask = 0x1f; // If the field is fully contained by CurWord, return it quickly. if (BitsInCurWord >= NumBits) { int bitsToShift = (int)(BitsInWord - NumBits); uint RQuick = CurWord & (~(uint)0 >> bitsToShift); // Use a mask to avoid undefined behavior. CurWord >>= (int)(NumBits & Mask); BitsInCurWord -= NumBits; return RQuick; } uint R = (BitsInCurWord != 0) ? CurWord : 0; uint BitsLeft = NumBits - BitsInCurWord; fillCurWord(); // If we run out of data, stop at the end of the stream. if (BitsLeft > BitsInCurWord) return 0; uint R2 = CurWord & (~(uint)0 >> (int)(BitsInWord - BitsLeft)); // Use a mask to avoid undefined behavior. CurWord >>= (int)(BitsLeft & Mask); BitsInCurWord -= BitsLeft; R |= R2 << (int)(NumBits - BitsLeft); return R; } public uint Read(uint NumBits, string text) { uint start = this.GetOffset(); uint result = Read(NumBits); log.NR_SE_Leaf(text + ": " + result, start, this.GetOffset()); return result; } public uint ReadVBR(uint NumBits) { return ReadVBR(NumBits, null); } public uint ReadVBR(uint NumBits, string text) { uint start = this.GetOffset(); uint Piece = Read(NumBits); if ((Piece & (1U << (int)(NumBits - 1))) == 0) { log.NR_SE_Leaf(text + ": " + Piece, start, this.GetOffset()); return Piece; } uint Result = 0; uint NextBit = 0; for (;;) { Result |= (Piece & ((1U << (int)(NumBits - 1)) - 1)) << (int)NextBit; if ((Piece & (1U << (int)(NumBits - 1))) == 0) { log.NR_SE_Leaf(text + ": " + Result, start, this.GetOffset()); return Result; } NextBit += NumBits - 1; Piece = Read(NumBits); } } ulong ReadVBR64(uint NumBits) { return ReadVBR64(NumBits, null); } // Read a VBR that may have a value up to 64-bits in size. The chunk size of // the VBR must still be <= 32 bits though. ulong ReadVBR64(uint NumBits, string text) { uint startOff = this.GetOffset(); uint Piece = Read(NumBits); if ((Piece & (1U << (int)(NumBits - 1))) == 0) { log.NR_SE_Leaf(text + ": " + Piece, startOff, this.GetOffset()); return (ulong)(Piece); } ulong Result = 0; uint NextBit = 0; for (;;) { Result |= (ulong)(Piece & ((1U << (int)(NumBits - 1)) - 1)) << (int)NextBit; if ((Piece & (1U << (int)(NumBits - 1))) == 0) { log.NR_SE_Leaf(text + ": " + Result, startOff, this.GetOffset()); return Result; } NextBit += NumBits - 1; Piece = Read(NumBits); } } private void SkipToFourByteBoundary() { // If word_t is 64-bits and if we've read less than 32 bits, just dump // the bits we have up to the next 32-bit boundary. // We fix word_t to be 32-bits though, so this is a no-op. //if (sizeof(word_t) > 4 && // BitsInCurWord >= 32) //{ // CurWord >>= BitsInCurWord - 32; // BitsInCurWord = 32; // return; //} if (BitsInCurWord == 0) return; uint start = this.GetOffset(); BitsInCurWord = 0; log.NR_SE_Leaf("four-byte pad", start, this.GetOffset()); } public uint ReadCode() { return Read(CurCodeSize); } // Block header: // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen] /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block. public uint ReadSubBlockID() { return ReadVBR((uint)StandardWidths.BlockIDWidth, "SubBlockID"); } /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body /// of this block. If the block record is malformed, return true. public bool SkipBlock() { // Read and ignore the codelen value. Since we are skipping this block, we // don't care what code widths are used inside of it. ReadVBR((uint)StandardWidths.CodeLenWidth, "CodeSize"); SkipToFourByteBoundary(); uint NumFourBytes = Read((uint)StandardWidths.BlockSizeWidth, "BlockSize(4-bytes)"); // Check that the block wasn't partially defined, and that the offset isn't // bogus. uint SkipTo = (uint)(GetCurrentBitNo() + NumFourBytes * 4 * 8); if (AtEndOfStream() || !canSkipToPos(SkipTo / 8)) return true; JumpToBit(SkipTo); return false; } public bool EnterSubBlock(uint BlockID) { uint dontCare; return EnterSubBlock(BlockID, out dontCare); } /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true /// if the block has an error. public bool EnterSubBlock(uint BlockID, out uint NumWordsP) { // Save the current block's state on BlockScope. BlockScope.Add(new Block(CurCodeSize)); BlockScope.Last().PrevAbbrevs.AddRange(CurAbbrevs); // Add the abbrevs specific to this block to the CurAbbrevs list. DxilBitstreamReader.BlockInfo Info = BitStream.getBlockInfo(BlockID); if (Info != null) { CurAbbrevs.AddRange(Info.Abbrevs); } // Get the codesize of this block. CurCodeSize = ReadVBR((int)StandardWidths.CodeLenWidth, "CodeSize"); // We can't read more than MaxChunkSize at a time NumWordsP = 0; if (CurCodeSize > MaxChunkSize) return true; SkipToFourByteBoundary(); NumWordsP = Read((int)StandardWidths.BlockSizeWidth, "NumWords"); // Validate that this block is sane. return CurCodeSize == 0 || AtEndOfStream(); } public bool ReadBlockEnd() { if (BlockScope.Count == 0) return true; // Block tail: // [END_BLOCK, <align4bytes>] SkipToFourByteBoundary(); popBlockScope(); return false; } void popBlockScope() { var last = BlockScope[BlockScope.Count - 1]; CurCodeSize = last.PrevCodeSize; CurAbbrevs = last.PrevAbbrevs; BlockScope.RemoveAt(BlockScope.Count - 1); } //===--------------------------------------------------------------------===// // Record Processing //===--------------------------------------------------------------------===// /// Return the abbreviation for the specified AbbrevId. public BitCodeAbbrev getAbbrev(uint AbbrevID) { uint AbbrevNo = AbbrevID - (uint)FixedAbbrevIDs.FIRST_APPLICATION_ABBREV; if (AbbrevNo >= CurAbbrevs.Count) throw new Exception("Invalid abbrev number"); return CurAbbrevs[(int)AbbrevNo]; } /// Read the current record and discard it. public void skipRecord(uint AbbrevID) { throw new NotImplementedException(); } public uint readRecord(uint AbbrevID, List<ulong> Vals) { string dontCare; return readRecord(AbbrevID, Vals, out dontCare); } private const uint END_BLOCK = (uint)FixedAbbrevIDs.END_BLOCK; private const uint ENTER_SUBBLOCK = (uint)FixedAbbrevIDs.ENTER_SUBBLOCK; private const uint DEFINE_ABBREV = (uint)FixedAbbrevIDs.DEFINE_ABBREV; private const uint UNABBREV_RECORD = (uint)FixedAbbrevIDs.UNABBREV_RECORD; /// BlockInfoCodes - The blockinfo block contains metadata about user-defined /// blocks. // enum BlockInfoCodes // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd // block, instead of the BlockInfo block. const uint BLOCKINFO_CODE_SETBID = 1; // SETBID: [blockid#] const uint BLOCKINFO_CODE_BLOCKNAME = 2; // BLOCKNAME: [name] const uint BLOCKINFO_CODE_SETRECORDNAME = 3; // BLOCKINFO_CODE_SETRECORDNAME: [id, name] const uint BLOCKINFO_BLOCK_ID = (uint)StandardBlockIDs.BLOCKINFO_BLOCK_ID; ulong readAbbreviatedField(BitCodeAbbrevOp Op) { Debug.Assert(!Op.IsLiteral); switch (Op.Enc) { case BitCodeAbbrevOp.EncKind.Array: throw new Exception(); case BitCodeAbbrevOp.EncKind.Blob: throw new Exception(); case BitCodeAbbrevOp.EncKind.Fixed: return Read((uint)Op.Val); case BitCodeAbbrevOp.EncKind.VBR: return ReadVBR64((uint)Op.Val); case BitCodeAbbrevOp.EncKind.Char6: return BitCodeAbbrevOp.DecodeChar6(Read(6)); default: throw new Exception(); } } public uint readRecord(uint AbbrevID, List<ulong> Vals, out string Blob) { Blob = null; if (AbbrevID == UNABBREV_RECORD) { log.NR_Push("UNABBREV_RECORD"); uint UnabbrevCode = ReadVBR(6, "Code"); uint NumElts = ReadVBR(6, "NumElts"); for (uint i = 0; i != NumElts; ++i) Vals.Add(ReadVBR64(6, "Val #" + i)); log.NR_Pop(); return UnabbrevCode; } BitCodeAbbrev Abbv = getAbbrev(AbbrevID); // Read the record code first. //assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?"); BitCodeAbbrevOp CodeOp = Abbv.OperandList[0]; uint Code; if (CodeOp.IsLiteral) Code = (uint)CodeOp.Val; else { if (CodeOp.Enc == BitCodeAbbrevOp.EncKind.Array || CodeOp.Enc == BitCodeAbbrevOp.EncKind.Blob) throw new Exception("Abbreviation starts with an Array or a Blob"); Code = (uint)readAbbreviatedField(CodeOp); } for (int i = 1, e = Abbv.getNumOperandInfos(); i != e; ++i) { BitCodeAbbrevOp Op = Abbv.OperandList[i]; if (Op.IsLiteral) { Vals.Add(Op.Val); continue; } if (Op.getEncoding() != BitCodeAbbrevOp.EncKind.Array && Op.getEncoding() != BitCodeAbbrevOp.EncKind.Blob) { Vals.Add(readAbbreviatedField(Op)); continue; } if (Op.getEncoding() == BitCodeAbbrevOp.EncKind.Array) { // Array case. Read the number of elements as a vbr6. uint ArrNumElts = ReadVBR(6); // Get the element encoding. if (i + 2 != e) throw new Exception("Array op not second to last"); BitCodeAbbrevOp EltEnc = Abbv.OperandList[++i]; if (!EltEnc.isEncoding()) throw new Exception( "Array element type has to be an encoding of a type"); if (EltEnc.getEncoding() == BitCodeAbbrevOp.EncKind.Array || EltEnc.getEncoding() == BitCodeAbbrevOp.EncKind.Blob) throw new Exception("Array element type can't be an Array or a Blob"); // Read all the elements. for (; ArrNumElts != 0; --ArrNumElts) Vals.Add(readAbbreviatedField(EltEnc)); continue; } //assert(Op.getEncoding() == BitCodeAbbrevOp::Blob); // Blob case. Read the number of bytes as a vbr6. uint NumElts = ReadVBR(6); SkipToFourByteBoundary(); // 32-bit alignment // Figure out where the end of this blob will be including tail padding. uint CurBitPos = (uint)GetCurrentBitNo(); uint NewEnd = CurBitPos + ((NumElts + 3) & (~(uint)3)) * 8; // If this would read off the end of the bitcode file, just set the // record to empty and return. if (!canSkipToPos(NewEnd / 8)) { for (uint ec = 0; ec < NumElts; ++ec) Vals.Add(0); //NextChar = BitStream->getBitcodeBytes().getExtent(); //break; throw new NotImplementedException(); } // Otherwise, inform the streamer that we need these bytes in memory. //const char* Ptr = (const char*) BitStream->getBitcodeBytes().getPointer(CurBitPos / 8, NumElts); // If we can return a reference to the data, do so to avoid copying it. Blob = null; //if (Blob) { // *Blob = StringRef(Ptr, NumElts); } //else { // Otherwise, unpack into Vals with zero extension. //for (; 0 != NumElts; --NumElts) //Vals.Add((uint char) * Ptr++); throw new NotImplementedException(); } // Skip over tail padding. //JumpToBit(NewEnd); } return Code; } //===--------------------------------------------------------------------===// // Abbrev Processing //===--------------------------------------------------------------------===// public void ReadAbbrevRecord() { log.NR_Push("AbbrevRecord"); BitCodeAbbrev Abbv = new BitCodeAbbrev(); uint NumOpInfo = ReadVBR(5, "NumOps"); for (uint i = 0; i != NumOpInfo; ++i) { bool IsLiteral = Read(1) != 0; if (IsLiteral) { Abbv.OperandList.Add(new BitCodeAbbrevOp(ReadVBR64(8, "Literal"))); continue; } BitCodeAbbrevOp.EncKind E = (BitCodeAbbrevOp.EncKind)Read(3, "EncodingKind"); log.NR_Note(E.ToString()); if (BitCodeAbbrevOp.hasEncodingData(E)) { ulong Data = ReadVBR64(5, "Data"); // As a special case, handle fixed(0) (i.e., a fixed field with zero bits) // and vbr(0) as a literal zero. This is decoded the same way, and avoids // a slow path in Read() to have to handle reading zero bits. if ((E == BitCodeAbbrevOp.EncKind.Fixed || E == BitCodeAbbrevOp.EncKind.VBR) && Data == 0) { Abbv.OperandList.Add(new BitCodeAbbrevOp((ulong)0)); continue; } if ((E == BitCodeAbbrevOp.EncKind.Fixed || E == BitCodeAbbrevOp.EncKind.VBR) && Data > MaxChunkSize) throw new Exception( "Fixed or VBR abbrev record with size > MaxChunkData"); Abbv.OperandList.Add(new BitCodeAbbrevOp(E, Data)); } else Abbv.OperandList.Add(new BitCodeAbbrevOp(E)); } if (Abbv.OperandList.Count == 0) throw new Exception("Abbrev record with no operands"); CurAbbrevs.Add(Abbv); log.NR_Pop(); } public bool ReadBlockInfoBlock() { // If this is the second stream to get to the block info block, skip it. if (BitStream.hasBlockInfoRecords()) return SkipBlock(); if (EnterSubBlock(BLOCKINFO_BLOCK_ID)) return true; List<ulong> Record = new List<ulong>(); DxilBitstreamReader.BlockInfo CurBlockInfo = null; // Read all the records for this module. for (;;) { BitstreamEntry Entry = advanceSkippingSubblocks(advance_flags.AF_DontAutoprocessAbbrevs); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: return true; case BitstreamEntry.EntryKind.EndBlock: return false; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read abbrev records, associate them with CurBID. if (Entry.ID == DEFINE_ABBREV) { if (CurBlockInfo == null) return true; ReadAbbrevRecord(); // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the // appropriate BlockInfo. int lastIdx = CurAbbrevs.Count - 1; CurBlockInfo.Abbrevs.Add(CurAbbrevs[lastIdx]); CurAbbrevs.RemoveAt(lastIdx); continue; } // Read a record. Record.Clear(); switch (readRecord(Entry.ID, Record)) { default: break; // Default behavior, ignore unknown content. case BLOCKINFO_CODE_SETBID: if (Record.Count < 1) return true; CurBlockInfo = BitStream.getOrCreateBlockInfo((uint)Record[0]); break; case BLOCKINFO_CODE_BLOCKNAME: { if (CurBlockInfo == null) return true; string Name = ""; for (int i = 0, e = Record.Count; i != e; ++i) Name += (char)Record[i]; CurBlockInfo.Name = Name; break; } case BLOCKINFO_CODE_SETRECORDNAME: { if (CurBlockInfo == null) return true; string Name = ""; for (int i = 1, e = Record.Count; i != e; ++i) Name += (char)Record[i]; CurBlockInfo.RecordNames.Add(new KeyValuePair<uint,string>((uint)Record[0], Name)); break; } } } } } public class DxilBitcodeReader { private byte[] bytes; private int offset; private TreeNode rootNode; private DxilBitstreamReader StreamFile; private DxilBitstreamCursor Stream; private ulong NextUnreadBit = 0; private bool SeenValueSymbolTable; private bool SeenFirstFunctionBody; private List<DxilFunction> FunctionsWithBodies = new List<DxilFunction>(); private bool UseRelativeIDs; private Stack<TreeNode> nodes = new Stack<TreeNode>(); public DxilBitcodeReader(byte[] bytes, int offset, int length, TreeNode root) { this.bytes = bytes; this.offset = offset; this.rootNode = root; this.nodes.Push(root); // Length and offset are in bits, but we initialize the bitstream // object in bytes. Debug.Assert(offset % 8 == 0); Debug.Assert(length % 8 == 0); this.StreamFile = new DxilBitstreamReader(bytes, offset / 8, length / 8); this.Stream = new DxilBitstreamCursor(this.StreamFile, this); } public static void BuildTree(byte[] bytes, ref int offset, int length, TreeNode root) { DxilBitcodeReader reader = new DxilBitcodeReader(bytes, offset, length, root); reader.parseBitcodeInto(); offset = reader.offset; } public TreeNode NR_SE_Leaf(string text, uint start, uint end) { var tn = NR_SE(text, start, end); this.nodes.Peek().Nodes.Add(tn); return tn; } public TreeNode NR_Push(string text) { var tn = new TreeNode(text); this.nodes.Peek().Nodes.Add(tn); this.nodes.Push(tn); return tn; } public void NR_Note(string text) { this.nodes.Peek().Text += " - " + text; } public void NR_Pop() { this.nodes.Pop(); } /// <summary>TreeNode with range for start/end.</summary> private TreeNode NR_SE(string text, uint start, uint end) { return TreeNodeRange.For(text, (int)start, (int)(end - start)); } private void parseBitcodeInto() { // Sniff for the signature. uint sigStart = Stream.GetOffset(); if (Stream.Read(8) != 'B' || Stream.Read(8) != 'C' || Stream.Read(4) != 0x0 || Stream.Read(4) != 0xC || Stream.Read(4) != 0xE || Stream.Read(4) != 0xD) throw new Exception("Invalid bitcode signature"); uint sigEnd = Stream.GetOffset(); NR_SE_Leaf("Signature - BC 0xC0DE", sigStart, sigEnd); // We expect a number of well-defined blocks, though we don't necessarily // need to understand them all. for (;;) { if (Stream.AtEndOfStream()) { // We didn't really read a proper Module. throw new Exception("Malformed IR file"); } BitstreamEntry Entry = Stream.advance(DxilBitstreamCursor.advance_flags.AF_DontAutoprocessAbbrevs); if (Entry.Kind != BitstreamEntry.EntryKind.SubBlock) throw new Exception("Malformed block"); if (Entry.ID == MODULE_BLOCK_ID) { NR_Push("Module Block"); parseModule(false); NR_Pop(); return; } if (Stream.SkipBlock()) throw new Exception("Invalid record"); } } const uint BLOCKINFO_BLOCK_ID = (uint)StandardBlockIDs.BLOCKINFO_BLOCK_ID; // enum BlockIDs const uint MODULE_BLOCK_ID = 8; const uint PARAMATTR_BLOCK_ID = 9; const uint PARAMATTR_GROUP_BLOCK_ID = 10; const uint CONSTANTS_BLOCK_ID = 11; const uint FUNCTION_BLOCK_ID = 12; const uint UNUSED_ID1 = 13; const uint VALUE_SYMTAB_BLOCK_ID = 14; const uint METADATA_BLOCK_ID = 15; const uint METADATA_ATTACHMENT_ID = 16; const uint TYPE_BLOCK_ID_NEW = 17; const uint USELIST_BLOCK_ID = 18; // enum ModuleCodes const uint MODULE_CODE_VERSION = 1; // VERSION: [version#] const uint MODULE_CODE_TRIPLE = 2; // TRIPLE: [strchr x N] const uint MODULE_CODE_DATALAYOUT = 3; // DATALAYOUT: [strchr x N] const uint MODULE_CODE_ASM = 4; // ASM: [strchr x N] const uint MODULE_CODE_SECTIONNAME = 5; // SECTIONNAME: [strchr x N] // FIXME: Remove DEPLIB in 4.0. const uint MODULE_CODE_DEPLIB = 6; // DEPLIB: [strchr x N] // GLOBALVAR: [pointer type, isconst, initid, // linkage, alignment, section, visibility, threadlocal] const uint MODULE_CODE_GLOBALVAR = 7; // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, // section, visibility, gc, unnamed_addr] const uint MODULE_CODE_FUNCTION = 8; // ALIAS: [alias type, aliasee val#, linkage, visibility] const uint MODULE_CODE_ALIAS = 9; // MODULE_CODE_PURGEVALS: [numvals] const uint MODULE_CODE_PURGEVALS = 10; const uint MODULE_CODE_GCNAME = 11; // GCNAME: [strchr x N] const uint MODULE_CODE_COMDAT = 12; // COMDAT: [selection_kind, name] /// PARAMATTR blocks have code for defining a parameter attribute set. // enum AttributeCodes // FIXME: Remove `PARAMATTR_CODE_ENTRY_OLD' in 4.0 const uint PARAMATTR_CODE_ENTRY_OLD = 1; // ENTRY: [paramidx0, attr0, paramidx1, attr1...] const uint PARAMATTR_CODE_ENTRY = 2; // ENTRY: [paramidx0, attrgrp0, paramidx1, attrgrp1, ...] const uint PARAMATTR_GRP_CODE_ENTRY = 3; // ENTRY: [id, attr0, att1, ...] const bool ShouldLazyLoadMetadata = false; private void globalCleanup() { //throw new NotImplementedException(); } private static bool convertToString(List<ulong> Record, int Idx, out string Result) { if (Idx > Record.Count) { Result = null; return true; } StringBuilder sb = new StringBuilder(Record.Count - Idx); for (int i = Idx; i < Record.Count; ++i) sb.Append((char)Record[i]); Result = sb.ToString(); return false; } private Exception error(string text) { return new Exception(text); } private void parseModule(bool Resume) { if (Resume) Stream.JumpToBit(NextUnreadBit); else if (Stream.EnterSubBlock(MODULE_BLOCK_ID)) throw new Exception("Invalid record"); List<ulong> Record = new List<ulong>(); List<string> SectionTable = new List<string>(); List<string> GCTable = new List<string>(); // Read all the records for this module. for (;;) { BitstreamEntry Entry = Stream.advance(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.Error: throw new Exception("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: globalCleanup(); return; case BitstreamEntry.EntryKind.SubBlock: switch (Entry.ID) { default: // Skip unknown content. if (Stream.SkipBlock()) throw error("Invalid record"); break; case BLOCKINFO_BLOCK_ID: NR_Push("Block Info"); if (Stream.ReadBlockInfoBlock()) throw error("Malformed block"); NR_Pop(); break; case PARAMATTR_BLOCK_ID: NR_Push("Attribute"); parseAttributeBlock(); NR_Pop(); break; case PARAMATTR_GROUP_BLOCK_ID: NR_Push("AttributeGroup"); parseAttributeGroupBlock(); NR_Pop(); break; case TYPE_BLOCK_ID_NEW: NR_Push("TypeTable"); parseTypeTable(); NR_Pop(); break; case VALUE_SYMTAB_BLOCK_ID: parseValueSymbolTable(); SeenValueSymbolTable = true; break; case CONSTANTS_BLOCK_ID: parseConstants(); resolveGlobalAndAliasInits(); break; case METADATA_BLOCK_ID: parseMetadata(); break; case FUNCTION_BLOCK_ID: // If this is the first function body we've seen, reverse the // FunctionsWithBodies list. if (!SeenFirstFunctionBody) { FunctionsWithBodies.Reverse(); globalCleanup(); SeenFirstFunctionBody = true; } rememberAndSkipFunctionBody(); // Suspend parsing when we reach the function bodies. Subsequent // materialization calls will resume it when necessary. If the bitcode // file is old, the symbol table will be at the end instead and will not // have been seen yet. In this case, just finish the parse now. if (SeenValueSymbolTable) { NextUnreadBit = Stream.GetCurrentBitNo(); return; } break; case USELIST_BLOCK_ID: parseUseLists(); break; } continue; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. switch (Stream.readRecord(Entry.ID, Record)) { default: break; // Default behavior, ignore unknown content. case MODULE_CODE_VERSION: // VERSION: [version#] if (Record.Count < 1) throw error("Invalid record"); // Only version #0 and #1 are supported so far. uint module_version = (uint)Record[0]; switch (module_version) { default: throw error("Invalid value"); case 0: UseRelativeIDs = false; break; case 1: UseRelativeIDs = true; break; } if (!UseRelativeIDs) { NR_Note("no relative ID support - old IR version"); } break; case MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); //TheModule->setTargetTriple(S); break; } case MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); //TheModule->setDataLayout(S); break; } case MODULE_CODE_ASM: { // ASM: [strchr x N] string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); //TheModule->setModuleInlineAsm(S); break; } case MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] // FIXME: Remove in 4.0. string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); // Ignore value. break; } case MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); SectionTable.Add(S); break; } case MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] string S; if (convertToString(Record, 0, out S)) throw error("Invalid record"); GCTable.Add(S); break; } case MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] if (Record.Count < 2) throw error("Invalid record"); throw new NotImplementedException(); #if FALSE Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); uint ComdatNameSize = Record[1]; std::string ComdatName; ComdatName.reserve(ComdatNameSize); for (uint i = 0; i != ComdatNameSize; ++i) ComdatName += (char)Record[2 + i]; Comdat* C = TheModule->getOrInsertComdat(ComdatName); C->setSelectionKind(SK); ComdatList.push_back(C); break; #endif } // GLOBALVAR: [pointer type, isconst, initid, // linkage, alignment, section, visibility, threadlocal, // unnamed_addr, externally_initialized, dllstorageclass, // comdat] case MODULE_CODE_GLOBALVAR: { if (Record.Count < 6) throw error("Invalid record"); throw new NotImplementedException(); #if FALSE Type* Ty = getTypeByID(Record[0]); if (!Ty) throw error("Invalid record"); bool isConstant = Record[1] & 1; bool explicitType = Record[1] & 2; uint AddressSpace; if (explicitType) { AddressSpace = Record[1] >> 2; } else { if (!Ty->isPointerTy()) throw error("Invalid type for value"); AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); Ty = cast<PointerType>(Ty)->getElementType(); } ulong RawLinkage = Record[3]; GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); uint Alignment; parseAlignmentValue(Record[4], Alignment); std::string Section; if (Record[5]) { if (Record[5] - 1 >= SectionTable.Count) throw error("Invalid ID"); Section = SectionTable[Record[5] - 1]; } GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; // Local linkage must have default visibility. if (Record.Count > 6 && !GlobalValue::isLocalLinkage(Linkage)) // FIXME: Change to an error if non-default in 4.0. Visibility = getDecodedVisibility(Record[6]); GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; if (Record.Count > 7) TLM = getDecodedThreadLocalMode(Record[7]); bool UnnamedAddr = false; if (Record.Count > 8) UnnamedAddr = Record[8]; bool ExternallyInitialized = false; if (Record.Count > 9) ExternallyInitialized = Record[9]; GlobalVariable* NewGV = new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, TLM, AddressSpace, ExternallyInitialized); NewGV->setAlignment(Alignment); if (!Section.empty()) NewGV->setSection(Section); NewGV->setVisibility(Visibility); NewGV->setUnnamedAddr(UnnamedAddr); if (Record.Count > 10) NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); else upgradeDLLImportExportLinkage(NewGV, RawLinkage); ValueList.push_back(NewGV); // Remember which value to use for the global initializer. if (uint InitID = Record[2]) GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); if (Record.Count > 11) { if (uint ComdatID = Record[11]) { if (ComdatID > ComdatList.Count) throw error("Invalid global variable comdat ID"); NewGV->setComdat(ComdatList[ComdatID - 1]); } } else if (hasImplicitComdat(RawLinkage)) { NewGV->setComdat(reinterpret_cast<Comdat*>(1)); } break; #endif } // FUNCTION: [type, callingconv, isproto, linkage, paramattr, // alignment, section, visibility, gc, unnamed_addr, // prologuedata, dllstorageclass, comdat, prefixdata] case MODULE_CODE_FUNCTION: { if (Record.Count < 8) throw error("Invalid record"); DxilType Ty = getTypeByID(Record[0]); if (Ty == null) throw error("Invalid record"); DxilPointerType PTy = Ty as DxilPointerType; if (PTy != null) Ty = PTy.getElementType(); DxilFunctionType FTy = Ty as DxilFunctionType; if (FTy == null) throw error("Invalid type for value"); //DxilFunction Func = Function::Create(FTy, GlobalValue::ExternalLinkage, "", TheModule); DxilFunction Func = new DxilFunction(FTy); #if FALSE Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); bool isProto = Record[2]; ulong RawLinkage = Record[3]; Func->setLinkage(getDecodedLinkage(RawLinkage)); Func->setAttributes(getAttributes(Record[4])); uint Alignment; parseAlignmentValue(Record[5], Alignment); Func->setAlignment(Alignment); if (Record[6]) { if (Record[6] - 1 >= SectionTable.Count) throw error("Invalid ID"); Func->setSection(SectionTable[Record[6] - 1]); } // Local linkage must have default visibility. if (!Func->hasLocalLinkage()) // FIXME: Change to an error if non-default in 4.0. Func->setVisibility(getDecodedVisibility(Record[7])); if (Record.Count > 8 && Record[8]) { if (Record[8] - 1 >= GCTable.Count) throw error("Invalid ID"); Func->setGC(GCTable[Record[8] - 1].c_str()); } bool UnnamedAddr = false; if (Record.Count > 9) UnnamedAddr = Record[9]; Func->setUnnamedAddr(UnnamedAddr); if (Record.Count > 10 && Record[10] != 0) FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1)); if (Record.Count > 11) Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); else upgradeDLLImportExportLinkage(Func, RawLinkage); if (Record.Count > 12) { if (uint ComdatID = Record[12]) { if (ComdatID > ComdatList.Count) throw error("Invalid function comdat ID"); Func->setComdat(ComdatList[ComdatID - 1]); } } else if (hasImplicitComdat(RawLinkage)) { Func->setComdat(reinterpret_cast<Comdat*>(1)); } if (Record.Count > 13 && Record[13] != 0) FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1)); if (Record.Count > 14 && Record[14] != 0) FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); ValueList.push_back(Func); // If this is a function with a body, remember the prototype we are // creating now, so that we can match up the body with them later. if (!isProto) { Func->setIsMaterializable(true); FunctionsWithBodies.push_back(Func); DeferredFunctionInfo[Func] = 0; } #endif break; } // ALIAS: [alias type, aliasee val#, linkage] // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] case MODULE_CODE_ALIAS: { if (Record.Count < 3) throw error("Invalid record"); throw new NotImplementedException(); #if FALSE Type* Ty = getTypeByID(Record[0]); if (!Ty) throw error("Invalid record"); auto* PTy = dyn_cast<PointerType>(Ty); if (!PTy) throw error("Invalid type for value"); auto* NewGA = GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule); // Old bitcode files didn't have visibility field. // Local linkage must have default visibility. if (Record.Count > 3 && !NewGA->hasLocalLinkage()) // FIXME: Change to an error if non-default in 4.0. NewGA->setVisibility(getDecodedVisibility(Record[3])); if (Record.Count > 4) NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4])); else upgradeDLLImportExportLinkage(NewGA, Record[2]); if (Record.Count > 5) NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5])); if (Record.Count > 6) NewGA->setUnnamedAddr(Record[6]); ValueList.push_back(NewGA); AliasInits.push_back(std::make_pair(NewGA, Record[1])); break; #endif } /// MODULE_CODE_PURGEVALS: [numvals] case MODULE_CODE_PURGEVALS: throw new NotImplementedException(); #if FALSE // Trim down the value list to the specified size. if (Record.Count < 1 || Record[0] > ValueList.Count) throw error("Invalid record"); ValueList.shrinkTo(Record[0]); #endif } Record.Clear(); } } class AttributeSet { }; class AttrBuilder { }; private List<AttributeSet> MAttributes = new List<AttributeSet>(); private Dictionary<uint, AttributeSet> MAttributeGroups = new Dictionary<uint, AttributeSet>(); private void parseAttributeBlock() { if (Stream.EnterSubBlock(PARAMATTR_BLOCK_ID)) throw error("Invalid record"); if (!MAttributes.empty()) throw error("Invalid multiple blocks"); List<ulong> Record = new List<ulong>(); List<AttributeSet> Attrs = new List<AttributeSet>(); // Read all the records. for (;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.Clear(); switch (Stream.readRecord(Entry.ID, Record)) { default: // Default behavior: ignore. break; case PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] // FIXME: Remove in 4.0. if ((Record.size() & 1) != 0) throw error("Invalid record"); for (int i = 0, e = Record.size(); i != e; i += 2) { //AttrBuilder B; //decodeLLVMAttributesForBitcode(B, Record[i + 1]); //Attrs.push_back(AttributeSet::get(Context, Record[i], B)); } //MAttributes.push_back(AttributeSet::get(Context, Attrs)); Attrs.clear(); break; } case PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] for (int i = 0, e = Record.size(); i != e; ++i) //Attrs.push_back(MAttributeGroups[Record[i]]); //MAttributes.push_back(AttributeSet::get(Context, Attrs)); Attrs.clear(); break; } } } } private void parseAttributeGroupBlock() { if (Stream.EnterSubBlock(PARAMATTR_GROUP_BLOCK_ID)) throw error("Invalid record"); if (!MAttributeGroups.empty()) throw error("Invalid multiple blocks"); List<ulong> Record = new List<ulong>(); // Read all the records. for (;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.Clear(); switch (Stream.readRecord(Entry.ID, Record)) { default: // Default behavior: ignore. break; case PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] if (Record.size() < 3) throw error("Invalid record"); ulong GrpID = Record[0]; ulong Idx = Record[1]; // Index of the object this attribute refers to. //AttrBuilder B; for (int i = 2, e = Record.size(); i != e; ++i) { if (Record[i] == 0) { // Enum attribute ++i; // AttrKind Kind; // parseAttrKind(Record[++i], &Kind); //B.addAttribute(Kind); } else if (Record[i] == 1) { // Integer attribute ++i; //Attribute::AttrKind Kind; // parseAttrKind(Record[++i], &Kind); //if (Kind == Attribute::Alignment) // B.addAlignmentAttr(Record[++i]); //else if (Kind == Attribute::StackAlignment) // B.addStackAlignmentAttr(Record[++i]); //else if (Kind == Attribute::Dereferenceable) // B.addDereferenceableAttr(Record[++i]); //else if (Kind == Attribute::DereferenceableOrNull) // B.addDereferenceableOrNullAttr(Record[++i]); } else { // String attribute Debug.Assert((Record[i] == 3 || Record[i] == 4), "Invalid attribute group entry"); bool HasValue = (Record[i++] == 4); string KindStr = ""; string ValStr = ""; while (Record[i] != 0 && i != e) KindStr += Record[i++]; Debug.Assert(Record[i] == 0, "Kind string not null terminated"); if (HasValue) { // Has a value associated with it. ++i; // Skip the '0' that terminates the "kind" string. while (Record[i] != 0 && i != e) ValStr += Record[i++]; Debug.Assert(Record[i] == 0, "Value string not null terminated"); } //B.addAttribute(KindStr.str(), ValStr.str()); } } //MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); break; } } } } private void parseTypeTable() { if (Stream.EnterSubBlock(TYPE_BLOCK_ID_NEW)) throw error("Invalid record"); parseTypeTableBody(); } class DxilType { public DxilType(string name) { this.Name = name; } public string Name; public static DxilType getInt8Ty() { return Int8Ty; } public static DxilType getInt32Ty() { return Int32Ty; } public static DxilType Int32Ty = new DxilType("i32"); public static DxilType Int8Ty = new DxilType("i8"); } class DxilPointerType : DxilType { private uint addressSpace; private DxilType elementType; public DxilPointerType(uint addressSpace, DxilType elementType) : base(elementType == null ? "?" : elementType.Name + "*") { this.addressSpace = addressSpace; this.elementType = elementType; } public DxilType getElementType() { return elementType; } } class DxilFunctionType : DxilType { public DxilFunctionType(DxilType ResultTy, DxilType[] ArgTys, bool varArgs) : base("Fn") { this.ResultTy = ResultTy; this.ArgTys = ArgTys; this.VarArgs = varArgs; } public DxilType ResultTy; public DxilType[] ArgTys; public bool VarArgs; } class DxilFunction { public DxilFunction(DxilFunctionType Ty) { this.ty = Ty; } private DxilFunctionType ty; } List<DxilType> TypeList = new List<DxilType>(); List<object> ValueList = new List<object>(); /// TYPE blocks have codes for each type primitive they use. // enum TypeCodes const uint TYPE_CODE_NUMENTRY = 1; // NUMENTRY: [numentries] // Type Codes const uint TYPE_CODE_VOID = 2; // VOID const uint TYPE_CODE_FLOAT = 3; // FLOAT const uint TYPE_CODE_DOUBLE = 4; // DOUBLE const uint TYPE_CODE_LABEL = 5; // LABEL const uint TYPE_CODE_OPAQUE = 6; // OPAQUE const uint TYPE_CODE_INTEGER = 7; // INTEGER: [width] const uint TYPE_CODE_POINTER = 8; // POINTER: [pointee type] const uint TYPE_CODE_FUNCTION_OLD = 9; // FUNCTION: [vararg, attrid, retty, // paramty x N] const uint TYPE_CODE_HALF = 10; // HALF const uint TYPE_CODE_ARRAY = 11; // ARRAY: [numelts, eltty] const uint TYPE_CODE_VECTOR = 12; // VECTOR: [numelts, eltty] // These are not with the other floating point types because they're // a late addition, and putting them in the right place breaks // binary compatibility. const uint TYPE_CODE_X86_FP80 = 13; // X86 LONG DOUBLE const uint TYPE_CODE_FP128 = 14; // LONG DOUBLE (112 bit mantissa) const uint TYPE_CODE_PPC_FP128 = 15; // PPC LONG DOUBLE (2 doubles) const uint TYPE_CODE_METADATA = 16; // METADATA const uint TYPE_CODE_X86_MMX = 17; // X86 MMX const uint TYPE_CODE_STRUCT_ANON = 18; // STRUCT_ANON: [ispacked, eltty x N] const uint TYPE_CODE_STRUCT_NAME = 19; // STRUCT_NAME: [strchr x N] const uint TYPE_CODE_STRUCT_NAMED = 20;// STRUCT_NAMED: [ispacked, eltty x N] const uint TYPE_CODE_FUNCTION = 21; // FUNCTION: [vararg, retty, paramty x N] private DxilType getTypeByID(ulong id) { // Consider: if entry is null, should create placeholder struct return TypeList[(int)id]; } private void parseTypeTableBody() { if (!TypeList.empty()) throw error("Invalid multiple blocks"); List<ulong> Record = new List<ulong>(); int NumRecords = 0; string TypeName = ""; // Read all the records for this type table. for (;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: if (NumRecords != TypeList.size()) throw error("Malformed block"); return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.clear(); DxilType ResultTy = null; switch (Stream.readRecord(Entry.ID, Record)) { default: throw error("Invalid value"); case TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] // TYPE_CODE_NUMENTRY contains a count of the number of types in the // type list. This allows us to reserve space. if (Record.size() < 1) throw error("Invalid record"); TypeList.resize((int)Record[0]); continue; case TYPE_CODE_VOID: // VOID ResultTy = new DxilType("void"); break; case TYPE_CODE_HALF: // HALF ResultTy = new DxilType("HalfTy"); break; case TYPE_CODE_FLOAT: // FLOAT ResultTy = new DxilType("Float"); break; case TYPE_CODE_DOUBLE: // DOUBLE ResultTy = new DxilType("Double"); break; case TYPE_CODE_X86_FP80: // X86_FP80 ResultTy = new DxilType("X86_FP80"); break; case TYPE_CODE_FP128: // FP128 ResultTy = new DxilType("FP128"); break; case TYPE_CODE_PPC_FP128: // PPC_FP128 ResultTy = new DxilType("PPC_FP128"); break; case TYPE_CODE_LABEL: // LABEL ResultTy = new DxilType("Label"); break; case TYPE_CODE_METADATA: // METADATA ResultTy = new DxilType("Metadata"); break; case TYPE_CODE_X86_MMX: // X86_MMX ResultTy = new DxilType("X86_MMX"); break; case TYPE_CODE_INTEGER: { // INTEGER: [width] if (Record.size() < 1) throw error("Invalid record"); ulong NumBits = Record[0]; //if (NumBits < IntegerType::MIN_INT_BITS || // NumBits > IntegerType::MAX_INT_BITS) // throw error("Bitwidth for integer type out of range"); ResultTy = new DxilType("int:" + NumBits); break; } case TYPE_CODE_POINTER: { // POINTER: [pointee type] or // [pointee type, address space] if (Record.size() < 1) throw error("Invalid record"); uint AddressSpace = 0; if (Record.size() == 2) AddressSpace = (uint)Record[1]; ResultTy = getTypeByID(Record[0]); //if (!ResultTy || !PointerType::isValidElementType(ResultTy)) // throw error("Invalid type"); ResultTy = new DxilPointerType(AddressSpace, ResultTy); break; } case TYPE_CODE_FUNCTION_OLD: { // FIXME: attrid is dead, remove it in LLVM 4.0 // FUNCTION: [vararg, attrid, retty, paramty x N] if (Record.size() < 3) throw error("Invalid record"); throw new NotImplementedException(); #if FALSE List<DxilType> ArgTys = new List<DxilType>(); for (int i = 3, e = Record.size(); i != e; ++i) { if (DxilType T = getTypeByID(Record[i])) ArgTys.push_back(T); else break; } ResultTy = getTypeByID(Record[2]); if (!ResultTy || ArgTys.size() < Record.size() - 3) throw error("Invalid type"); ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); break; #endif } case TYPE_CODE_FUNCTION: { // FUNCTION: [vararg, retty, paramty x N] if (Record.size() < 2) throw error("Invalid record"); List<DxilType> ArgTys = new List<DxilType>(); for (int i = 2, e = Record.size(); i != e; ++i) { //if (DxilType T = getTypeByID(Record[i])) DxilType T = getTypeByID(Record[i]); if (T != null) { //if (!FunctionType::isValidArgumentType(T)) // throw error("Invalid function argument type"); ArgTys.push_back(T); } else break; } ResultTy = getTypeByID(Record[1]); if (ResultTy == null || ArgTys.size() < Record.size() - 2) throw error("Invalid type"); ResultTy = new DxilFunctionType(ResultTy, ArgTys.ToArray(), Record[0] != 0); break; } case TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] if (Record.size() < 1) throw error("Invalid record"); List<DxilType> EltTys = new List<DxilType>(); for (int i = 1, e = Record.size(); i != e; ++i) { DxilType T = getTypeByID(Record[i]); if (T != null) EltTys.push_back(T); else break; } if (EltTys.size() != Record.size() - 1) throw error("Invalid type"); ResultTy = new DxilType("StructType::get(Context, EltTys, Record[0]);"); break; } case TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] if (convertToString(Record, 0, out TypeName)) throw error("Invalid record"); continue; case TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] if (Record.size() < 1) throw error("Invalid record"); if (NumRecords >= TypeList.size()) throw error("Invalid TYPE table"); // Check to see if this was forward referenced, if so fill in the temp. //StructType* Res = cast_or_null<StructType>(TypeList[NumRecords]); //if (Res) //{ // Res->setName(TypeName); // TypeList[NumRecords] = nullptr; //} //else // Otherwise, create a new struct. // Res = createIdentifiedStructType(Context, TypeName); //TypeName = ""; //SmallVector < Type *, 8 > EltTys; //for (unsigned i = 1, e = Record.size(); i != e; ++i) //{ // if (Type * T = getTypeByID(Record[i])) // EltTys.push_back(T); // else // break; //} //if (EltTys.size() != Record.size() - 1) // throw error("Invalid record"); //Res->setBody(EltTys, Record[0]); //ResultTy = Res; break; } case TYPE_CODE_OPAQUE: { // OPAQUE: [] if (Record.size() != 1) throw error("Invalid record"); if (NumRecords >= TypeList.size()) throw error("Invalid TYPE table"); // Check to see if this was forward referenced, if so fill in the temp. //StructType* Res = cast_or_null<StructType>(TypeList[NumRecords]); //if (Res) //{ // Res->setName(TypeName); // TypeList[NumRecords] = nullptr; //} //else // Otherwise, create a new struct with no body. // Res = createIdentifiedStructType(Context, TypeName); //TypeName = ""; //ResultTy = Res; break; } case TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] if (Record.size() < 2) throw error("Invalid record"); ResultTy = getTypeByID(Record[1]); if (ResultTy == null) //|| !ArrayType::isValidElementType(ResultTy)) throw error("Invalid type"); ResultTy = new DxilType("ArrayType::get(ResultTy, Record[0]);"); break; case TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] if (Record.size() < 2) throw error("Invalid record"); if (Record[0] == 0) throw error("Invalid vector length"); ResultTy = getTypeByID(Record[1]); if (ResultTy == null) //|| !StructType::isValidElementType(ResultTy)) throw error("Invalid type"); ResultTy = new DxilType("VectorType::get(ResultTy, Record[0]);"); break; } if (NumRecords >= TypeList.size()) throw error("Invalid TYPE table"); if (TypeList[NumRecords] != null) throw error("Invalid TYPE table: Only named structs can be forward referenced"); //Debug.Assert(ResultTy != null, "Didn't read a type?"); TypeList[NumRecords++] = ResultTy; } } private void parseValueSymbolTable() { if (Stream.EnterSubBlock(VALUE_SYMTAB_BLOCK_ID)) throw error("Invalid record"); List<ulong> Record = new List<ulong>(); //Triple TT(TheModule->getTargetTriple()); // Read all the records for this value table. //SmallString < 128 > ValueName; for(;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.clear(); #if FALSE switch (Stream.readRecord(Entry.ID, Record)) { default: // Default behavior: unknown type. break; case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] if (convertToString(Record, 1, ValueName)) return error("Invalid record"); unsigned ValueID = Record[0]; if (ValueID >= ValueList.size() || !ValueList[ValueID]) return error("Invalid record"); Value* V = ValueList[ValueID]; V->setName(StringRef(ValueName.data(), ValueName.size())); if (auto * GO = dyn_cast<GlobalObject>(V)) { if (GO->getComdat() == reinterpret_cast<Comdat*>(1)) { if (TT.isOSBinFormatMachO()) GO->setComdat(nullptr); else GO->setComdat(TheModule->getOrInsertComdat(V->getName())); } } ValueName.clear(); break; } case bitc::VST_CODE_BBENTRY: { if (convertToString(Record, 1, ValueName)) return error("Invalid record"); BasicBlock* BB = getBasicBlock(Record[0]); if (!BB) return error("Invalid record"); BB->setName(StringRef(ValueName.data(), ValueName.size())); ValueName.clear(); break; } } #else Stream.readRecord(Entry.ID, Record); #endif } } private void parseConstants() { if (Stream.EnterSubBlock(CONSTANTS_BLOCK_ID)) throw error("Invalid record"); List<ulong> Record = new List<ulong>(); // Read all the records for this value table. DxilType CurTy = DxilType.getInt32Ty(); //uint NextCstNo = ValueList.size(); for(;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: //if (NextCstNo != ValueList.size()) // throw error("Invalid ronstant reference"); // Once all the constants have been read, go through and resolve forward // references. //ValueList.resolveConstantForwardRefs(); return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.clear(); #if FALSE Value* V = nullptr; unsigned BitCode = Stream.readRecord(Entry.ID, Record); switch (BitCode) { default: // Default behavior: unknown constant case bitc::CST_CODE_UNDEF: // UNDEF V = UndefValue::get(CurTy); break; case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] if (Record.empty()) return error("Invalid record"); if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) return error("Invalid record"); CurTy = TypeList[Record[0]]; continue; // Skip the ValueList manipulation. case bitc::CST_CODE_NULL: // NULL V = Constant::getNullValue(CurTy); break; case bitc::CST_CODE_INTEGER: // INTEGER: [intval] if (!CurTy->isIntegerTy() || Record.empty()) return error("Invalid record"); V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); break; case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] if (!CurTy->isIntegerTy() || Record.empty()) return error("Invalid record"); APInt VInt = readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); V = ConstantInt::get(Context, VInt); break; } case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] if (Record.empty()) return error("Invalid record"); if (CurTy->isHalfTy()) V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, APInt(16, (uint16_t)Record[0]))); else if (CurTy->isFloatTy()) V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, APInt(32, (uint32_t)Record[0]))); else if (CurTy->isDoubleTy()) V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, APInt(64, Record[0]))); else if (CurTy->isX86_FP80Ty()) { // Bits are not stored the same way as a normal i80 APInt, compensate. uint64_t Rearrange[2]; Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); Rearrange[1] = Record[0] >> 48; V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, APInt(80, Rearrange))); } else if (CurTy->isFP128Ty()) V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, APInt(128, Record))); else if (CurTy->isPPC_FP128Ty()) V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, APInt(128, Record))); else V = UndefValue::get(CurTy); break; } case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] if (Record.empty()) return error("Invalid record"); unsigned Size = Record.size(); SmallVector < Constant *, 16 > Elts; if (StructType * STy = dyn_cast<StructType>(CurTy)) { for (unsigned i = 0; i != Size; ++i) Elts.push_back(ValueList.getConstantFwdRef(Record[i], STy->getElementType(i))); V = ConstantStruct::get(STy, Elts); } else if (ArrayType * ATy = dyn_cast<ArrayType>(CurTy)) { Type* EltTy = ATy->getElementType(); for (unsigned i = 0; i != Size; ++i) Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); V = ConstantArray::get(ATy, Elts); } else if (VectorType * VTy = dyn_cast<VectorType>(CurTy)) { Type* EltTy = VTy->getElementType(); for (unsigned i = 0; i != Size; ++i) Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); V = ConstantVector::get(Elts); } else { V = UndefValue::get(CurTy); } break; } case bitc::CST_CODE_STRING: // STRING: [values] case bitc::CST_CODE_CSTRING: { // CSTRING: [values] if (Record.empty()) return error("Invalid record"); SmallString < 16 > Elts(Record.begin(), Record.end()); V = ConstantDataArray::getString(Context, Elts, BitCode == bitc::CST_CODE_CSTRING); break; } case bitc::CST_CODE_DATA: {// DATA: [n x value] if (Record.empty()) return error("Invalid record"); Type* EltTy = cast<SequentialType>(CurTy)->getElementType(); unsigned Size = Record.size(); if (EltTy->isIntegerTy(8)) { SmallVector < uint8_t, 16 > Elts(Record.begin(), Record.end()); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else if (EltTy->isIntegerTy(16)) { SmallVector < uint16_t, 16 > Elts(Record.begin(), Record.end()); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else if (EltTy->isIntegerTy(32)) { SmallVector < uint32_t, 16 > Elts(Record.begin(), Record.end()); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else if (EltTy->isIntegerTy(64)) { SmallVector < uint64_t, 16 > Elts(Record.begin(), Record.end()); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else if (EltTy->isFloatTy()) { SmallVector < float, 16 > Elts(Size); std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else if (EltTy->isDoubleTy()) { SmallVector < double, 16 > Elts(Size); std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToDouble); if (isa<VectorType>(CurTy)) V = ConstantDataVector::get(Context, Elts); else V = ConstantDataArray::get(Context, Elts); } else { return error("Invalid type for value"); } break; } case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] if (Record.size() < 3) return error("Invalid record"); int Opc = getDecodedBinaryOpcode(Record[0], CurTy); if (Opc < 0) { V = UndefValue::get(CurTy); // Unknown binop. } else { Constant* LHS = ValueList.getConstantFwdRef(Record[1], CurTy); Constant* RHS = ValueList.getConstantFwdRef(Record[2], CurTy); unsigned Flags = 0; if (Record.size() >= 4) { if (Opc == Instruction::Add || Opc == Instruction::Sub || Opc == Instruction::Mul || Opc == Instruction::Shl) { if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) Flags |= OverflowingBinaryOperator::NoSignedWrap; if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || Opc == Instruction::LShr || Opc == Instruction::AShr) { if (Record[3] & (1 << bitc::PEO_EXACT)) Flags |= SDivOperator::IsExact; } } V = ConstantExpr::get(Opc, LHS, RHS, Flags); } break; } case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] if (Record.size() < 3) return error("Invalid record"); int Opc = getDecodedCastOpcode(Record[0]); if (Opc < 0) { V = UndefValue::get(CurTy); // Unknown cast. } else { Type* OpTy = getTypeByID(Record[1]); if (!OpTy) return error("Invalid record"); Constant* Op = ValueList.getConstantFwdRef(Record[2], OpTy); V = UpgradeBitCastExpr(Opc, Op, CurTy); if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); } break; } case bitc::CST_CODE_CE_INBOUNDS_GEP: case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] unsigned OpNum = 0; Type* PointeeType = nullptr; if (Record.size() % 2) PointeeType = getTypeByID(Record[OpNum++]); SmallVector < Constant *, 16 > Elts; while (OpNum != Record.size()) { Type* ElTy = getTypeByID(Record[OpNum++]); if (!ElTy) return error("Invalid record"); Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); } if (PointeeType && PointeeType != cast<SequentialType>(Elts[0]->getType()->getScalarType()) ->getElementType()) return error("Explicit gep operator type does not match pointee type " "of pointer operand"); ArrayRef<Constant*> Indices(Elts.begin() + 1, Elts.end()); V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP); break; } case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] if (Record.size() < 3) return error("Invalid record"); Type* SelectorTy = Type::getInt1Ty(Context); // If CurTy is a vector of length n, then Record[0] must be a <n x i1> // vector. Otherwise, it must be a single bit. if (VectorType * VTy = dyn_cast<VectorType>(CurTy)) SelectorTy = VectorType::get(Type::getInt1Ty(Context), VTy->getNumElements()); V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], SelectorTy), ValueList.getConstantFwdRef(Record[1], CurTy), ValueList.getConstantFwdRef(Record[2], CurTy)); break; } case bitc::CST_CODE_CE_EXTRACTELT : { // CE_EXTRACTELT: [opty, opval, opty, opval] if (Record.size() < 3) return error("Invalid record"); VectorType* OpTy = dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); if (!OpTy) return error("Invalid record"); Constant* Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); Constant* Op1 = nullptr; if (Record.size() == 4) { Type* IdxTy = getTypeByID(Record[2]); if (!IdxTy) return error("Invalid record"); Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); } else // TODO: Remove with llvm 4.0 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); if (!Op1) return error("Invalid record"); V = ConstantExpr::getExtractElement(Op0, Op1); break; } case bitc::CST_CODE_CE_INSERTELT : { // CE_INSERTELT: [opval, opval, opty, opval] VectorType* OpTy = dyn_cast<VectorType>(CurTy); if (Record.size() < 3 || !OpTy) return error("Invalid record"); Constant* Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); Constant* Op1 = ValueList.getConstantFwdRef(Record[1], OpTy->getElementType()); Constant* Op2 = nullptr; if (Record.size() == 4) { Type* IdxTy = getTypeByID(Record[2]); if (!IdxTy) return error("Invalid record"); Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); } else // TODO: Remove with llvm 4.0 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); if (!Op2) return error("Invalid record"); V = ConstantExpr::getInsertElement(Op0, Op1, Op2); break; } case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] VectorType* OpTy = dyn_cast<VectorType>(CurTy); if (Record.size() < 3 || !OpTy) return error("Invalid record"); Constant* Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); Constant* Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); Type* ShufTy = VectorType::get(Type::getInt32Ty(Context), OpTy->getNumElements()); Constant* Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); break; } case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] VectorType* RTy = dyn_cast<VectorType>(CurTy); VectorType* OpTy = dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); if (Record.size() < 4 || !RTy || !OpTy) return error("Invalid record"); Constant* Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); Constant* Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); Type* ShufTy = VectorType::get(Type::getInt32Ty(Context), RTy->getNumElements()); Constant* Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); break; } case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] if (Record.size() < 4) return error("Invalid record"); Type* OpTy = getTypeByID(Record[0]); if (!OpTy) return error("Invalid record"); Constant* Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); Constant* Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); if (OpTy->isFPOrFPVectorTy()) V = ConstantExpr::getFCmp(Record[3], Op0, Op1); else V = ConstantExpr::getICmp(Record[3], Op0, Op1); break; } // This maintains backward compatibility, pre-asm dialect keywords. // FIXME: Remove with the 4.0 release. case bitc::CST_CODE_INLINEASM_OLD: { if (Record.size() < 2) return error("Invalid record"); std::string AsmStr, ConstrStr; bool HasSideEffects = Record[0] & 1; bool IsAlignStack = Record[0] >> 1; unsigned AsmStrSize = Record[1]; if (2 + AsmStrSize >= Record.size()) return error("Invalid record"); unsigned ConstStrSize = Record[2 + AsmStrSize]; if (3 + AsmStrSize + ConstStrSize > Record.size()) return error("Invalid record"); for (unsigned i = 0; i != AsmStrSize; ++i) AsmStr += (char)Record[2 + i]; for (unsigned i = 0; i != ConstStrSize; ++i) ConstrStr += (char)Record[3 + AsmStrSize + i]; PointerType* PTy = cast<PointerType>(CurTy); V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), AsmStr, ConstrStr, HasSideEffects, IsAlignStack); break; } // This version adds support for the asm dialect keywords (e.g., // inteldialect). case bitc::CST_CODE_INLINEASM: { if (Record.size() < 2) return error("Invalid record"); std::string AsmStr, ConstrStr; bool HasSideEffects = Record[0] & 1; bool IsAlignStack = (Record[0] >> 1) & 1; unsigned AsmDialect = Record[0] >> 2; unsigned AsmStrSize = Record[1]; if (2 + AsmStrSize >= Record.size()) return error("Invalid record"); unsigned ConstStrSize = Record[2 + AsmStrSize]; if (3 + AsmStrSize + ConstStrSize > Record.size()) return error("Invalid record"); for (unsigned i = 0; i != AsmStrSize; ++i) AsmStr += (char)Record[2 + i]; for (unsigned i = 0; i != ConstStrSize; ++i) ConstrStr += (char)Record[3 + AsmStrSize + i]; PointerType* PTy = cast<PointerType>(CurTy); V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), AsmStr, ConstrStr, HasSideEffects, IsAlignStack, InlineAsm::AsmDialect(AsmDialect)); break; } case bitc::CST_CODE_BLOCKADDRESS: { if (Record.size() < 3) return error("Invalid record"); Type* FnTy = getTypeByID(Record[0]); if (!FnTy) return error("Invalid record"); Function* Fn = dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1], FnTy)); if (!Fn) return error("Invalid record"); // Don't let Fn get dematerialized. BlockAddressesTaken.insert(Fn); // If the function is already parsed we can insert the block address right // away. BasicBlock* BB; unsigned BBID = Record[2]; if (!BBID) // Invalid reference to entry block. return error("Invalid ID"); if (!Fn->empty()) { Function::iterator BBI = Fn->begin(), BBE = Fn->end(); for (size_t I = 0, E = BBID; I != E; ++I) { if (BBI == BBE) return error("Invalid ID"); ++BBI; } BB = BBI; } else { // Otherwise insert a placeholder and remember it so it can be inserted // when the function is parsed. auto & FwdBBs = BasicBlockFwdRefs[Fn]; if (FwdBBs.empty()) BasicBlockFwdRefQueue.push_back(Fn); if (FwdBBs.size() < BBID + 1) FwdBBs.resize(BBID + 1); if (!FwdBBs[BBID]) FwdBBs[BBID] = BasicBlock::Create(Context); BB = FwdBBs[BBID]; } V = BlockAddress::get(Fn, BB); break; } } ValueList.assignValue(V, NextCstNo); ++NextCstNo; } #else Stream.readRecord(Entry.ID, Record); } #endif } private void resolveGlobalAndAliasInits() { //throw new NotImplementedException(); } private void parseMetadata() { if (Stream.EnterSubBlock(METADATA_BLOCK_ID)) throw error("Invalid record"); List<ulong> Record = new List<ulong>(); for (;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.Clear(); switch (Stream.readRecord(Entry.ID, Record)) { default: break; } } } private void rememberAndSkipFunctionBody() { //throw new NotImplementedException(); } private void parseUseLists() { if (Stream.EnterSubBlock(USELIST_BLOCK_ID)) throw error("Invalid record"); List<ulong> Record = new List<ulong>(); for (;;) { BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case BitstreamEntry.EntryKind.SubBlock: // Handled for us already. case BitstreamEntry.EntryKind.Error: throw error("Malformed block"); case BitstreamEntry.EntryKind.EndBlock: return; case BitstreamEntry.EntryKind.Record: // The interesting case. break; } // Read a record. Record.Clear(); switch (Stream.readRecord(Entry.ID, Record)) { default: break; } } } } }