diff --git a/dev/cppgm-scaffold.cpp b/dev/cppgm-scaffold.cpp index 60627c11cc..a2c6abe0f2 100644 --- a/dev/cppgm-scaffold.cpp +++ b/dev/cppgm-scaffold.cpp @@ -233,7 +233,8 @@ bool consume_search_option(const vector& args, size_t& i) { return true; } - if (consume_joined_or_separate_option(args, i, "-isystem", "path")) + if (consume_joined_or_separate_option(args, i, "-isystem", "path") || + consume_joined_or_separate_option(args, i, "-iquote", "path")) { return true; } diff --git a/dev/cppgm.cpp b/dev/cppgm.cpp index a07ee04e3d..4658e5e425 100644 --- a/dev/cppgm.cpp +++ b/dev/cppgm.cpp @@ -218,6 +218,7 @@ struct SourceOutputInvocation bool exceptions = true; bool rtti = true; vector include_paths; + vector quote_include_paths; vector system_include_paths; string command_line; bool wasm_atomics = true; @@ -404,6 +405,11 @@ SourceOutputInvocation parse_source_output_invocation(const vector& args invocation.include_paths.push_back(i == option ? args[i].substr(2) : args[i]); continue; } + if (consume_joined_or_separate_option(args, i, "-iquote", "path")) + { + invocation.quote_include_paths.push_back(i == option ? args[i].substr(7) : args[i]); + continue; + } if (consume_joined_or_separate_option(args, i, "-isystem", "path")) { invocation.system_include_paths.push_back(i == option ? args[i].substr(8) : args[i]); @@ -536,7 +542,8 @@ bool consume_search_option(const vector& args, size_t& i) { return true; } - if (consume_joined_or_separate_option(args, i, "-isystem", "path")) + if (consume_joined_or_separate_option(args, i, "-isystem", "path") || + consume_joined_or_separate_option(args, i, "-iquote", "path")) { return true; } @@ -756,6 +763,7 @@ PreprocessorOptions source_preprocessor_options(const SourceOutputInvocation& in { PreprocessorOptions options = source_preprocessor_options(); options.include_paths = invocation.include_paths; + options.quote_include_paths = invocation.quote_include_paths; options.system_include_paths = invocation.system_include_paths; options.command_line = invocation.command_line; driver::configure_source_language(invocation.language, invocation.standard, options); @@ -780,6 +788,8 @@ PreprocessorOptions source_preprocessor_options(const SourceOutputInvocation& in } else if (!invocation.sysroot.empty() || !invocation.resource_directory.empty()) throw InvocationError("target header directories currently require a Wasm target"); + if (!options.quote_include_paths.empty()) + driver::prune_include_paths(options); return options; } diff --git a/dev/frontend_source_sets.mk b/dev/frontend_source_sets.mk index d7f04eb817..2475c09ea6 100644 --- a/dev/frontend_source_sets.mk +++ b/dev/frontend_source_sets.mk @@ -71,7 +71,7 @@ FRONTEND_PHASE_BASENAMES_object := native/object/object_file native/object/elf_o FRONTEND_PHASE_BASENAMES_link := native/link/routine_builder native/link/runtime_support native/link/runtime_library native/link/linker # lowir2native links an executable needing link mode's runtime library. FRONTEND_OBJ_BASENAMES_lowir2native += $(FRONTEND_PHASE_BASENAMES_object) $(FRONTEND_PHASE_BASENAMES_link) -FRONTEND_OBJ_BASENAMES_cppgm += $(FRONTEND_PHASE_BASENAMES_native) $(FRONTEND_PHASE_BASENAMES_object) $(FRONTEND_PHASE_BASENAMES_link) driver/host_environment driver/wasm_environment driver/toolchain +FRONTEND_OBJ_BASENAMES_cppgm += $(FRONTEND_PHASE_BASENAMES_native) $(FRONTEND_PHASE_BASENAMES_object) $(FRONTEND_PHASE_BASENAMES_link) driver/host_environment driver/wasm_environment driver/native_assembly driver/toolchain # PA33: the optimizer, and the LowIR reader for LowIR object inputs. FRONTEND_OBJ_BASENAMES_cppgm += lowir/text_lexer lowir/text_parser lowir/text_parser_debug lowir/text_parser_debug_scopes lowir/text_parser_body lowir/text_parser_assembly lowir/text_reader $(FRONTEND_PHASE_BASENAMES_opt) FRONTEND_OBJ_BASENAMES_cppgm += asm/registers diff --git a/dev/src/asm/gnu_template.cpp b/dev/src/asm/gnu_template.cpp index e60d1b076d..cd3abee8f5 100644 --- a/dev/src/asm/gnu_template.cpp +++ b/dev/src/asm/gnu_template.cpp @@ -72,9 +72,31 @@ uint32_t reference(const std::string& source, std::size_t& pos, const std::vecto void pieces(PacketBuilder& packet, const std::string& source, const std::vector& operands, bool basic) { std::string literal; + bool alternatives = false; + bool selected = true; for (std::size_t pos = 0; pos < source.size();) { const char c = source[pos++]; + // Source GNU packets use AT&T, the first dialect alternative. + if (!basic && c == '{') + { + if (alternatives) + fail("nested assembly dialect alternatives"); + alternatives = true; + continue; + } + if (alternatives && (c == '|' || c == '}')) + { + alternatives = c != '}'; + selected = !alternatives; + continue; + } + if (!selected) + { + if (c == '%' && pos < source.size()) + ++pos; + continue; + } if (c != '%' || basic) { literal += c; @@ -131,6 +153,7 @@ void pieces(PacketBuilder& packet, const std::string& source, const std::vector< piece.bits = 512; break; case 'P': + case 'X': // Raw spelling without a PIC suffix. case 'c': piece.format = Format::Bare; break; @@ -157,6 +180,8 @@ void pieces(PacketBuilder& packet, const std::string& source, const std::vector< } packet.pieces.push_back(piece); } + if (alternatives) + fail("unterminated assembly dialect alternatives"); text(packet, literal); } diff --git a/dev/src/driver/host_environment.cpp b/dev/src/driver/host_environment.cpp index 4e467387f6..5f46c21326 100644 --- a/dev/src/driver/host_environment.cpp +++ b/dev/src/driver/host_environment.cpp @@ -15,6 +15,65 @@ namespace driver { +// GCC's include chain (cpplib's remove_duplicates): a directory named +// twice is searched at its first position only, and an -I directory that +// is also a system directory (-isystem or a standard one) is searched as +// that system directory ("the -I option is ignored"), so under +// -I/usr/include still finds libstdc++'s wrapper first. Directories are +// compared by device and inode. +void prune_include_paths(PreprocessorOptions& options) +{ + std::vector> seen; + const auto identity = [](const std::string& path, std::pair& id) { + struct stat status; + if (stat(path.c_str(), &status) != 0 || !S_ISDIR(status.st_mode)) + return false; + id = std::make_pair(status.st_dev, status.st_ino); + return true; + }; + const auto first = [&](const std::string& path) { + std::pair id; + if (!identity(path, id)) + return true; + for (const std::pair& other : seen) + { + if (other == id) + return false; + } + seen.push_back(id); + return true; + }; + std::vector system; + for (const std::string& path : options.system_include_paths) + { + if (first(path)) + system.push_back(path); + } + std::vector user; + for (const std::string& path : options.include_paths) + { + if (first(path)) + user.push_back(path); + } + if (!options.quote_include_paths.empty()) + { + seen.clear(); + std::vector quote; + for (const std::string& path : options.quote_include_paths) + if (first(path)) + quote.push_back(path); + // CPP joins the two chains, coalescing only a repeated boundary. + const std::vector& angle = user.empty() ? system : user; + std::pair before, after; + if (!quote.empty() && !angle.empty() && identity(quote.back(), before) && identity(angle.front(), after) && + before == after) + quote.pop_back(); + options.quote_include_paths.swap(quote); + } + options.system_include_paths.swap(system); + options.include_paths.swap(user); +} + void configure_target_environment(PreprocessorOptions& options, native::Target target) { options.target = target; diff --git a/dev/src/driver/host_environment.h b/dev/src/driver/host_environment.h index cf49b8e0cf..0e8d920fa7 100644 --- a/dev/src/driver/host_environment.h +++ b/dev/src/driver/host_environment.h @@ -33,6 +33,9 @@ bool add_host_environment( // Foreign SDK paths must be explicit; baked host paths are not a foreign SDK. void configure_target_environment(PreprocessorOptions& options, native::Target target); +// Canonicalize the GNU include search chains by filesystem identity. +void prune_include_paths(PreprocessorOptions& options); + // Builtin templates have language semantics independent of va_list or layout. const char* builtin_template_declarations(); diff --git a/dev/src/driver/native_assembly.cpp b/dev/src/driver/native_assembly.cpp new file mode 100644 index 0000000000..e5769f0d51 --- /dev/null +++ b/dev/src/driver/native_assembly.cpp @@ -0,0 +1,89 @@ +#include "driver/native_assembly.h" + +#include + +#include "asm/module_expand.h" +#include "native/asm/module.h" +#include "native/backend_error.h" +#include "preprocess/preprocessor.h" + +namespace driver { +namespace { + +std::string assembly_source(Preprocessor& preprocessor) +{ + std::string source; + bool comment = false; + for (;;) + { + const PPToken& token = preprocessor.next(); + if (token.kind == PPTokenKind::EndOfFile) + return source; + if ((token.flags & kStartOfLine) != 0) + { + source.push_back('\n'); + comment = false; + } + if (token.punctuator == kHashPunctuator) + comment = true; + if (comment || token.kind == PPTokenKind::WhitespaceSequence || token.kind == PPTokenKind::NewLine) + continue; + if ((token.flags & kLeadingSpace) != 0) + source.push_back(' '); + source.append(token.spelling, token.length); + } +} + +} // namespace + +bool compile_native_assembly( + const std::string& path, const PreprocessorOptions& base, native::Target target, native::object::ObjectFile& object) +{ + PreprocessorOptions options = base; + options.assembler = true; + options.language = SourceLanguage::C; + options.cplusplus.clear(); + options.builtin_declarations.clear(); + try + { + Preprocessor preprocessor(options, path); + try + { + assembly::ModuleExpander expander; + const auto lines = expander.expand(assembly::module_lines(assembly_source(preprocessor), {})); + object.path = path; + native::ModuleAssembler assembler(object, target); + assembler.begin(asm_model::Dialect::Att); + for (const auto& line : lines) + assembler.declare(line); + for (const auto& line : lines) + assembler.append(line); + assembler.finish(); + return true; + } + catch (const PreprocessError& failure) + { + std::cerr << "ERROR: " << preprocessor.describe(failure) << '\n'; + return false; + } + } + catch (const assembly::AssemblyError& failure) + { + std::cerr << "ERROR: " << path << ':' << failure.line << ": " << failure.message << '\n'; + } + catch (const native::BackendError& failure) + { + std::cerr << "ERROR: " << path << ": " << failure.what() << '\n'; + } + catch (const SourceError& failure) + { + std::cerr << "ERROR: " << path << ": " << failure.what() << '\n'; + } + catch (const PreprocessError& failure) + { + std::cerr << "ERROR: " << path << ": " << failure.what() << '\n'; + } + return false; +} + +} // namespace driver diff --git a/dev/src/driver/native_assembly.h b/dev/src/driver/native_assembly.h new file mode 100644 index 0000000000..47f3ca1bc6 --- /dev/null +++ b/dev/src/driver/native_assembly.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +#include "native/target.h" + +struct PreprocessorOptions; + +namespace native { +namespace object { +struct ObjectFile; +} +} + +namespace driver { + +bool compile_native_assembly(const std::string& path, const PreprocessorOptions& base, native::Target target, + native::object::ObjectFile& object); + +} // namespace driver diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index fd5f2fe79e..bc33fb0709 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -12,6 +12,7 @@ #include "abi/itanium/abi_encoding_error.h" #include "driver/host_environment.h" +#include "driver/native_assembly.h" #include "driver/wasm_environment.h" #include "driver/wasm_link_options.h" #include "lex/post_token_writer.h" @@ -43,11 +44,13 @@ namespace driver { // Source dialect and feature gates share the token tools' standard names. void language_standard(const std::string& standard, PreprocessorOptions& options) { - if (standard == "c17" || standard == "gnu17") + const bool c99 = standard == "c99" || standard == "gnu99"; + if (c99 || standard == "c17" || standard == "gnu17") { options.language = SourceLanguage::C; options.cplusplus.clear(); - options.strict = standard == "c17"; + options.c_version = c99 ? "199901L" : "201710L"; + options.strict = standard == "c99" || standard == "c17"; return; } options.language = SourceLanguage::Cxx; @@ -228,6 +231,20 @@ bool option_value(const std::vector& args, size_t& i, const char* o return false; } +bool parse_include_option(const std::vector& args, size_t& i, PreprocessorOptions& options) +{ + std::string value; + if (option_value(args, i, "-iquote", value)) + options.quote_include_paths.push_back(std::move(value)); + else if (option_value(args, i, "-isystem", value)) + options.system_include_paths.push_back(std::move(value)); + else if (option_value(args, i, "-I", value)) + options.include_paths.push_back(std::move(value)); + else + return false; + return true; +} + // GCC flags that change the program's types, layout, ABI or observable // behavior, which this compiler does not honor: refused rather than // accepted with another meaning (README: build-system flags are honored or @@ -253,50 +270,6 @@ bool accepted_flag(const std::string& arg) arg == "-MMD" || arg == "-MD" || arg == "-MP"; } -// GCC's include chain (cpplib's remove_duplicates): a directory named -// twice is searched at its first position only, and an -I directory that -// is also a system directory (-isystem or a standard one) is searched as -// that system directory ("the -I option is ignored"), so under -// -I/usr/include still finds libstdc++'s wrapper first. Directories are -// compared by device and inode. -void prune_include_paths(PreprocessorOptions& options) -{ - std::vector> seen; - const auto identity = [](const std::string& path, std::pair& id) { - struct stat status; - if (stat(path.c_str(), &status) != 0 || !S_ISDIR(status.st_mode)) - return false; - id = std::make_pair(status.st_dev, status.st_ino); - return true; - }; - const auto first = [&](const std::string& path) { - std::pair id; - if (!identity(path, id)) - return true; - for (const std::pair& other : seen) - { - if (other == id) - return false; - } - seen.push_back(id); - return true; - }; - std::vector system; - for (const std::string& path : options.system_include_paths) - { - if (first(path)) - system.push_back(path); - } - std::vector user; - for (const std::string& path : options.include_paths) - { - if (first(path)) - user.push_back(path); - } - options.system_include_paths.swap(system); - options.include_paths.swap(user); -} - void configure_target_runtime(Invocation& invocation, bool nostdinc) { configure_target_environment(invocation.preprocessor, invocation.target); @@ -530,10 +503,8 @@ Invocation parse(const std::vector& args, const PreprocessorOptions if (!native::parse_target(target, invocation.target)) throw InvocationError("unsupported target: " + target); } - else if (option_value(args, i, "-isystem", value)) - invocation.preprocessor.system_include_paths.push_back(value); - else if (option_value(args, i, "-I", value)) - invocation.preprocessor.include_paths.push_back(value); + else if (parse_include_option(args, i, invocation.preprocessor)) + continue; else if (option_value(args, i, "-D", value)) { const size_t equals = value.find('='); @@ -858,6 +829,8 @@ bool compile_lowir_unit(const std::string& path, const Invocation& invocation, n bool compile_input(const Input& input, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object, const std::string* lowir_output = nullptr) { + if (input.kind == Input::Kind::Assembly) + return compile_native_assembly(input.name, invocation.preprocessor, invocation.target, object); return input.kind == Input::Kind::LowIR ? compile_lowir_unit(input.name, invocation, eh_model, object, lowir_output) : compile_unit(input.name, invocation, eh_model, object, lowir_output); } @@ -921,8 +894,8 @@ int compile_mode(const Invocation& invocation) { if (input.kind == Input::Kind::Library) continue; - if (input.kind != Input::Kind::Source && input.kind != Input::Kind::LowIR) - throw InvocationError("-c needs C++ source or LowIR inputs: " + input.name); + if (input.kind == Input::Kind::Object) + throw InvocationError("-c needs source, assembly or LowIR inputs: " + input.name); native::object::ObjectFile object; const std::string output = default_output_name(invocation, input); if (invocation.emit_lowir) @@ -973,7 +946,8 @@ int link_mode(const Invocation& invocation) { objects.push_back(native::object::ObjectFile()); native::object::ObjectFile& object = objects.back(); - if (input.kind == Input::Kind::Source || input.kind == Input::Kind::LowIR) + if (input.kind == Input::Kind::Source || input.kind == Input::Kind::LowIR || + input.kind == Input::Kind::Assembly) { if (!compile_input(input, invocation, native::EhModel::Course, object)) return EXIT_FAILURE; @@ -1284,8 +1258,8 @@ int run_toolchain(const std::vector& args, const PreprocessorOption const Invocation invocation = parse(args, base); for (const Input& input : invocation.inputs) if (input.kind == Input::Kind::Assembly && - (!target_model::is_wasm(invocation.target) || invocation.preprocess_only || invocation.syntax_only)) - throw InvocationError("Wasm assembly requires a Wasm compile or link invocation"); + (invocation.preprocess_only || invocation.syntax_only || invocation.emit_lowir)) + throw InvocationError("assembly input requires a compile or link invocation"); if (!target_model::is_wasm(invocation.target) && !invocation.exports.empty()) throw InvocationError("explicit function exports require a Wasm target"); diff --git a/dev/src/lex/gnu_builtins.cpp b/dev/src/lex/gnu_builtins.cpp index 17f7c05d0d..7d12550a2f 100644 --- a/dev/src/lex/gnu_builtins.cpp +++ b/dev/src/lex/gnu_builtins.cpp @@ -20,6 +20,7 @@ const struct { "__builtin_abort", { GnuBuiltin::Abort, 0, "v", 0 } }, { "__builtin_abs", { GnuBuiltin::Library, 0, "ii", 0 } }, { "__builtin_add_overflow", { GnuBuiltin::Overflow, 0, nullptr, 0 } }, + { "__builtin_add_overflow_p", { GnuBuiltin::Overflow, 3, nullptr, 0 } }, { "__builtin_addressof", { GnuBuiltin::AddressOf, 0, nullptr, 0 } }, { "__builtin_alloca", { GnuBuiltin::Alloca, 0, nullptr, 0 } }, { "__builtin_assume_aligned", { GnuBuiltin::AssumeAligned, 0, nullptr, 0 } }, @@ -260,6 +261,7 @@ const struct { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::HorizontalSub), "DDD", 0 } }, { "__builtin_ia32_hsubps", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::HorizontalSub), "FFF", 0 } }, + { "__builtin_ia32_insert128i256", { GnuBuiltin::VectorBinaryImmediate, 2, nullptr, 0 } }, { "__builtin_ia32_insertps128", { GnuBuiltin::VectorImmediate, 2, "FFFi", 0 } }, { "__builtin_ia32_lddqu", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::Load), "Bc*", 0 } }, { "__builtin_ia32_ldmxcsr", { GnuBuiltin::Mxcsr, 1, nullptr, 0 } }, @@ -450,6 +452,10 @@ const struct { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::MulHigh), "HHH", 0 } }, { "__builtin_ia32_pmuludq128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::MulWideUnsigned), "QWW", 0 } }, + { "__builtin_ia32_pmuludq256", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::MulWideUnsigned), "2Q2W2W", 0 } }, + { "__builtin_ia32_pmuludq512_mask", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::MulWideUnsigned), "4Q4W4W4Qx", 'm' } }, { "__builtin_ia32_prefetch", { GnuBuiltin::Prefetch, 1, nullptr, 0 } }, { "__builtin_ia32_psadbw128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::SumAbsoluteDifference), "QBB", 0 } }, @@ -462,6 +468,8 @@ const struct { "__builtin_ia32_pshufb512_mask", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ByteShuffle), "4B4B4B4Bx", 'm' } }, { "__builtin_ia32_pshufd", { GnuBuiltin::VectorShuffle, 0, nullptr, 0 } }, + { "__builtin_ia32_pshufd256", { GnuBuiltin::VectorShuffle, 5, nullptr, 0 } }, + { "__builtin_ia32_pshufd512_mask", { GnuBuiltin::VectorShuffle, 6, nullptr, 0 } }, { "__builtin_ia32_pshufhw", { GnuBuiltin::VectorShuffle, 3, nullptr, 0 } }, { "__builtin_ia32_pshuflw", { GnuBuiltin::VectorShuffle, 2, nullptr, 0 } }, { "__builtin_ia32_psignb128", @@ -478,6 +486,10 @@ const struct { "__builtin_ia32_psllq128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftLeft), "QQQ", 0 } }, { "__builtin_ia32_psllqi128", { GnuBuiltin::VectorShiftLanes, 6, nullptr, 0 } }, + { "__builtin_ia32_psllqi256", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftLeft), "2Q2Qi", 0 } }, + { "__builtin_ia32_psllqi512_mask", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftLeft), "4Q4Qi4Qx", 'm' } }, { "__builtin_ia32_psllw128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftLeft), "HHH", 0 } }, { "__builtin_ia32_psllwi128", { GnuBuiltin::VectorShiftLanes, 0, nullptr, 0 } }, @@ -501,6 +513,10 @@ const struct { "__builtin_ia32_psrlq128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "QQQ", 0 } }, { "__builtin_ia32_psrlqi128", { GnuBuiltin::VectorShiftLanes, 7, nullptr, 0 } }, + { "__builtin_ia32_psrlqi256", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "2Q2Qi", 0 } }, + { "__builtin_ia32_psrlqi512_mask", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "4Q4Qi4Qx", 'm' } }, { "__builtin_ia32_psrlw128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "HHH", 0 } }, { "__builtin_ia32_psrlwi128", { GnuBuiltin::VectorShiftLanes, 1, nullptr, 0 } }, @@ -510,6 +526,8 @@ const struct { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "4H4Hi", 0 } }, { "__builtin_ia32_psrlwi512_mask", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::ShiftRightLogical), "4H4Hi4Hx", 'm' } }, + { "__builtin_ia32_psubq512_mask", + { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::Sub), "4Q4Q4Q4Qx", 'm' } }, { "__builtin_ia32_psubsb128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::SubSaturate), "BBB", 0 } }, { "__builtin_ia32_psubsw128", @@ -522,6 +540,7 @@ const struct { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::SubSaturateUnsigned), "4B4B4B4Bx", 'm' } }, { "__builtin_ia32_psubusw128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::SubSaturateUnsigned), "HHH", 0 } }, + { "__builtin_ia32_pternlogd512_mask", { GnuBuiltin::VectorTernary, 0, nullptr, 0 } }, { "__builtin_ia32_ptestc128", { GnuBuiltin::VectorLanewise, static_cast(VectorLanewiseOp::TestCarry), "iQQ", 0 } }, { "__builtin_ia32_ptestmb512", @@ -663,6 +682,7 @@ const struct { "__builtin_memmove", { GnuBuiltin::Memmove, 0, "v*v*Cv*z", 0 } }, { "__builtin_memset", { GnuBuiltin::Library, 0, "v*v*iz", 0 } }, { "__builtin_mul_overflow", { GnuBuiltin::Overflow, 2, nullptr, 0 } }, + { "__builtin_mul_overflow_p", { GnuBuiltin::Overflow, 5, nullptr, 0 } }, { "__builtin_nan", { GnuBuiltin::FloatConstant, 0, nullptr, 0 } }, { "__builtin_nanf", { GnuBuiltin::FloatConstant, 1, nullptr, 0 } }, { "__builtin_nanl", { GnuBuiltin::FloatConstant, 2, nullptr, 0 } }, @@ -703,6 +723,7 @@ const struct { "__builtin_strrchr", { GnuBuiltin::Library, 0, "c*Cc*i", 0 } }, { "__builtin_strstr", { GnuBuiltin::Library, 0, "c*Cc*Cc*", 0 } }, { "__builtin_sub_overflow", { GnuBuiltin::Overflow, 1, nullptr, 0 } }, + { "__builtin_sub_overflow_p", { GnuBuiltin::Overflow, 4, nullptr, 0 } }, { "__builtin_trap", { GnuBuiltin::Trap, 0, "v", 0 } }, { "__builtin_unreachable", { GnuBuiltin::Unreachable, 0, "v", 0 } }, { "__builtin_va_copy", { GnuBuiltin::VaList, 2, nullptr, 0 } }, diff --git a/dev/src/lex/gnu_builtins.h b/dev/src/lex/gnu_builtins.h index 3a911cdb9d..e0a623d405 100644 --- a/dev/src/lex/gnu_builtins.h +++ b/dev/src/lex/gnu_builtins.h @@ -90,6 +90,7 @@ enum class GnuBuiltin : uint8_t VectorShiftLanes, // SSE immediate lane shuffles: 0 pshufd, 1 shufpd, 2 pshuflw, 3 pshufhw, 4 shufps. VectorShuffle, + VectorTernary, // Two integer vectors and an immediate: PCLMULQDQ (128 bits), // or selection of two 128-bit halves from 256-bit inputs. VectorBinaryImmediate, diff --git a/dev/src/lower/c_compound_literals.cpp b/dev/src/lower/c_compound_literals.cpp index 09b083d706..9ce9c1f4e1 100644 --- a/dev/src/lower/c_compound_literals.cpp +++ b/dev/src/lower/c_compound_literals.cpp @@ -1,6 +1,7 @@ #include "lower/function_lowering.h" #include "sema/conversions.h" +#include "sema/aggregates.h" namespace lower { @@ -30,6 +31,8 @@ Place FunctionLowering::compound_literal(const syntax::FunctionalCastExpr& expr) else if (sema::ClassOf(type) != nullptr) aggregate_object(type, AddressPath{ AddressPath::Root::Storage, object.storage, path_steps_.size() }, expr.braced, true, expr.location); + else if (sema::LaneList(type, *expr.braced)) + store(lowering_.storage_type(type), vector_list(type, *expr.braced), object); else { const RValue value = expr.braced->elements.empty() diff --git a/dev/src/lower/expression_lowering.cpp b/dev/src/lower/expression_lowering.cpp index f33c392726..c029c48ed8 100644 --- a/dev/src/lower/expression_lowering.cpp +++ b/dev/src/lower/expression_lowering.cpp @@ -1902,8 +1902,6 @@ Place FunctionLowering::assignment(const syntax::BinaryExpr& expr) // 5.17p1: the right operand is evaluated before the left's address. const sema::ExprFacts* left_facts = WithoutParentheses(expr.left)->facts; const sema::Type* type = left_facts->type; - if (type->unqualified->kind == sema::TypeKind::Class) - throw LoweringError(expr.location, "class assignment is outside the procedural lowering slice"); RValue value; if (expr.right->kind == syntax::ExprKind::BracedInit) { @@ -1913,6 +1911,18 @@ Place FunctionLowering::assignment(const syntax::BinaryExpr& expr) : list.elements.empty() ? zero_value(type) : operand(*list.elements[0], ConversionContext::Assignment); } + else if (sema::ClassOf(type) != nullptr) + { + const syntax::Expr* source = WithoutParentheses(expr.right); + if (source->facts->category == sema::ValueCategory::PRValue && source->kind != syntax::ExprKind::Assign) + { + Place temporary = Place(); + temporary.storage = temporary_object(*source); + value = load(lowering_.storage_type(type), temporary); + } + else + value = rvalue(*source); + } else { // A union member's assignment, and a class template diff --git a/dev/src/lower/function_lowering.h b/dev/src/lower/function_lowering.h index a206ce3dd4..f2cf8ee4de 100644 --- a/dev/src/lower/function_lowering.h +++ b/dev/src/lower/function_lowering.h @@ -1488,6 +1488,7 @@ class FunctionLowering // 0 left, 1 logical right, 2 arithmetic right by an int count. RValue shift_lanes(const sema::Type* vector, const RValue& value, const RValue& count, unsigned operation); RValue shuffle_vector(const syntax::CallExpr& expr); + RValue ternary_vector(const syntax::CallExpr& expr); RValue binary_immediate_vector(const syntax::CallExpr& expr); RValue immediate_vector(const syntax::CallExpr& expr); bool immediate_vector_helper(lowir::VectorOp operation); @@ -1693,7 +1694,7 @@ class FunctionLowering RValue source_location(sema::Intrinsic kind, uint32_t location); RValue quiet_bit(const RValue& x); RValue wide_overflow(sema::Intrinsic kind, const RValue& a, const sema::IntegralKind& left_kind, const RValue& b, - const sema::IntegralKind& right_kind, const Place& target, lowir::Type stored, + const sema::IntegralKind& right_kind, const Place* target, lowir::Type stored, const sema::IntegralKind& result_kind); void push_converted(const syntax::Expr& argument, const sema::Type* parameter, const sema::Conversion* conversion); // ------------------ new and delete (lower/allocation_lowering.cpp) diff --git a/dev/src/lower/intrinsic_lowering.cpp b/dev/src/lower/intrinsic_lowering.cpp index a98b3303ad..ac117d2bca 100644 --- a/dev/src/lower/intrinsic_lowering.cpp +++ b/dev/src/lower/intrinsic_lowering.cpp @@ -425,6 +425,8 @@ RValue FunctionLowering::gnu_intrinsic(const syntax::CallExpr& expr, sema::Intri return shift_vector_lanes(expr); case sema::Intrinsic::VectorShuffle: return shuffle_vector(expr); + case sema::Intrinsic::VectorTernary: + return ternary_vector(expr); case sema::Intrinsic::VectorCarrylessMultiply: case sema::Intrinsic::VectorPermuteHalves: return binary_immediate_vector(expr); @@ -948,18 +950,26 @@ RValue FunctionLowering::overflow_intrinsic(const syntax::CallExpr& expr, sema:: : expr.arguments[1]->facts->type; const RValue a = operand(*expr.arguments[0], ConversionContext::Argument); const RValue b = operand(*expr.arguments[1], ConversionContext::Argument); - const RValue pointer = operand(*expr.arguments[2], ConversionContext::Argument); + const bool predicate = (expr.facts->value & sema::kOverflowPredicate) != 0; const sema::Type* result_type = expr.arguments[2]->facts->type->unqualified; - result_type = result_type->element->unqualified; + Place target = Place(); + if (predicate) + discard(*expr.arguments[2]); + else + { + target.storage = operand(*expr.arguments[2], ConversionContext::Argument).value; + result_type = result_type->element->unqualified; + } sema::IntegralKind left_kind, right_kind, result_kind; sema::IntegralKindOf(left_type, left_kind); sema::IntegralKindOf(right_type, right_kind); sema::IntegralKindOf(result_type, result_kind); + const uint64_t width = expr.facts->value >> sema::kOverflowResultWidthShift; + if (width != 0 && width < result_kind.bits) + result_kind.bits = static_cast(width); const lowir::Type stored = lowering_.storage_type(result_type); const lowir::Type i64 = lowir::Type::scalar(lowir::TypeKind::I64); - Place target = Place(); - target.storage = pointer.value; - const bool same = left_type->unqualified == result_type && right_type->unqualified == result_type; + const bool same = width == 0 && left_type->unqualified == result_type && right_type->unqualified == result_type; if (same && (kind != sema::Intrinsic::MulOverflow || result_kind.bits == 32) && result_kind.bits >= 32) { const lowir::Type type = a.type; @@ -970,12 +980,14 @@ RValue FunctionLowering::overflow_intrinsic(const syntax::CallExpr& expr, sema:: const RValue wide_b = convert_op(widen, i64, b); const RValue wide = binary(lowir::BinaryOp::Mul, i64, convert_op(widen, i64, a), wide_b); const RValue narrow = convert_op(lowir::ConvertOp::Trunc, type, wide); - store(stored, narrow, target); + if (!predicate) + store(stored, narrow, target); return compare(lowir::ComparePredicate::Ne, i64, wide, convert_op(widen, i64, narrow)); } const bool add = kind == sema::Intrinsic::AddOverflow; const RValue r = binary(add ? lowir::BinaryOp::Add : lowir::BinaryOp::Sub, type, a, b); - store(stored, r, target); + if (!predicate) + store(stored, r, target); if (!result_kind.is_signed) return add ? compare(lowir::ComparePredicate::Ult, type, r, a) : compare(lowir::ComparePredicate::Ult, type, a, b); @@ -987,7 +999,7 @@ RValue FunctionLowering::overflow_intrinsic(const syntax::CallExpr& expr, sema:: return compare(lowir::ComparePredicate::Lt, type, signs, integer(type, 0)); } if (left_kind.bits > 64 || right_kind.bits > 64 || result_kind.bits > 64) - return wide_overflow(kind, a, left_kind, b, right_kind, target, stored, result_kind); + return wide_overflow(kind, a, left_kind, b, right_kind, predicate ? nullptr : &target, stored, result_kind); const lowir::Type i128 = lowir::Type::scalar(lowir::TypeKind::I128); const auto widen = [&](const RValue& value, const sema::IntegralKind& kind) { return convert_op(kind.is_signed ? lowir::ConvertOp::SExt : lowir::ConvertOp::ZExt, i128, value); @@ -997,7 +1009,8 @@ RValue FunctionLowering::overflow_intrinsic(const syntax::CallExpr& expr, sema:: : lowir::BinaryOp::Mul; const RValue wide_b = widen(b, right_kind); const RValue r = binary(op, i128, widen(a, left_kind), wide_b); - store(stored, convert_op(lowir::ConvertOp::Trunc, stored, r), target); + if (!predicate) + store(stored, convert_op(lowir::ConvertOp::Trunc, stored, r), target); const uint32_t bits = result_kind.bits; const uint64_t max = result_kind.is_signed ? (uint64_t(1) << (bits - 1)) - 1 : bits == 64 ? ~uint64_t(0) @@ -1012,7 +1025,7 @@ RValue FunctionLowering::overflow_intrinsic(const syntax::CallExpr& expr, sema:: } RValue FunctionLowering::wide_overflow(sema::Intrinsic kind, const RValue& a, const sema::IntegralKind& left_kind, - const RValue& b, const sema::IntegralKind& right_kind, const Place& target, lowir::Type stored, + const RValue& b, const sema::IntegralKind& right_kind, const Place* target, lowir::Type stored, const sema::IntegralKind& result_kind) { // A 128-bit operand or result: each operand as a sign and a 128-bit @@ -1090,9 +1103,12 @@ RValue FunctionLowering::wide_overflow(sema::Intrinsic kind, const RValue& a, co // Stored modulo 2^N; representable when below 2^(N-1) (2^N unsigned) // in magnitude, or 2^(N-1) itself negative and signed, never negative // and unsigned (but zero). - const RValue mask = binary(lowir::BinaryOp::Sub, i128, zero, negative); - const RValue value = binary(lowir::BinaryOp::Sub, i128, binary(lowir::BinaryOp::Xor, i128, result, mask), mask); - store(stored, result_kind.bits == 128 ? value : convert_op(lowir::ConvertOp::Trunc, stored, value), target); + if (target != nullptr) + { + const RValue mask = binary(lowir::BinaryOp::Sub, i128, zero, negative); + const RValue value = binary(lowir::BinaryOp::Sub, i128, binary(lowir::BinaryOp::Xor, i128, result, mask), mask); + store(stored, result_kind.bits == 128 ? value : convert_op(lowir::ConvertOp::Trunc, stored, value), *target); + } const unsigned bits = result_kind.bits - (result_kind.is_signed ? 1 : 0); const lowir::Literal limit_bits = bits >= 128 ? lowir::Literal{ ~uint64_t(0), ~uint64_t(0) } : bits >= 64 ? lowir::Literal{ ~uint64_t(0), (uint64_t(1) << (bits - 64)) - 1 } diff --git a/dev/src/lower/object_lowering.cpp b/dev/src/lower/object_lowering.cpp index 023df1a094..782dcc2981 100644 --- a/dev/src/lower/object_lowering.cpp +++ b/dev/src/lower/object_lowering.cpp @@ -1,4 +1,5 @@ #include "lower/function_lowering.h" +#include "sema/analyzer.h" #include "sema/aggregates.h" #include "sema/conversions.h" @@ -892,6 +893,19 @@ void FunctionLowering::materialize_prvalue(const syntax::Expr& expr, lowir::Valu return; } const sema::ExprFacts* facts = e->facts; + if (lowering_.analyzer_->c_source() && sema::ClassOf(facts->type) != nullptr) + { + // C records initialize from their values, without a copy constructor. + if (facts->category == sema::ValueCategory::LValue || e->kind == syntax::ExprKind::Assign) + { + Place target = Place(); + target.storage = object; + const lowir::Type storage = lowering_.storage_type(facts->type); + store(storage, rvalue(*e), target); + return; + } + } + if (e->kind == syntax::ExprKind::Binary && (facts->flags & (sema::kRewrittenComparison | sema::kUserConverted | sema::kImmediateValue)) == sema::kRewrittenComparison) diff --git a/dev/src/lower/program_lowering.cpp b/dev/src/lower/program_lowering.cpp index f1d9529837..a3484f3ee4 100644 --- a/dev/src/lower/program_lowering.cpp +++ b/dev/src/lower/program_lowering.cpp @@ -755,6 +755,10 @@ void ProgramLowering::define_variable( bool ProgramLowering::emitted_at_definition(const sema::FunctionEntity* function) const { + // ISO C inline supplies an external definition if any file-scope + // declaration uses extern or leaves out inline (6.7.4p7). + if (analyzer_->c_source() && function->is_inline && !function->internal_linkage) + return function->c_external_definition && !function->gnu_inline; // An inline definition (7.1.2p4: every unit that odr-uses it defines // it) is emitted where odr-used; so is an internal always_inline one, // or one whose body calls a reserved builtin this compiler lacks (as @@ -774,7 +778,7 @@ void ProgramLowering::define_function(const sema::FunctionEntity* function, uint { // An inline function one unit already emitted; any other is defined // twice (3.2p3). - if (function->is_inline) + if (function->is_inline && !analyzer_->c_source()) return; throw LoweringError(location, "redefinition of a function across translation units"); } @@ -991,6 +995,9 @@ void ProgramLowering::demand_entry(const sema::FunctionEntity* function, EntryVa if (function->gnu_inline || (function->primary != nullptr && function->primary->gnu_inline) || (pattern != nullptr && pattern->gnu_inline)) return; + // An ISO C inline-only definition does not provide the external symbol. + if (analyzer_->c_source() && function->is_inline && !function->internal_linkage && !function->c_external_definition) + return; // A template's specialization (or an instance's member) is defined // where odr-used, its body instantiated on this demand (14.7.1p2). if (!synthesized && function->instantiated) diff --git a/dev/src/lower/symbol_lowering.cpp b/dev/src/lower/symbol_lowering.cpp index 9da5f91543..6b454c2802 100644 --- a/dev/src/lower/symbol_lowering.cpp +++ b/dev/src/lower/symbol_lowering.cpp @@ -2525,9 +2525,10 @@ lowir::SymbolMetadata ProgramLowering::function_metadata(const sema::FunctionEnt } // 3.5p4: a member of a class of internal linkage, or of a local class // (no linkage, 3.5p8), is internal to its unit. - metadata.binding = unit_local(function) ? ir_model::SBM_INTERNAL - : function->is_inline || function->instantiated ? ir_model::SBM_WEAK - : ir_model::SBM_STRONG; + const bool mergeable_inline = function->is_inline && !analyzer_->c_source(); + metadata.binding = unit_local(function) ? ir_model::SBM_INTERNAL + : mergeable_inline || function->instantiated ? ir_model::SBM_WEAK + : ir_model::SBM_STRONG; // GNU weak (the analysis allows it on entities with external linkage): // replaceable, an inline function's too (lowir.md `replaceable=yes`). const sema::SemanticGraph::SymbolAttributes* attributes = graph_->symbol_attributes(function); diff --git a/dev/src/lower/vector_immediates.cpp b/dev/src/lower/vector_immediates.cpp index 8581e4ba84..7cc016914d 100644 --- a/dev/src/lower/vector_immediates.cpp +++ b/dev/src/lower/vector_immediates.cpp @@ -102,6 +102,7 @@ RValue FunctionLowering::binary_immediate_vector(const syntax::CallExpr& expr) discard(*expr.arguments[2]); if (multiply && !deferred) return vector_instruction(lowir::VectorOp::Pclmulqdq, &first, &second, nullptr, immediate); + const bool insertion = (expr.facts->value >> 17 & 1) != 0; const lowir::Value a = vector_storage(first); const lowir::Value b = vector_storage(second); const auto read_word = [&](lowir::Value base, const RValue& offset) { @@ -124,6 +125,25 @@ RValue FunctionLowering::binary_immediate_vector(const syntax::CallExpr& expr) } lowir::SlotId slot = lowir::kNoId; const lowir::Value out = zeroed_vector(expr.facts->type, slot); + if (insertion) + { + const RValue selected = binary(lowir::BinaryOp::And, i64, count, integer(i64, 1)); + const sema::Type* type = expr.facts->type; + for (uint32_t half = 0; half < 2; ++half) + { + const RValue replace = compare(lowir::ComparePredicate::Eq, i64, selected, integer(i64, half)); + for (uint32_t lane = 0; lane < 2; ++lane) + { + const uint32_t index = half * 2 + lane; + const RValue value = select_value( + replace, read_word(b, integer(i64, lane * 8)), read_word(a, integer(i64, index * 8))); + set_vector_lane(out, type, index, value); + } + } + Place result = Place(); + result.storage = out; + return load(lowering_.storage_type(type), result); + } RValue first_address; first_address.type = ptr; first_address.value = a; @@ -151,4 +171,67 @@ RValue FunctionLowering::binary_immediate_vector(const syntax::CallExpr& expr) return load(lowering_.storage_type(expr.facts->type), result); } +RValue FunctionLowering::ternary_vector(const syntax::CallExpr& expr) +{ + using lowir::BinaryOp; + const sema::Type* type = expr.facts->type; + const lowir::Type word = lowir::Type::scalar(lowir::TypeKind::I32); + const RValue zero = integer(word, 0); + const RValue ones = integer(word, UINT32_MAX); + lowir::Value args[3]; + for (unsigned i = 0; i < 3; ++i) + args[i] = vector_storage(operand(*expr.arguments[i], ConversionContext::Argument)); + const bool deferred = (expr.facts->value >> 16 & 1) != 0; + const unsigned immediate = static_cast(expr.facts->value >> 8 & 255); + RValue selector; + if (deferred) + { + selector = operand(*expr.arguments[3], ConversionContext::Argument); + builder_.call(lowir::Type::scalar(lowir::TypeKind::Void), + lowir::Value::symbol(lowering_.source_immediate_guard()), &selector.value, 1, lowir::kNoId, 0); + } + else + discard(*expr.arguments[3]); + const RValue lanes = convert_op( + lowir::ConvertOp::ZExt, word, operand(*expr.arguments[4], ConversionContext::Argument)); + RValue table[8]; + if (deferred) + for (unsigned i = 0; i < 8; ++i) + table[i] = binary(BinaryOp::Sub, word, zero, + binary( + BinaryOp::And, word, binary(BinaryOp::UShr, word, selector, integer(word, i)), integer(word, 1))); + lowir::SlotId slot = lowir::kNoId; + const lowir::Value out = zeroed_vector(type, slot); + for (unsigned lane = 0; lane < type->bound; ++lane) + { + const RValue a = vector_lane(args[0], type, lane); + const RValue b = vector_lane(args[1], type, lane); + const RValue c = vector_lane(args[2], type, lane); + const RValue inputs[] = { c, b, a }; + RValue result = zero; + if (!deferred && immediate == 0x96) + result = binary(BinaryOp::Xor, word, binary(BinaryOp::Xor, word, a, b), c); + else + for (unsigned i = 0; i < 8; ++i) + { + if (!deferred && (immediate & (1u << i)) == 0) + continue; + RValue term = deferred ? table[i] : ones; + for (unsigned bit = 0; bit < 3; ++bit) + { + const RValue value = (i & (1u << bit)) != 0 ? inputs[bit] + : binary(BinaryOp::Xor, word, inputs[bit], ones); + term = binary(BinaryOp::And, word, term, value); + } + result = binary(BinaryOp::Or, word, result, term); + } + const RValue mask = binary(BinaryOp::And, word, lanes, integer(word, uint64_t(1) << lane)); + const RValue enabled = compare(lowir::ComparePredicate::Ne, word, mask, zero); + set_vector_lane(out, type, lane, select_value(enabled, result, a)); + } + Place place = Place(); + place.storage = out; + return load(lowering_.storage_type(type), place); +} + } // namespace lower diff --git a/dev/src/lower/vector_lowering.cpp b/dev/src/lower/vector_lowering.cpp index 3e4f7c8394..811af6347f 100644 --- a/dev/src/lower/vector_lowering.cpp +++ b/dev/src/lower/vector_lowering.cpp @@ -824,9 +824,11 @@ RValue FunctionLowering::shuffle_vector(const syntax::CallExpr& expr) const sema::Type* vector = expr.facts->type; const bool doubles = vector->bound == 2; const bool paired = expr.arguments.size == 3; - const bool words = vector->bound == 8; + const bool words = vector->bound == 8 && vector->element->fundamental == FundamentalType::ShortInt; + const bool masked = (expr.facts->value >> 18 & 1) != 0; + const bool wide_dwords = vector->bound >= 8 && !words; const uint64_t start = words && (expr.facts->value >> 17 & 1) != 0 ? 4 : 0; - const uint64_t mask = words ? 3 : vector->bound - 1; + const uint64_t mask = words || wide_dwords ? 3 : vector->bound - 1; const RValue first_value = operand(*expr.arguments[0], ConversionContext::Argument); const RValue second_value = paired ? operand(*expr.arguments[1], ConversionContext::Argument) : first_value; const syntax::Expr& selector = *expr.arguments[paired ? 2 : 1]; @@ -856,6 +858,11 @@ RValue FunctionLowering::shuffle_vector(const syntax::CallExpr& expr) convert_op(lowir::ConvertOp::Trunc, lowir::Type::scalar(lowir::TypeKind::I32), count)); const lowir::Value first = vector_storage(first_value); const lowir::Value second = paired ? vector_storage(second_value) : first; + const lowir::Value merge = masked ? vector_storage(operand(*expr.arguments[2], ConversionContext::Argument)) + : lowir::Value(); + const RValue lanes = masked + ? convert_op(lowir::ConvertOp::ZExt, i64, operand(*expr.arguments[3], ConversionContext::Argument)) + : RValue(); const uint64_t immediate = expr.facts->value >> 8 & 0xff; lowir::SlotId slot = lowir::kNoId; const lowir::Value out = zeroed_vector(vector, slot); @@ -866,22 +873,29 @@ RValue FunctionLowering::shuffle_vector(const syntax::CallExpr& expr) set_vector_lane(out, vector, i, vector_lane(first, vector, i)); continue; } - const uint64_t shift = (i - start) * (doubles ? 1 : 2); + const uint64_t half = wide_dwords ? (i & ~uint64_t(3)) : start; + const uint64_t shift = (i - half) * (doubles ? 1 : 2); const lowir::Value source = paired && i >= vector->bound / 2 ? second : first; RValue lane; if (runtime) { RValue offset = binary(lowir::BinaryOp::UShr, i64, count, integer(i64, shift)); offset = binary(lowir::BinaryOp::And, i64, offset, integer(i64, mask)); - if (start != 0) - offset = binary(lowir::BinaryOp::Add, i64, offset, integer(i64, start)); - offset = binary(lowir::BinaryOp::Mul, i64, offset, integer(i64, 16 / vector->bound)); + if (half != 0) + offset = binary(lowir::BinaryOp::Add, i64, offset, integer(i64, half)); + offset = binary(lowir::BinaryOp::Mul, i64, offset, integer(i64, wide_dwords ? 4 : 16 / vector->bound)); Place place = Place(); place.storage = index(lowir::Type::scalar(lowir::TypeKind::I8), ir_model::IPK_FIELD, source, offset).value; lane = load(lowering_.storage_type(vector->element), place); } else - lane = vector_lane(source, vector, start + (immediate >> shift & mask)); + lane = vector_lane(source, vector, half + (immediate >> shift & mask)); + if (masked) + { + const RValue bit = binary(lowir::BinaryOp::And, i64, lanes, integer(i64, uint64_t(1) << i)); + const RValue enabled = compare(lowir::ComparePredicate::Ne, i64, bit, integer(i64, 0)); + lane = select_value(enabled, lane, vector_lane(merge, vector, i)); + } set_vector_lane(out, vector, i, lane); } Place place = Place(); diff --git a/dev/src/native/asm/encoding.cpp b/dev/src/native/asm/encoding.cpp index 040bbcaebc..3494708324 100644 --- a/dev/src/native/asm/encoding.cpp +++ b/dev/src/native/asm/encoding.cpp @@ -167,7 +167,11 @@ void encode_instruction(Assembler& out, const assembly::Instruction& inst) uint16_t suffix = 0; const Form* form = asm_detail::assembly_form(inst.mnemonic, suffix, static_cast(inst.operands.size())); if (form == nullptr) + { + if (encode_bmi2_shift(out, inst)) + return; fail(inst, "instruction form is not implemented"); + } if (form->encoding == Encoding::Control) { encode_control_form(out, inst, *form, suffix); diff --git a/dev/src/native/asm/module_directives.cpp b/dev/src/native/asm/module_directives.cpp index a727891f8c..62c9570155 100644 --- a/dev/src/native/asm/module_directives.cpp +++ b/dev/src/native/asm/module_directives.cpp @@ -201,7 +201,10 @@ bool ModuleAssembler::directive(const std::string& name, assembly::ModuleCursor& { if (name == ".pushsection") section_stack_.push_back(section_); - std::string section_name = cursor.quoted_start() ? cursor.quoted() : cursor.word(); + const bool quoted = cursor.quoted_start(); + std::string section_name = quoted ? cursor.quoted() : cursor.word(); + while (!quoted && cursor.take('-')) + section_name += "-" + cursor.word(); if (section_name.empty()) cursor.fail("module section name cannot be empty"); SectionKind kind = SectionKind::Data; diff --git a/dev/src/native/asm/vex_forms.cpp b/dev/src/native/asm/vex_forms.cpp index bd7366cbd9..a4f4329654 100644 --- a/dev/src/native/asm/vex_forms.cpp +++ b/dev/src/native/asm/vex_forms.cpp @@ -51,7 +51,31 @@ void emit(Assembler& out, const VexForm& form, unsigned bits, unsigned reg, unsi out.byte(control); } +} // namespace + +bool encode_bmi2_shift(Assembler& out, const Instruction& inst) +{ + const std::string& name = inst.mnemonic; + const uint8_t prefix = name.compare(0, 4, "shlx") == 0 ? 1 + : name.compare(0, 4, "sarx") == 0 ? 2 + : name.compare(0, 4, "shrx") == 0 ? 3 + : 0; + if (prefix == 0 || (name.size() != 4 && (name.size() != 5 || (name.back() != 'l' && name.back() != 'q')))) + return false; + if (inst.prefix != 0 || inst.operands.size() != 3 || inst.operands[0].kind != OperandKind::Register || + inst.operands[2].kind != OperandKind::Register) + fail(inst, "BMI2 shift requires a register destination, register or memory source, and register count"); + const unsigned suffix = name.size() == 4 ? 0 : name.back() == 'q' ? 64 : 32; + const unsigned bits = asm_detail::integer_width(inst, static_cast(suffix)); + if (bits != 32 && bits != 64) + fail(inst, "BMI2 shift requires 32-bit or 64-bit operands"); + const VexForm form = { nullptr, L::Move, 0xf7, 2, prefix, static_cast(bits == 64), 0, 0, 0, 0 }; + emit(out, form, bits, asm_detail::physical(inst.operands[0].reg, inst), + asm_detail::physical(inst.operands[2].reg, inst), asm_detail::rm(inst.operands[1], inst), form.opcode, false, + 0); + return true; } + void encode_vex_plan(Assembler& out, const x86_asm_model::VexForm& form, const VectorEncodingPlan& plan) { emit(out, form, plan.bits, plan.reg, plan.source, plan.other, plan.opcode, plan.has_immediate, plan.control); diff --git a/dev/src/native/asm/vex_forms.h b/dev/src/native/asm/vex_forms.h index cbf9cc1d4c..ed17b5f421 100644 --- a/dev/src/native/asm/vex_forms.h +++ b/dev/src/native/asm/vex_forms.h @@ -9,6 +9,7 @@ namespace native { // widen the ordinary MIR register sets or fabricate scalar value carriers. void encode_vex_plan(Assembler& out, const x86_asm_model::VexForm& form, const VectorEncodingPlan& plan); bool encode_vex_form(Assembler& out, const assembly::Instruction& instruction); +bool encode_bmi2_shift(Assembler& out, const assembly::Instruction& instruction); void encode_assembly_vector_transfer( Assembler& out, const asm_model::Register& reg, const RM& memory, bool store, unsigned bytes); } // namespace native diff --git a/dev/src/native/object/elf_object_writer.cpp b/dev/src/native/object/elf_object_writer.cpp index c3241b0272..93f653d8e4 100644 --- a/dev/src/native/object/elf_object_writer.cpp +++ b/dev/src/native/object/elf_object_writer.cpp @@ -128,6 +128,7 @@ class Encoder uint32_t strtab_ = 0; uint32_t shstrtab_ = 0; bool extended_ = false; + bool has_stack_note_ = false; }; uint32_t Encoder::section_name(bool rela, uint32_t name) @@ -217,6 +218,8 @@ void Encoder::add_contents() const Section& from = object_.sections[s]; OutputSection section = OutputSection(); section.name = section_name(false, from.name); + if (from.kind == SectionKind::Metadata && std::strcmp(object_.string(from.name), ".note.GNU-stack") == 0) + has_stack_note_ = true; section.type = section_type(from.kind); section.flags = section_flags(from.kind) | (from.group != kNoGroup ? kShfGroup : 0); const bool nobits = from.kind == SectionKind::Bss || from.kind == SectionKind::TlsBss; @@ -325,12 +328,14 @@ void Encoder::encode(std::vector& out) shstrtab.type = kShtStrtab; shstrtab.align = 1; OutputSection stack = OutputSection(); - stack.name = name(".note.GNU-stack", ""); + if (!has_stack_note_) + stack.name = name(".note.GNU-stack", ""); stack.type = kShtProgbits; stack.align = 1; shstrtab.built.assign(names_.begin(), names_.end()); sections_.push_back(std::move(shstrtab)); - sections_.push_back(std::move(stack)); + if (!has_stack_note_) + sections_.push_back(std::move(stack)); write(out); } diff --git a/dev/src/preprocess/preprocessor.cpp b/dev/src/preprocess/preprocessor.cpp index 03104a0dcc..ee5a2160cd 100644 --- a/dev/src/preprocess/preprocessor.cpp +++ b/dev/src/preprocess/preprocessor.cpp @@ -36,8 +36,8 @@ std::string PredefinedText(const PreprocessorOptions& options) if (options.assembler) text += "#define __ASSEMBLER__ 1\n"; if (options.language == SourceLanguage::C) - text += "#define __STDC__ 1\n#define __STDC_VERSION__ 201710L\n" - "#define __STDC_NO_VLA__ 1\n#define __STDC_NO_THREADS__ 1\n"; + text += std::string("#define __STDC__ 1\n#define __STDC_VERSION__ ") + options.c_version + + "\n#define __STDC_NO_VLA__ 1\n#define __STDC_NO_THREADS__ 1\n"; else text += "#define __cplusplus " + options.cplusplus + "\n"; text += std::string("#define __STDC_HOSTED__ ") + (options.target == target_model::Target::Wasm32 ? "0\n" : "1\n") + @@ -164,8 +164,11 @@ Preprocessor::Preprocessor(const PreprocessorOptions& options, const std::string host_predefines_end_ = source_.current_inclusion().base + static_cast(predefined_->buffer().size()) + 1; } - include_paths_ = options.include_paths; - system_paths_ = include_paths_.size(); + angle_paths_ = options.quote_include_paths.size(); + system_paths_ = angle_paths_ + options.include_paths.size(); + include_paths_.reserve(system_paths_ + options.system_include_paths.size()); + include_paths_.insert(include_paths_.end(), options.quote_include_paths.begin(), options.quote_include_paths.end()); + include_paths_.insert(include_paths_.end(), options.include_paths.begin(), options.include_paths.end()); include_paths_.insert( include_paths_.end(), options.system_include_paths.begin(), options.system_include_paths.end()); } diff --git a/dev/src/preprocess/preprocessor.h b/dev/src/preprocess/preprocessor.h index b9b8af5f49..2f1a7ae339 100644 --- a/dev/src/preprocess/preprocessor.h +++ b/dev/src/preprocess/preprocessor.h @@ -35,6 +35,8 @@ struct PreprocessorOptions // Directories searched for an included file after the including file's // directory and before the working directory (-I, in order). std::vector include_paths; + // Directories searched only for quoted includes, before the -I chain. + std::vector quote_include_paths; // Hosted mode (cppgm's -E, -c and link modes, PA26/PA30): the system // directories searched after include_paths by both #include forms // (-isystem, then the host's standard directories unless -nostdinc), @@ -65,6 +67,8 @@ struct PreprocessorOptions FeatureModes modes; // __cplusplus's value (201103L, 201402L, 201703L or 202002L). std::string cplusplus = "201103L"; + // __STDC_VERSION__ for C source. + const char* c_version = "201710L"; // The strict ISO dialect (-std=c++11, c++14, c++17): the host's // predefined macros for it (__STRICT_ANSI__) instead of the GNU // dialect's (gnu++11 ..., and the default). @@ -252,9 +256,10 @@ class Preprocessor final : public PPTokenCursor, uint32_t host_predefines_end_; uint32_t builtin_begin_; uint32_t builtin_end_; - // The -I directories, then the system directories (hosted mode), which - // start at system_paths_. + // Quote-only directories, then the -I and system directories. + // Includes retain the index in this combined chain for #include_next. std::vector include_paths_; + size_t angle_paths_; size_t system_paths_; std::string missing_headers_note_; bool hosted_; diff --git a/dev/src/preprocess/preprocessor_directives.cpp b/dev/src/preprocess/preprocessor_directives.cpp index 0bed932fbe..def1885fe5 100644 --- a/dev/src/preprocess/preprocessor_directives.cpp +++ b/dev/src/preprocess/preprocessor_directives.cpp @@ -481,10 +481,11 @@ SourceFile* Preprocessor::find_include( // one, and nothing else. SourceFile* file = nullptr; index = -1; + const size_t start = angle ? angle_paths_ : 0; if (next) { const int32_t found_in = source_.current().search_index; - for (size_t i = found_in < 0 ? 0 : static_cast(found_in) + 1; + for (size_t i = found_in < 0 ? start : static_cast(found_in) + 1; file == nullptr && i < include_paths_.size(); ++i) { if ((file = files_.open(path = joined_path(include_paths_[i], name))) != nullptr) @@ -494,7 +495,7 @@ SourceFile* Preprocessor::find_include( } const std::string current = source_.current_inclusion().presumed_name; const std::size_t slash = current.rfind('/'); - size_t i = 0; + size_t i = start; if (angle) { for (; file == nullptr && i < include_paths_.size(); ++i) diff --git a/dev/src/sema/analyzer.cpp b/dev/src/sema/analyzer.cpp index 79852d5134..6cffd53151 100644 --- a/dev/src/sema/analyzer.cpp +++ b/dev/src/sema/analyzer.cpp @@ -859,14 +859,16 @@ void Analyzer::alias_declaration(const syntax::AliasDecl& decl, Scope* scope) // A deferred reserved builtin call (see deferrable_statement). if (deferred_reserved_call()) return; - if (specifiers.type == nullptr || specifiers.type == auto_placeholder_ || - specifiers.type == decltype_auto_placeholder_) + if (specifiers.type == nullptr) error(decl.location, "alias-declaration without a type"); if (!specifiers.mode_specifiers.empty()) filter_mode_alias(specifiers); const DeclaratorInfo info = declarator(decl.type->declarator, specifiers.type, scope, decl.location, specifiers.mode_specifiers.empty() ? nullptr : &specifiers, DeclaratorUse::TypeId); const Type* type = info.type; + if ((specifiers.type == auto_placeholder_ || specifiers.type == decltype_auto_placeholder_) && + holds_auto(info.type)) + error(decl.location, "alias-declaration without a type"); check_type_packs(type, decl.location); // 9.2p9, 7.1.2p1: no virt-specifier or function-specifier here. if (info.virt_suffix != nullptr || specifiers.is_virtual) diff --git a/dev/src/sema/analyzer.h b/dev/src/sema/analyzer.h index f24374c80a..1dada49e93 100644 --- a/dev/src/sema/analyzer.h +++ b/dev/src/sema/analyzer.h @@ -1250,6 +1250,7 @@ class Analyzer ExprFacts* vector_lane_builtin(const syntax::CallExpr& expr, uint8_t variant, Scope* scope); ExprFacts* vector_shift_builtin(const syntax::CallExpr& expr, uint8_t variant, Scope* scope); ExprFacts* vector_shuffle_builtin(const syntax::CallExpr& expr, uint8_t variant, Scope* scope); + ExprFacts* vector_ternary_builtin(const syntax::CallExpr& expr, Scope* scope); ExprFacts* vector_binary_immediate_builtin(const syntax::CallExpr& expr, uint8_t variant, Scope* scope); ExprFacts* vector_permute_builtin(const syntax::CallExpr& expr, uint8_t variant, Scope* scope); ExprFacts* vector_index_shuffle_builtin(const syntax::CallExpr& expr, Scope* scope); diff --git a/dev/src/sema/analyzer_builtins.cpp b/dev/src/sema/analyzer_builtins.cpp index 9202a3ab13..cac3e8002d 100644 --- a/dev/src/sema/analyzer_builtins.cpp +++ b/dev/src/sema/analyzer_builtins.cpp @@ -254,6 +254,8 @@ ExprFacts* Analyzer::builtin_operation(const syntax::CallExpr& expr, const Funct return vector_shift_builtin(expr, variant, scope); case GnuBuiltin::VectorShuffle: return vector_shuffle_builtin(expr, variant, scope); + case GnuBuiltin::VectorTernary: + return vector_ternary_builtin(expr, scope); case GnuBuiltin::VectorBinaryImmediate: return vector_binary_immediate_builtin(expr, variant, scope); case GnuBuiltin::VectorLanewise: @@ -617,8 +619,7 @@ ExprFacts* Analyzer::gnu_intrinsic(const syntax::CallExpr& expr, GnuBuiltin buil if (typed_value(*expr.arguments[i], scope) == nullptr) return nullptr; const bool constant = constant_value(*expr.arguments[i], scope, value, false); - if (!constant && - (variant == 0 || body_ == nullptr || body_->function == nullptr || !body_->function->always_inline)) + if (!constant && (body_ == nullptr || body_->function == nullptr || !body_->function->always_inline)) error(expr.arguments[i]->location, "a prefetch control must be an integral constant"); if (variant == 0 && constant && value.bits > (i == 1 ? 1u : 3u)) error(expr.arguments[i]->location, "__builtin_prefetch control is outside its permitted range"); @@ -1161,33 +1162,64 @@ ExprFacts* Analyzer::vector_shuffle_builtin(const syntax::CallExpr& expr, uint8_ const bool doubles = variant == 1; const bool words = variant == 2 || variant == 3; const bool floats = variant == 4; - const uint32_t count = doubles || floats ? 3 : 2; + const bool masked = variant == 6; + const uint32_t count = masked ? 4 : doubles || floats ? 3 : 2; + const uint32_t selector_index = doubles || floats ? 2 : 1; if (expr.arguments.size != count) error(expr.location, "wrong number of arguments to a packed lane shuffle"); const Type* vector = types_.vector(types_.fundamental(words ? FundamentalType::ShortInt : doubles ? FundamentalType::Double : floats ? FundamentalType::Float : FundamentalType::Int), - words ? 8 - : doubles ? 2 - : 4); + masked ? 16 + : words || variant == 5 ? 8 + : doubles ? 2 + : 4); for (uint32_t i = 0; i < count; ++i) { if (typed_value(*expr.arguments[i], scope) == nullptr) return nullptr; - convert(*expr.arguments[i], i == count - 1 ? types_.fundamental(FundamentalType::Int) : vector, false); + const Type* argument_type = i == selector_index ? types_.fundamental(FundamentalType::Int) + : masked && i == 3 ? types_.fundamental(FundamentalType::UnsignedShortInt) + : vector; + convert(*expr.arguments[i], argument_type, false); } Constant selector; - const bool constant = constant_value(*expr.arguments[count - 1], scope, selector, false); + const bool constant = constant_value(*expr.arguments[selector_index], scope, selector, false); if (!constant && template_depth_ == 0 && (body_ == nullptr || body_->function == nullptr || !body_->function->always_inline)) - error(expr.arguments[count - 1]->location, + error(expr.arguments[selector_index]->location, "a packed lane shuffle selector that is no integral constant expression"); ExprFacts* facts = new_facts(expr, vector, ValueCategory::PRValue); facts->flags |= kIntrinsic; facts->value = static_cast(Intrinsic::VectorShuffle) | (constant ? (selector.bits & (doubles ? 3U : 255U)) << 8 : uint64_t(1) << 16) | - (variant == 3 ? uint64_t(1) << 17 : 0); + (variant == 3 ? uint64_t(1) << 17 : 0) | (masked ? uint64_t(1) << 18 : 0); + return facts; +} + +ExprFacts* Analyzer::vector_ternary_builtin(const syntax::CallExpr& expr, Scope* scope) +{ + if (expr.arguments.size != 5) + error(expr.location, "wrong number of arguments to a masked ternary logic operation"); + const Type* vector = types_.vector(types_.fundamental(FundamentalType::Int), 16); + const Type* integer = types_.fundamental(FundamentalType::Int); + const Type* args[] = { vector, vector, vector, integer, types_.fundamental(FundamentalType::UnsignedShortInt) }; + for (uint32_t i = 0; i < 5; ++i) + { + if (typed_value(*expr.arguments[i], scope) == nullptr) + return nullptr; + convert(*expr.arguments[i], args[i], false); + } + Constant selector; + const bool constant = constant_value(*expr.arguments[3], scope, selector, false); + if (!constant && template_depth_ == 0 && + (body_ == nullptr || body_->function == nullptr || !body_->function->always_inline)) + error(expr.arguments[3]->location, "a ternary logic selector that is no integral constant expression"); + ExprFacts* facts = new_facts(expr, vector, ValueCategory::PRValue); + facts->flags |= kIntrinsic; + facts->value = static_cast(Intrinsic::VectorTernary) | + (constant ? (selector.bits & 255U) << 8 : uint64_t(1) << 16); return facts; } @@ -1200,7 +1232,10 @@ ExprFacts* Analyzer::vector_binary_immediate_builtin(const syntax::CallExpr& exp { if (typed_value(*expr.arguments[i], scope) == nullptr) return nullptr; - convert(*expr.arguments[i], i == 2 ? types_.fundamental(FundamentalType::Int) : vector, false); + const Type* type = i == 2 ? types_.fundamental(FundamentalType::Int) + : variant == 2 && i == 1 ? types_.vector(vector->element, 2) + : vector; + convert(*expr.arguments[i], type, false); if (failed()) return nullptr; } @@ -1220,7 +1255,7 @@ ExprFacts* Analyzer::vector_binary_immediate_builtin(const syntax::CallExpr& exp facts->flags |= kIntrinsic; facts->value = static_cast( variant == 0 ? Intrinsic::VectorCarrylessMultiply : Intrinsic::VectorPermuteHalves) | - (constant ? (selector.bits & 255U) << 8 : uint64_t(1) << 16); + (constant ? (selector.bits & 255U) << 8 : uint64_t(1) << 16) | (variant == 2 ? uint64_t(1) << 17 : 0); return facts; } @@ -1406,7 +1441,10 @@ ExprFacts* Analyzer::overflow_builtin(const syntax::CallExpr& expr, uint8_t vari // GCC's __builtin_add/sub/mul_overflow(a, b, r): a and b of integral // or unscoped enumeration type (bool too; both host compilers), promoted, // and r a pointer to a non-const integral object (no bool or - // enumeration); a bool. + // enumeration); a bool. The _p forms take an expression of the result + // type and evaluate it for effects only. + const bool predicate = variant >= 3; + uint32_t result_width = 0; if (expr.arguments.size != 3) error(expr.location, "wrong number of arguments to an overflow builtin"); for (uint32_t i = 0; i < 3; ++i) @@ -1417,6 +1455,19 @@ ExprFacts* Analyzer::overflow_builtin(const syntax::CallExpr& expr, uint8_t vari const Type* type = operand->type->unqualified; if (i == 2) { + if (predicate) + { + if (!IsIntegralType(type) || type->fundamental == FundamentalType::Bool) + error(expr.arguments[i]->location, "an overflow predicate's result type is no integer"); + if ((operand->flags & kBitField) != 0 && operand->entity != nullptr && + operand->entity->kind == EntityKind::Variable) + { + const DataMember* member = static_cast(operand->entity)->data_member; + if (member != nullptr && member->bit_field) + result_width = member->width; + } + continue; + } const Type* pointer = type->kind == TypeKind::Array ? types_.pointer(type->element) : type; const Type* result = pointer->kind == TypeKind::Pointer ? pointer->element : nullptr; if (result == nullptr || (result->cv & kConst) != 0 || !IsIntegralType(result->unqualified) || @@ -1432,7 +1483,9 @@ ExprFacts* Analyzer::overflow_builtin(const syntax::CallExpr& expr, uint8_t vari } ExprFacts* facts = new_facts(expr, types_.fundamental(FundamentalType::Bool), ValueCategory::PRValue); facts->flags |= kIntrinsic; - facts->value = static_cast(Intrinsic::AddOverflow) + variant; + facts->value = static_cast(Intrinsic::AddOverflow) + (predicate ? variant - 3 : variant); + if (predicate) + facts->value |= kOverflowPredicate | (static_cast(result_width) << kOverflowResultWidthShift); return facts; } diff --git a/dev/src/sema/analyzer_construction.cpp b/dev/src/sema/analyzer_construction.cpp index 94177ebf6c..b9df0ecc3f 100644 --- a/dev/src/sema/analyzer_construction.cpp +++ b/dev/src/sema/analyzer_construction.cpp @@ -1517,8 +1517,9 @@ FunctionEntity* Analyzer::initialize_object( { // 8.5: an object (or reference) of `type` from its initializer; the // constructor a class object runs is returned. - if (ClassEntity* entity = type->is_reference() || type->kind == TypeKind::Array ? nullptr : ObjectClass(type)) - return initialize_class(entity, type, init, scope, location); + if (!c_source_ && !type->is_reference() && type->kind != TypeKind::Array) + if (ClassEntity* entity = ObjectClass(type)) + return initialize_class(entity, type, init, scope, location); const syntax::Expr* single = nullptr; bool direct = false; switch (init.kind) diff --git a/dev/src/sema/analyzer_declarations.cpp b/dev/src/sema/analyzer_declarations.cpp index 2ba4386336..cebfb105e7 100644 --- a/dev/src/sema/analyzer_declarations.cpp +++ b/dev/src/sema/analyzer_declarations.cpp @@ -2097,6 +2097,8 @@ Binding* Analyzer::declare_function(const Specifiers& specifiers, const Declarat if (cxx20_) attach_function_constraint(function, info, befriending); const bool was_defined = function->defined; + if (c_source_ && where->kind == ScopeKind::Namespace && (specifiers.is_extern || !specifiers.is_inline)) + function->c_external_definition = true; function->is_inline = function->is_inline || specifiers.is_inline || specifiers.is_constexpr; function->defined = function->defined || definition || deleted; function->deleted = function->deleted || deleted; diff --git a/dev/src/sema/analyzer_expressions.cpp b/dev/src/sema/analyzer_expressions.cpp index 2dbd455513..056398375a 100644 --- a/dev/src/sema/analyzer_expressions.cpp +++ b/dev/src/sema/analyzer_expressions.cpp @@ -1029,6 +1029,24 @@ const Type* Analyzer::usual_arithmetic(const Type* a, const Type* b) return CommonType(types_, promoted(a), promoted(b)); } +static bool CAssignableRecord(const ClassEntity* record) +{ + if (!record->complete) + return false; + for (const DataMember* member = record->members; member != nullptr; member = member->next) + { + const Type* type = member->variable->type; + while (type->kind == TypeKind::Array) + type = type->element; + if ((type->cv & kConst) != 0) + return false; + if (const ClassEntity* nested = ClassOf(type)) + if (!CAssignableRecord(nested)) + return false; + } + return true; +} + bool Analyzer::modifiable_lvalue(const ExprFacts* facts) const { // 3.10p10. @@ -1039,6 +1057,9 @@ bool Analyzer::modifiable_lvalue(const ExprFacts* facts) const return false; if ((type->cv & kConst) != 0) return false; + if (c_source_) + if (const ClassEntity* record = ClassOf(type)) + return CAssignableRecord(record); return !IsVoid(type); } @@ -1841,9 +1862,9 @@ ExprFacts* Analyzer::assignment(const syntax::BinaryExpr& expr, Scope* scope) } if (typed(*expr.right, scope) == nullptr) return nullptr; - if (ExprFacts* overloaded = MayOverload(expr.left) || MayOverload(expr.right) ? binary_operator(expr, scope) - : nullptr) - return overloaded; + if (!c_source_ && (MayOverload(expr.left) || MayOverload(expr.right))) + if (ExprFacts* overloaded = binary_operator(expr, scope)) + return overloaded; if (failed()) return nullptr; // A class operand of a compound assignment may now stand for its @@ -1852,7 +1873,7 @@ ExprFacts* Analyzer::assignment(const syntax::BinaryExpr& expr, Scope* scope) // 13.5.3: a class object is assigned by an operator= member (its // implicit copy or move assignment operator at least, 12.8p18-p20). // An invalid assignment in a substitution is its failure (14.8.2p8). - if (expr.op == TokenKind::OP_ASS && left->type->unqualified->kind == TypeKind::Class) + if (!c_source_ && expr.op == TokenKind::OP_ASS && left->type->unqualified->kind == TypeKind::Class) { substitution_error(expr.location, "no viable assignment operator for the class object"); return nullptr; diff --git a/dev/src/sema/constant_expressions.cpp b/dev/src/sema/constant_expressions.cpp index dd4d0f2848..9d7e32b2a3 100644 --- a/dev/src/sema/constant_expressions.cpp +++ b/dev/src/sema/constant_expressions.cpp @@ -2187,17 +2187,32 @@ bool ConstantInterpreter::overflow_builtin(const syntax::CallExpr& expr, ConstVa // it. const Intrinsic which = static_cast(expr.facts->value & 0xff); ConstValue a, b, pointer; - if (!operand(*expr.arguments[0], a) || !operand(*expr.arguments[1], b) || !operand(*expr.arguments[2], pointer)) + const bool predicate = (expr.facts->value & kOverflowPredicate) != 0; + if (!operand(*expr.arguments[0], a) || !operand(*expr.arguments[1], b)) return false; + const Type* result_type = expr.arguments[2]->facts->type->unqualified; + if (predicate) + { + if (!discard(*expr.arguments[2])) + return false; + } + else + { + if (!operand(*expr.arguments[2], pointer)) + return false; + if (pointer.kind != ValueKind::Pointer || pointer.root == RootKind::Null) + return fail(expr.location, "an overflow builtin's result through a null pointer"); + result_type = pointer.type->unqualified->element; + } if (a.kind != ValueKind::Integer || b.kind != ValueKind::Integer) return false; - if (pointer.kind != ValueKind::Pointer || pointer.root == RootKind::Null) - return fail(expr.location, "an overflow builtin's result through a null pointer"); - const Type* result_type = pointer.type->unqualified->element; IntegralKind left_kind, right_kind, result_kind; if (!IntegralKindOf(a.type, left_kind) || !IntegralKindOf(b.type, right_kind) || !IntegralKindOf(result_type, result_kind)) return false; + const uint64_t width = expr.facts->value >> kOverflowResultWidthShift; + if (width != 0 && width < result_kind.bits) + result_kind.bits = static_cast(width); ExactInteger x = ExactOf(a, left_kind), y = ExactOf(b, right_kind); if (which == Intrinsic::SubOverflow) y.negative = !y.negative; @@ -2209,12 +2224,15 @@ bool ConstantInterpreter::overflow_builtin(const syntax::CallExpr& expr, ConstVa const bool zero = exact.low == 0 && exact.high == 0; const bool fits = exact.high == 0 && (!exact.negative || result_kind.is_signed || zero) && (limit == 0 || exact.low < limit || (exact.negative && result_kind.is_signed && exact.low == limit)); - const WideBits wrapped = exact.negative ? 0 - exact.low : exact.low; - const ConstValue stored = result_kind.bits > 64 - ? WideValue(result_type, wrapped) - : IntegerValue(result_type, ConvertIntegral(static_cast(wrapped), result_kind)); - if (!write(PlaceOf(pointer, result_type), stored, expr.location)) - return false; + if (!predicate) + { + const WideBits wrapped = exact.negative ? 0 - exact.low : exact.low; + const ConstValue stored = result_kind.bits > 64 + ? WideValue(result_type, wrapped) + : IntegerValue(result_type, ConvertIntegral(static_cast(wrapped), result_kind)); + if (!write(PlaceOf(pointer, result_type), stored, expr.location)) + return false; + } out = IntegerValue(analyzer_.types_.fundamental(FundamentalType::Bool), fits ? 0 : 1); return true; } diff --git a/dev/src/sema/expression_facts.h b/dev/src/sema/expression_facts.h index dfe58f422a..f3f0aa8940 100644 --- a/dev/src/sema/expression_facts.h +++ b/dev/src/sema/expression_facts.h @@ -285,6 +285,10 @@ enum : uint64_t kLiteralCallRaw = 4 }; +// Extra intrinsic facts for GNU checked arithmetic predicates. +constexpr uint64_t kOverflowPredicate = 1u << 8; +constexpr unsigned kOverflowResultWidthShift = 9; + struct ExprFacts { // 5p5, 5p6: never a reference type; glvalues keep their cv-qualifiers. diff --git a/dev/src/sema/function_records.h b/dev/src/sema/function_records.h index d5629b7de9..e9f0a80ea2 100644 --- a/dev/src/sema/function_records.h +++ b/dev/src/sema/function_records.h @@ -231,6 +231,7 @@ enum class Intrinsic : uint8_t // SSE2 lane shuffles: selector in bits 8-15; bit 16 denotes a // deferred selector; bit 17 selects the high half of eight word lanes. VectorShuffle, + VectorTernary, VectorCarrylessMultiply, VectorPermuteHalves, // __builtin_add/sub/mul_overflow(a, b, result): the infinitely precise @@ -435,6 +436,8 @@ struct FunctionEntity : Entity bool unanalyzed_body : 1; bool excluded_instantiation : 1; bool gnu_inline : 1; + // A C file-scope declaration with extern or without inline (6.7.4). + bool c_external_definition : 1; // GNU used: an object-emission root. bool used : 1; // [[noreturn]] or GNU noreturn on any declaration: its calls do not diff --git a/dev/src/sema/template_names.cpp b/dev/src/sema/template_names.cpp index fb1c3f3202..6a07e57db7 100644 --- a/dev/src/sema/template_names.cpp +++ b/dev/src/sema/template_names.cpp @@ -1130,7 +1130,7 @@ void Analyzer::declare_alias_template(const syntax::AliasDecl& decl, Scope* scop // it (14p5 for templates, 3.3.1p4). Specifiers specifiers; this->specifiers(decl.type->specifiers, scope, specifiers, false); - if (specifiers.type == nullptr || specifiers.type == auto_placeholder_) + if (specifiers.type == nullptr) error(decl.location, "alias-declaration without a type"); if (specifiers.declared != nullptr && specifiers.defines) error(decl.location, "a class or enumeration defined in an alias template"); @@ -1138,6 +1138,9 @@ void Analyzer::declare_alias_template(const syntax::AliasDecl& decl, Scope* scop filter_mode_alias(specifiers); const DeclaratorInfo info = declarator(decl.type->declarator, specifiers.type, scope, decl.location, specifiers.mode_specifiers.empty() ? nullptr : &specifiers, DeclaratorUse::TypeId); + if ((specifiers.type == auto_placeholder_ || specifiers.type == decltype_auto_placeholder_) && + holds_auto(info.type)) + error(decl.location, "alias-declaration without a type"); check_type_packs(info.type, decl.location); if (info.virt_suffix != nullptr || specifiers.is_virtual) error(decl.location, "a virt-specifier or virtual in an alias-declaration"); diff --git a/dev/src/support/tool_help_text.h b/dev/src/support/tool_help_text.h index b5e4dcc876..aafd224cc1 100644 --- a/dev/src/support/tool_help_text.h +++ b/dev/src/support/tool_help_text.h @@ -45,6 +45,7 @@ inline const char* cppgm_help_text() " -c compile only\n" " -o explicit output path\n" " -I / -I user include search path\n" + " -iquote quoted include search path\n" " -isystem system include search path\n" " -nostdinc no standard include search paths\n" " --gcc-install-dir= GCC installation that has the standard headers\n" diff --git a/dev/src/syntax/parser.h b/dev/src/syntax/parser.h index 880e16a2f2..f0223329dc 100644 --- a/dev/src/syntax/parser.h +++ b/dev/src/syntax/parser.h @@ -223,7 +223,7 @@ class Parser : public ParserState // ------------------------------------------------------- declarators Declarator* parse_declarator(DeclaratorMode mode); bool parse_declarator_into(DeclaratorMode mode, Declarator* declarator); - bool parse_ptr_operator(ListFrame& pointers); + bool parse_ptr_operator(ListFrame& pointers, Attribute** inline_attributes); bool parse_declarator_suffixes(DeclaratorMode mode, Declarator* declarator, bool named, Scope* member_of); ParameterClause* parse_parameter_clause(Scope* member_of, bool definite, bool type_only = false); ParameterDeclaration* parse_c_identifier_parameter(); diff --git a/dev/src/syntax/parser_declarators.cpp b/dev/src/syntax/parser_declarators.cpp index 3fb8a2e457..8ce94854fd 100644 --- a/dev/src/syntax/parser_declarators.cpp +++ b/dev/src/syntax/parser_declarators.cpp @@ -138,7 +138,7 @@ bool Parser::ptr_operator_ahead(uint32_t ahead) return false; } -bool Parser::parse_ptr_operator(ListFrame& pointers) +bool Parser::parse_ptr_operator(ListFrame& pointers, Attribute** inline_attributes) { if (c_source_ && (at(TokenKind::OP_AMP) || at(TokenKind::OP_LAND) || member_pointer_ahead(0))) return fail(); @@ -158,12 +158,31 @@ bool Parser::parse_ptr_operator(ListFrame& pointers) if (pointer.class_name == nullptr || !expect(TokenKind::OP_COLON2) || !expect(TokenKind::OP_STAR)) return false; } + // GNU function inline attributes can follow a return pointer's star. + const auto parse_attributes = [&]() { + if (inline_attributes == nullptr) + return skip_attributes(); + Attribute* attributes = nullptr; + if (!collect_attributes(attributes)) + return false; + while (attributes != nullptr) + { + Attribute* current = attributes; + attributes = current->next; + if (current->kind == AttributeKind::AlwaysInline || current->kind == AttributeKind::GnuInline) + { + current->next = *inline_attributes; + *inline_attributes = current; + } + } + return true; + }; if (pointer.kind == TokenKind::OP_STAR || pointer.kind == TokenKind::OP_COLON2 || pointer.kind == TokenKind::OP_XOR) { ListFrame cv(cvs_); for (;;) { - if (!skip_attributes()) + if (!parse_attributes()) return false; if (c_source_ && tok().is_identifier() && gnu_names_.kind(tok().identifier) == static_cast(GnuTrait::AddAtomic) + 1) @@ -187,7 +206,7 @@ bool Parser::parse_ptr_operator(ListFrame& pointers) } pointer.cv = cv.take(arena_); } - else if (!skip_attributes()) + else if (!parse_attributes()) { return false; } @@ -251,7 +270,8 @@ bool Parser::parse_declarator_into(DeclaratorMode mode, Declarator* declarator) ListFrame pointers(pointers_); while (ptr_operator_ahead(0)) { - if (!parse_ptr_operator(pointers)) + if (!parse_ptr_operator( + pointers, c_source_ && mode == DeclaratorMode::Named ? &declarator->attributes : nullptr)) return false; } declarator->pointers = pointers.take(arena_); diff --git a/pa17/tests/controls/200-trailing-return-function-pointer-alias.t b/pa17/tests/controls/200-trailing-return-function-pointer-alias.t new file mode 100644 index 0000000000..d9b351d5d8 --- /dev/null +++ b/pa17/tests/controls/200-trailing-return-function-pointer-alias.t @@ -0,0 +1,12 @@ +// expect exit 0 +using Callback = auto (*)(int) -> int; +template using TypedCallback = auto (*)(T) -> T; + +int plus_one(int n) { return n + 1; } +long twice(long n) { return 2 * n; } + +int main() { + Callback callback = plus_one; + TypedCallback typed_callback = twice; + return callback(6) != 7 || typed_callback(10) != 20; +} diff --git a/pa29/README.md b/pa29/README.md index 76fd06542b..5b37c43325 100644 --- a/pa29/README.md +++ b/pa29/README.md @@ -184,6 +184,9 @@ Use all incoming paths when deciding whether a shared block is cold. ### Module assembly Namespace asm uses the shared `assembly_global` boundary. +For a standalone native `.S` file, run the preprocessor before passing the +source to the same integrated module assembler. The driver also accepts +`-x assembler-with-cpp` to select that input language explicitly. Keep module invocations ordered and preserve their symbol/section state. Emit code, scalar data, pointer relocations, BSS, strings and alignment directly. Support `.text`, `.data`, `.bss`, `.rodata`, `.section`, the section stack and diff --git a/pa29/tests/source/100-gnu-asm-cpuid-forms.t b/pa29/tests/source/100-gnu-asm-cpuid-forms.t index 17d468f2f6..90400ce4f0 100644 --- a/pa29/tests/source/100-gnu-asm-cpuid-forms.t +++ b/pa29/tests/source/100-gnu-asm-cpuid-forms.t @@ -1 +1 @@ -int main(){unsigned a,b,c,d;asm volatile("cpuid" : "=a"(a),"=b"(b),"=c"(c),"=d"(d):"0"(0u),"2"(0u));if(!a||!b||!c||!d)return 1;unsigned e,f,g,h;asm volatile("cpuid" : [a]"=a"(e),[b]"=b"(f),[c]"=c"(g),[d]"=d"(h):"[a]"(0u),"[c]"(0u));return a!=e||b!=f||c!=g||d!=h;} +int main(){unsigned a,b,c,d;asm volatile("cpuid" : "=a"(a),"=b"(b),"=c"(c),"=d"(d):"0"(0u),"2"(0u));if(!a||!b||!c||!d)return 1;unsigned e,f,g,h;asm volatile("{cpuid|cpuid}" : [a]"=a"(e),[b]"=b"(f),[c]"=c"(g),[d]"=d"(h):"[a]"(0u),"[c]"(0u));return a!=e||b!=f||c!=g||d!=h;} diff --git a/pa29/tests/source/200-preprocessed-assembly.assembly-profile b/pa29/tests/source/200-preprocessed-assembly.assembly-profile new file mode 100644 index 0000000000..95464d2cf3 --- /dev/null +++ b/pa29/tests/source/200-preprocessed-assembly.assembly-profile @@ -0,0 +1 @@ +native-source diff --git a/pa29/tests/source/200-preprocessed-assembly.driver.cpp b/pa29/tests/source/200-preprocessed-assembly.driver.cpp new file mode 100644 index 0000000000..87e4032f0d --- /dev/null +++ b/pa29/tests/source/200-preprocessed-assembly.driver.cpp @@ -0,0 +1,2 @@ +extern "C" long assembly_add(long); +int main() { return assembly_add(35) != 42; } diff --git a/pa29/tests/source/200-preprocessed-assembly.t b/pa29/tests/source/200-preprocessed-assembly.t new file mode 100644 index 0000000000..1baa1d5e6d --- /dev/null +++ b/pa29/tests/source/200-preprocessed-assembly.t @@ -0,0 +1,22 @@ +#if !defined(__ASSEMBLER__) +#error assembler mode required +#endif + +#if defined(__APPLE__) +#define ENTRY _assembly_add +#else +#define ENTRY assembly_add +.section .note.GNU-stack,"",%progbits +#endif +#define ADD(delta) leaq delta(%rdi), %rax; retq + +.text +.globl ENTRY +#if !defined(__APPLE__) +.type ENTRY,@function +#endif +ENTRY: + ADD(7) +#if !defined(__APPLE__) +.size ENTRY, .-ENTRY +#endif diff --git a/pa30/README.md b/pa30/README.md index 3167c5de14..7e358c3451 100644 --- a/pa30/README.md +++ b/pa30/README.md @@ -402,6 +402,10 @@ To complete PA30, implement hosted compatibility for: `section`, `vector_size`, `mode`, `gnu_inline`, `abi_tag`, `may_alias`, `using_if_exists` and `exclude_from_explicit_instantiation`, each also spelled `__name__`) and `0` for any other. + Directories added with `-iquote` are searched for quoted includes after + the including file's directory and before `-I`. Angle-bracket lookups + start at the ordinary include chain. `#include_next` continues from the + directory that found the current header. PA37 adds the Wasm-specific import/export binding attributes and probes; native profiles continue to report no support for those target attributes. GNU `alias("object-name")` declares another name for a function or global diff --git a/pa30/tests/compile/500-gnu-always-inline-prefetch.ref b/pa30/tests/compile/500-gnu-always-inline-prefetch.ref new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa30/tests/compile/500-gnu-always-inline-prefetch.ref.exit_status b/pa30/tests/compile/500-gnu-always-inline-prefetch.ref.exit_status new file mode 100644 index 0000000000..c1d5c9342c --- /dev/null +++ b/pa30/tests/compile/500-gnu-always-inline-prefetch.ref.exit_status @@ -0,0 +1 @@ +EXIT_SUCCESS diff --git a/pa30/tests/compile/500-gnu-always-inline-prefetch.ref.stdout b/pa30/tests/compile/500-gnu-always-inline-prefetch.ref.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa30/tests/compile/500-gnu-always-inline-prefetch.t b/pa30/tests/compile/500-gnu-always-inline-prefetch.t new file mode 100644 index 0000000000..11b22dcc1b --- /dev/null +++ b/pa30/tests/compile/500-gnu-always-inline-prefetch.t @@ -0,0 +1,10 @@ +extern __inline__ void __attribute__((__gnu_inline__, __always_inline__)) +prefetch_hint(const void *address, int selector) +{ + __builtin_prefetch(address, (selector & 4) >> 2, selector & 3); +} + +void use_hint(const void *address) +{ + prefetch_hint(address, 3); +} diff --git a/pa30/tests/run/800-source-view-iquote.flags b/pa30/tests/run/800-source-view-iquote.flags new file mode 100644 index 0000000000..a8525c4017 --- /dev/null +++ b/pa30/tests/run/800-source-view-iquote.flags @@ -0,0 +1 @@ +-nostdinc -iquote tests/run/quote-first -iquotetests/run/quote-first -iquotetests/run/quote-second -Itests/run/quote-angle diff --git a/pa30/tests/run/800-source-view-iquote.ref.impl.exit_status b/pa30/tests/run/800-source-view-iquote.ref.impl.exit_status new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/pa30/tests/run/800-source-view-iquote.ref.impl.exit_status @@ -0,0 +1 @@ +0 diff --git a/pa30/tests/run/800-source-view-iquote.ref.program.exit_status b/pa30/tests/run/800-source-view-iquote.ref.program.exit_status new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/pa30/tests/run/800-source-view-iquote.ref.program.exit_status @@ -0,0 +1 @@ +0 diff --git a/pa30/tests/run/800-source-view-iquote.ref.program.stdout b/pa30/tests/run/800-source-view-iquote.ref.program.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa30/tests/run/800-source-view-iquote.t b/pa30/tests/run/800-source-view-iquote.t new file mode 100644 index 0000000000..7cd7f6238e --- /dev/null +++ b/pa30/tests/run/800-source-view-iquote.t @@ -0,0 +1,19 @@ +#if __has_include() || !__has_include("cppgm-quote-only.h") +#error -iquote must be visible only to quoted lookups +#endif + +#include "cppgm-quote-chain.h" +#ifndef CPPGM_FROM_SECOND_QUOTE +#error include_next must continue through the quote chain +#endif + +#undef CPPGM_FROM_FIRST_QUOTE +#undef CPPGM_FROM_SECOND_QUOTE +#undef CPPGM_FROM_ANGLE + +#include +#if defined(CPPGM_FROM_FIRST_QUOTE) || defined(CPPGM_FROM_SECOND_QUOTE) +#error angle-bracket lookup must bypass the quote directories +#endif + +int main() { return CPPGM_FROM_ANGLE != 37; } diff --git a/pa30/tests/run/800-source-view-iquote.t.1 b/pa30/tests/run/800-source-view-iquote.t.1 new file mode 100644 index 0000000000..80279445d9 --- /dev/null +++ b/pa30/tests/run/800-source-view-iquote.t.1 @@ -0,0 +1 @@ +#include "800-source-view-iquote.t" diff --git a/pa30/tests/run/quote-angle/cppgm-quote-chain.h b/pa30/tests/run/quote-angle/cppgm-quote-chain.h new file mode 100644 index 0000000000..e223345e94 --- /dev/null +++ b/pa30/tests/run/quote-angle/cppgm-quote-chain.h @@ -0,0 +1 @@ +#define CPPGM_FROM_ANGLE 37 diff --git a/pa30/tests/run/quote-first/cppgm-quote-chain.h b/pa30/tests/run/quote-first/cppgm-quote-chain.h new file mode 100644 index 0000000000..0504714028 --- /dev/null +++ b/pa30/tests/run/quote-first/cppgm-quote-chain.h @@ -0,0 +1,5 @@ +#ifdef CPPGM_FROM_FIRST_QUOTE +#error duplicate quote directory +#endif +#define CPPGM_FROM_FIRST_QUOTE 1 +#include_next diff --git a/pa30/tests/run/quote-first/cppgm-quote-only.h b/pa30/tests/run/quote-first/cppgm-quote-only.h new file mode 100644 index 0000000000..655f4dbc11 --- /dev/null +++ b/pa30/tests/run/quote-first/cppgm-quote-only.h @@ -0,0 +1 @@ +#define CPPGM_QUOTE_ONLY 1 diff --git a/pa30/tests/run/quote-second/cppgm-quote-chain.h b/pa30/tests/run/quote-second/cppgm-quote-chain.h new file mode 100644 index 0000000000..ac5535b194 --- /dev/null +++ b/pa30/tests/run/quote-second/cppgm-quote-chain.h @@ -0,0 +1,2 @@ +#define CPPGM_FROM_SECOND_QUOTE 1 +#include_next "cppgm-quote-chain.h" diff --git a/pa38/README.md b/pa38/README.md index a141845188..57ab32e12b 100644 --- a/pa38/README.md +++ b/pa38/README.md @@ -29,7 +29,9 @@ immediate object-pointer qualifiers and conditional character/string escapes such as `\%` (whose value is `%`), as hosted GNU C libraries require. This does not make differently qualified types compatible or allow unrelated pointer conversions, nested qualifier removal, or removal of atomic qualification. -Strict `-std=c17` retains its qualifier and escape diagnostics. The input language and target +Strict `-std=c17` retains its qualifier and escape diagnostics. The C input +profile also accepts `-std=c99` and `-std=gnu99`, with the C99 value of +`__STDC_VERSION__`. The input language and target are separate choices. `-x c++` continues to select C++; a language and standard that disagree must be diagnosed. The existing `.c` handling is unchanged unless C is selected explicitly. @@ -71,7 +73,11 @@ The first fixture set covers these parts of the C17 input profile: reuse a tag spelling for an unrelated type; struct and enum tags, typedefs, aggregate initialization, C member and array designators, member access, - function parameters and results, C object linkage and tentative definitions. + function parameters and results, compatible record copy and assignment, C object + linkage and tentative definitions. A C inline definition with + external linkage supplies the external symbol if a file-scope declaration + uses `extern` or leaves out `inline`. GNU `gnu_inline` and `always_inline` + attributes can also occur after the return type's pointer operator. - C compound literals of scalar, pointer, record and array types, including array-bound deduction and designators. Each occurrence denotes an lvalue; block-scope objects survive the full expression and file-scope objects have @@ -112,7 +118,7 @@ make ref-test ``` `tests/general/*.t` inputs produce LowIR and are compared with the checked-in -reference outputs. A `.c-standard` sidecar selects `c17` or `gnu17` for an +reference outputs. A `.c-standard` sidecar selects `c99`, `gnu99`, `c17` or `gnu17` for an individual fixture; controls use the same convention. Rejected inputs have the usual failure-status reference. An adjacent `.t.1` adds another translation unit, as in the earlier source assignments. `tests/controls/*.t` state an expected program result and run the diff --git a/pa38/tests/controls/100-gnu99-version.c-standard b/pa38/tests/controls/100-gnu99-version.c-standard new file mode 100644 index 0000000000..ec71f3eeda --- /dev/null +++ b/pa38/tests/controls/100-gnu99-version.c-standard @@ -0,0 +1 @@ +gnu99 diff --git a/pa38/tests/controls/100-gnu99-version.t b/pa38/tests/controls/100-gnu99-version.t new file mode 100644 index 0000000000..eb7f2bc73d --- /dev/null +++ b/pa38/tests/controls/100-gnu99-version.t @@ -0,0 +1,8 @@ +// expect exit 0 +#if __STDC__ != 1 || __STDC_VERSION__ != 199901L +#error wrong C99 language version +#endif +#ifdef __cplusplus +#error C++ language selected +#endif +int main(void) { return 0; } diff --git a/pa38/tests/controls/400-record-copy-with-volatile-subobjects.t b/pa38/tests/controls/400-record-copy-with-volatile-subobjects.t new file mode 100644 index 0000000000..8a31edd1c3 --- /dev/null +++ b/pa38/tests/controls/400-record-copy-with-volatile-subobjects.t @@ -0,0 +1,18 @@ +// expect exit 0 +struct Lock { + union { + int fields[10]; + volatile int shared[10]; + } storage; +}; + +int main(void) +{ + struct Lock before = { .storage.fields = {1, 2, 3, 4, 5} }; + const struct Lock saved = before; + struct Lock after = {0}; + before.storage.fields[2] = 17; + after = saved; + return after.storage.fields[2] != 3 || after.storage.fields[4] != 5 + || before.storage.fields[2] != 17; +} diff --git a/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.c-standard b/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.c-standard new file mode 100644 index 0000000000..f8ed9d0a7b --- /dev/null +++ b/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.c-standard @@ -0,0 +1 @@ +gnu17 diff --git a/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.t b/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.t new file mode 100644 index 0000000000..3965475fe5 --- /dev/null +++ b/pa38/tests/controls/500-gnu-inline-return-pointer-attributes.t @@ -0,0 +1,12 @@ +// expect exit 0 +extern inline int * __attribute__((__gnu_inline__, __always_inline__)) +identity(int *value) +{ + return value; +} + +int main(void) +{ + int value = 42; + return *identity(&value) != 42; +} diff --git a/pa38/tests/controls/500-gnu-wide-vector-compound-literal.c-standard b/pa38/tests/controls/500-gnu-wide-vector-compound-literal.c-standard new file mode 100644 index 0000000000..f8ed9d0a7b --- /dev/null +++ b/pa38/tests/controls/500-gnu-wide-vector-compound-literal.c-standard @@ -0,0 +1 @@ +gnu17 diff --git a/pa38/tests/controls/500-gnu-wide-vector-compound-literal.t b/pa38/tests/controls/500-gnu-wide-vector-compound-literal.t new file mode 100644 index 0000000000..f3e7fe5f94 --- /dev/null +++ b/pa38/tests/controls/500-gnu-wide-vector-compound-literal.t @@ -0,0 +1,16 @@ +// expect exit 0 +typedef int v8si __attribute__((vector_size(32))); +typedef int v16si __attribute__((vector_size(64))); + +int main(void) +{ + int next = 1; + v8si a = (v8si){next++, next++, 3, 4, 5, 6, 7, 8}; + v8si b = __builtin_ia32_pshufd256(a, 0x1b); + v16si c = (v16si){10, 20, 30, 40}; + v16si d = __builtin_ia32_pshufd512_mask(c, 0x1b, c, 5); + v16si e = __builtin_ia32_pternlogd512_mask(c, d, (v16si){3}, 0x96, 1); + return next != 3 || b[0] != 4 || b[3] != 1 || b[4] != 8 || b[7] != 5 + || d[0] != 40 || d[1] != 20 || d[2] != 20 || d[3] != 40 || d[15] != 0 + || e[0] != (10 ^ 40 ^ 3) || e[1] != 20; +} diff --git a/pa38/tests/controls/500-overflow-predicates.c-standard b/pa38/tests/controls/500-overflow-predicates.c-standard new file mode 100644 index 0000000000..f8ed9d0a7b --- /dev/null +++ b/pa38/tests/controls/500-overflow-predicates.c-standard @@ -0,0 +1 @@ +gnu17 diff --git a/pa38/tests/controls/500-overflow-predicates.t b/pa38/tests/controls/500-overflow-predicates.t new file mode 100644 index 0000000000..f083e4bfc4 --- /dev/null +++ b/pa38/tests/controls/500-overflow-predicates.t @@ -0,0 +1,17 @@ +// expect exit 0 +_Static_assert(__builtin_add_overflow_p(255, 1, (unsigned char)0), "narrow addition"); +_Static_assert(!__builtin_sub_overflow_p(0, 1, (signed char)0), "signed difference"); +_Static_assert(__builtin_mul_overflow_p(64, 2, (signed char)0), "narrow multiplication"); + +struct Field { unsigned int small : 3; }; +int main(void) +{ + struct Field field = { 1 }; + volatile int n = 4; + int effects = 0; + if (!__builtin_mul_overflow_p(n, 2, (effects++, (unsigned char)0)) && effects == 1 && + __builtin_mul_overflow_p(n, 2, field.small) && + !__builtin_mul_overflow_p(n, 1, field.small)) + return 0; + return 1; +} diff --git a/pa38/tests/general/400-c-inline-linkage.ref b/pa38/tests/general/400-c-inline-linkage.ref new file mode 100644 index 0000000000..4450999039 --- /dev/null +++ b/pa38/tests/general/400-c-inline-linkage.ref @@ -0,0 +1,126 @@ +function @declared_first(%n : i32) -> i32 [linkage=c, binding=strong, inline_hint=yes] { + slot $n : i32 + + block ^entry: + store typed i32 %n, $n + %t1 = load typed i32 $n + %t2 = binary add nowrap i32 %t1, 3 + return i32 %t2 +} +function @declared_last(%n : i32) -> i32 [linkage=c, binding=strong, inline_hint=yes] { + slot $n : i32 + + block ^entry: + store typed i32 %n, $n + %t1 = load typed i32 $n + %t2 = binary add nowrap i32 %t1, 5 + return i32 %t2 +} +function @declared_with_extern(%n : i32) -> i32 [linkage=c, binding=strong, inline_hint=yes] { + slot $n : i32 + + block ^entry: + store typed i32 %n, $n + %t1 = load typed i32 $n + %t2 = binary add nowrap i32 %t1, 7 + return i32 %t2 +} +function @inline_only(%n : i32) -> i32 [linkage=c, binding=strong] { + slot $n : i32 + + block ^entry: + store typed i32 %n, $n + %t1 = load typed i32 $n + %t2 = binary add nowrap i32 %t1, 9 + return i32 %t2 +} +function @main() -> i32 [role=entry, binding=strong, keep_alias=yes] { + slot $external_address : ptr + slot $lor__1 : i64 + slot $lor__2 : i64 + slot $lor__3 : i64 + slot $lor__4 : i64 + + block ^entry: + %t1 = addr @inline_only + store volatile ptr %t1, $external_address + %t2 = call i32 @declared_first(1) + %t3 = cmp ne i32 %t2, 4 + %t4 = convert trunc i32 i64 %t3 + branch %t4, ^lor_short_2, ^lor_rhs_1 + + block ^lor_rhs_1: + %t5 = call i32 @declared_last(1) + %t6 = cmp ne i32 %t5, 6 + %t7 = convert trunc i32 i64 %t6 + %t8 = cmp ne i32 %t7, 0 + store typed i64 %t8, $lor__1 + jump ^lor_end_3 + + block ^lor_short_2: + store typed i64 1, $lor__1 + jump ^lor_end_3 + + block ^lor_end_3: + %t9 = load typed i64 $lor__1 + branch %t9, ^lor_short_5, ^lor_rhs_4 + + block ^lor_rhs_4: + %t10 = call i32 @declared_with_extern(1) + %t11 = cmp ne i32 %t10, 8 + %t12 = convert trunc i32 i64 %t11 + %t13 = cmp ne i32 %t12, 0 + store typed i64 %t13, $lor__2 + jump ^lor_end_6 + + block ^lor_short_5: + store typed i64 1, $lor__2 + jump ^lor_end_6 + + block ^lor_end_6: + %t14 = load typed i64 $lor__2 + branch %t14, ^lor_short_8, ^lor_rhs_7 + + block ^lor_rhs_7: + %t15 = load volatile ptr $external_address + %t16 = call i32 %t15(1) as (%arg0 : i32) -> i32 + %t17 = cmp ne i32 %t16, 10 + %t18 = convert trunc i32 i64 %t17 + %t19 = cmp ne i32 %t18, 0 + store typed i64 %t19, $lor__3 + jump ^lor_end_9 + + block ^lor_short_8: + store typed i64 1, $lor__3 + jump ^lor_end_9 + + block ^lor_end_9: + %t20 = load typed i64 $lor__3 + branch %t20, ^lor_short_11, ^lor_rhs_10 + + block ^lor_rhs_10: + %t21 = call i32 @local_inline(1) + %t22 = cmp ne i32 %t21, 12 + %t23 = convert trunc i32 i64 %t22 + %t24 = cmp ne i32 %t23, 0 + store typed i64 %t24, $lor__4 + jump ^lor_end_12 + + block ^lor_short_11: + store typed i64 1, $lor__4 + jump ^lor_end_12 + + block ^lor_end_12: + %t25 = load typed i64 $lor__4 + %t26 = convert trunc i32 i64 %t25 + return i32 %t26 +} +function @local_inline(%n : i32) -> i32 [linkage=c, binding=internal, inline_hint=yes] { + slot $n : i32 + + block ^entry: + store typed i32 %n, $n + %t1 = load typed i32 $n + %t2 = binary add nowrap i32 %t1, 11 + return i32 %t2 +} diff --git a/pa38/tests/general/400-c-inline-linkage.ref.exit_status b/pa38/tests/general/400-c-inline-linkage.ref.exit_status new file mode 100644 index 0000000000..c1d5c9342c --- /dev/null +++ b/pa38/tests/general/400-c-inline-linkage.ref.exit_status @@ -0,0 +1 @@ +EXIT_SUCCESS diff --git a/pa38/tests/general/400-c-inline-linkage.ref.stdout b/pa38/tests/general/400-c-inline-linkage.ref.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa38/tests/general/400-c-inline-linkage.t b/pa38/tests/general/400-c-inline-linkage.t new file mode 100644 index 0000000000..50b69e6219 --- /dev/null +++ b/pa38/tests/general/400-c-inline-linkage.t @@ -0,0 +1,9 @@ +extern int declared_first(int); +inline int declared_first(int n) { return n + 3; } + +inline int declared_last(int n) { return n + 5; } +extern int declared_last(int); + +extern inline int declared_with_extern(int n) { return n + 7; } + +int inline_only(int n) { return n + 9; } diff --git a/pa38/tests/general/400-c-inline-linkage.t.1 b/pa38/tests/general/400-c-inline-linkage.t.1 new file mode 100644 index 0000000000..bf9621559e --- /dev/null +++ b/pa38/tests/general/400-c-inline-linkage.t.1 @@ -0,0 +1,14 @@ +int declared_first(int); +int declared_last(int); +int declared_with_extern(int); + +inline int inline_only(int n) { return n + 99; } +static inline int local_inline(int n) { return n + 11; } + +int main(void) +{ + int (*volatile external_address)(int) = inline_only; + return declared_first(1) != 4 || declared_last(1) != 6 || + declared_with_extern(1) != 8 || external_address(1) != 10 || + local_inline(1) != 12; +} diff --git a/pa38/tests/general/400-c-inline-linkage.wasm-expect b/pa38/tests/general/400-c-inline-linkage.wasm-expect new file mode 100644 index 0000000000..4000c4f674 --- /dev/null +++ b/pa38/tests/general/400-c-inline-linkage.wasm-expect @@ -0,0 +1 @@ +{"source":true,"wasi":true,"target":"wasm32-wasip1","flags":["-x","c","-std=c17"],"units":["400-c-inline-linkage.t.1"],"commands":[{"exit":0,"stdout":""}]} diff --git a/pa38/tests/general/500-compound-literals.ref b/pa38/tests/general/500-compound-literals.ref index a41eec0a8a..9b984ea694 100644 --- a/pa38/tests/general/500-compound-literals.ref +++ b/pa38/tests/general/500-compound-literals.ref @@ -17,10 +17,7 @@ global @scalar_copy : i32 [linkage=c, binding=internal] = zero global @__cppgm_ref_temporary__scalar_copy_0 [binding=internal, object=_ZGR11scalar_copy_] = { i32 23 } -global @record_copy : obj<8x4> [linkage=c, binding=internal] = { - zero 8 -} -global @__cppgm_ref_temporary__record_copy_0 [binding=internal, object=_ZGR11record_copy_] = { +global @record_copy [linkage=c, binding=internal] = { i32 17 i32 19 } @@ -419,8 +416,5 @@ function @__cppgm_init() -> void [role=init, binding=internal] { block ^entry: %t1 = load typed i32 @__cppgm_ref_temporary__scalar_copy_0 store typed i32 %t1, @scalar_copy - %t2 = addr @record_copy - %t3 = addr @__cppgm_ref_temporary__record_copy_0 - copyobj 8x4 %t3, %t2 return void } diff --git a/scripts/CppgmBatchWorker.pm b/scripts/CppgmBatchWorker.pm index 8a96ab7b56..f4554caaf2 100644 --- a/scripts/CppgmBatchWorker.pm +++ b/scripts/CppgmBatchWorker.pm @@ -446,7 +446,7 @@ sub standard_args_for my $path = $files[0]; my $is_c = $path =~ /\.c-standard$/; my @standards = read_word_list($path); - my $pattern = $is_c ? qr/\A(?:c|gnu)17\z/ : qr/\A(?:c|gnu)\+\+(?:11|14|17|20)\z/; + my $pattern = $is_c ? qr/\A(?:c|gnu)(?:99|17)\z/ : qr/\A(?:c|gnu)\+\+(?:11|14|17|20)\z/; my $language = $is_c ? 'C' : 'C++'; die "Expected one $language standard in $path\n" if @standards != 1 || $standards[0] !~ $pattern; diff --git a/scripts/check_inline_assembly.pl b/scripts/check_inline_assembly.pl index 2639860bbe..017a446092 100644 --- a/scripts/check_inline_assembly.pl +++ b/scripts/check_inline_assembly.pl @@ -128,7 +128,7 @@ sub observe @fixture_link = fixture_link_options($test); my $profile = read_file(profile_path($test)); $profile =~ s/\s+\z//; - die "$test: unknown assembly profile '$profile'\n" if $profile !~ /\A(?:(?:lowir|gnu)(?:-reject)?|gnu-native|gnu-compile|lowir-native(?:-reject)?)\z/; + die "$test: unknown assembly profile '$profile'\n" if $profile !~ /\A(?:(?:lowir|gnu)(?:-reject)?|gnu-native|gnu-compile|native-source|lowir-native(?:-reject)?)\z/; my $directory = File::Spec->rel2abs(tempdir('case-XXXXXX', DIR => $out, CLEANUP => 0)); if ($profile =~ /-reject\z/) { @@ -205,7 +205,8 @@ sub observe note_progress_state('compile', $test); my $label = "input-$index-$level"; my $object = "$directory/$label.o"; - command($directory, "$label.compile", $app, "-$level", '-c', $input, '-o', $object); + my @language = $profile eq 'native-source' ? ('-x', 'assembler-with-cpp') : (); + command($directory, "$label.compile", $app, "-$level", @language, '-c', $input, '-o', $object); push @observations, observe($directory, $label, $object, $driver); if ($profile =~ /\Agnu/) {