Index: vendor/clang/dist-release_80/include/clang/Basic/DiagnosticSemaKinds.td =================================================================== --- vendor/clang/dist-release_80/include/clang/Basic/DiagnosticSemaKinds.td (revision 343192) +++ vendor/clang/dist-release_80/include/clang/Basic/DiagnosticSemaKinds.td (revision 343193) @@ -1,9491 +1,9495 @@ //==--- DiagnosticSemaKinds.td - libsema diagnostics ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Semantic Analysis //===----------------------------------------------------------------------===// let Component = "Sema" in { let CategoryName = "Semantic Issue" in { def note_previous_decl : Note<"%0 declared here">; def note_entity_declared_at : Note<"%0 declared here">; def note_callee_decl : Note<"%0 declared here">; def note_defined_here : Note<"%0 defined here">; // For loop analysis def warn_variables_not_in_loop_body : Warning< "variable%select{s| %1|s %1 and %2|s %1, %2, and %3|s %1, %2, %3, and %4}0 " "used in loop condition not modified in loop body">, InGroup, DefaultIgnore; def warn_redundant_loop_iteration : Warning< "variable %0 is %select{decremented|incremented}1 both in the loop header " "and in the loop body">, InGroup, DefaultIgnore; def note_loop_iteration_here : Note<"%select{decremented|incremented}0 here">; def warn_duplicate_enum_values : Warning< "element %0 has been implicitly assigned %1 which another element has " "been assigned">, InGroup>, DefaultIgnore; def note_duplicate_element : Note<"element %0 also has value %1">; // Absolute value functions def warn_unsigned_abs : Warning< "taking the absolute value of unsigned type %0 has no effect">, InGroup; def note_remove_abs : Note< "remove the call to '%0' since unsigned values cannot be negative">; def warn_abs_too_small : Warning< "absolute value function %0 given an argument of type %1 but has parameter " "of type %2 which may cause truncation of value">, InGroup; def warn_wrong_absolute_value_type : Warning< "using %select{integer|floating point|complex}1 absolute value function %0 " "when argument is of %select{integer|floating point|complex}2 type">, InGroup; def note_replace_abs_function : Note<"use function '%0' instead">; def warn_pointer_abs : Warning< "taking the absolute value of %select{pointer|function|array}0 type %1 is suspicious">, InGroup; def warn_max_unsigned_zero : Warning< "taking the max of " "%select{a value and unsigned zero|unsigned zero and a value}0 " "is always equal to the other value">, InGroup; def note_remove_max_call : Note< "remove call to max function and unsigned zero argument">; def warn_infinite_recursive_function : Warning< "all paths through this function will call itself">, InGroup, DefaultIgnore; def warn_comma_operator : Warning<"possible misuse of comma operator here">, InGroup>, DefaultIgnore; def note_cast_to_void : Note<"cast expression to void to silence warning">; // Constant expressions def err_expr_not_ice : Error< "expression is not an %select{integer|integral}0 constant expression">; def ext_expr_not_ice : Extension< "expression is not an %select{integer|integral}0 constant expression; " "folding it to a constant is a GNU extension">, InGroup; def err_typecheck_converted_constant_expression : Error< "value of type %0 is not implicitly convertible to %1">; def err_typecheck_converted_constant_expression_disallowed : Error< "conversion from %0 to %1 is not allowed in a converted constant expression">; def err_typecheck_converted_constant_expression_indirect : Error< "conversion from %0 to %1 in converted constant expression would " "bind reference to a temporary">; def err_expr_not_cce : Error< "%select{case value|enumerator value|non-type template argument|" "array size|constexpr if condition}0 " "is not a constant expression">; def ext_cce_narrowing : ExtWarn< "%select{case value|enumerator value|non-type template argument|" "array size|constexpr if condition}0 " "%select{cannot be narrowed from type %2 to %3|" "evaluates to %2, which cannot be narrowed to type %3}1">, InGroup, DefaultError, SFINAEFailure; def err_ice_not_integral : Error< "integral constant expression must have integral or unscoped enumeration " "type, not %0">; def err_ice_incomplete_type : Error< "integral constant expression has incomplete class type %0">; def err_ice_explicit_conversion : Error< "integral constant expression requires explicit conversion from %0 to %1">; def note_ice_conversion_here : Note< "conversion to %select{integral|enumeration}0 type %1 declared here">; def err_ice_ambiguous_conversion : Error< "ambiguous conversion from type %0 to an integral or unscoped " "enumeration type">; def err_ice_too_large : Error< "integer constant expression evaluates to value %0 that cannot be " "represented in a %1-bit %select{signed|unsigned}2 integer type">; def err_expr_not_string_literal : Error<"expression is not a string literal">; // Semantic analysis of constant literals. def ext_predef_outside_function : Warning< "predefined identifier is only valid inside function">, InGroup>; def warn_float_overflow : Warning< "magnitude of floating-point constant too large for type %0; maximum is %1">, InGroup; def warn_float_underflow : Warning< "magnitude of floating-point constant too small for type %0; minimum is %1">, InGroup; def warn_double_const_requires_fp64 : Warning< "double precision constant requires cl_khr_fp64, casting to single precision">; def err_half_const_requires_fp16 : Error< "half precision constant requires cl_khr_fp16">; // C99 variable-length arrays def ext_vla : Extension<"variable length arrays are a C99 feature">, InGroup; def warn_vla_used : Warning<"variable length array used">, InGroup, DefaultIgnore; def err_vla_in_sfinae : Error< "variable length array cannot be formed during template argument deduction">; def err_array_star_in_function_definition : Error< "variable length array must be bound in function definition">; def err_vla_decl_in_file_scope : Error< "variable length array declaration not allowed at file scope">; def err_vla_decl_has_static_storage : Error< "variable length array declaration cannot have 'static' storage duration">; def err_vla_decl_has_extern_linkage : Error< "variable length array declaration cannot have 'extern' linkage">; def ext_vla_folded_to_constant : Extension< "variable length array folded to constant array as an extension">, InGroup; def err_vla_unsupported : Error< "variable length arrays are not supported for the current target">; def note_vla_unsupported : Note< "variable length arrays are not supported for the current target">; // C99 variably modified types def err_variably_modified_template_arg : Error< "variably modified type %0 cannot be used as a template argument">; def err_variably_modified_nontype_template_param : Error< "non-type template parameter of variably modified type %0">; def err_variably_modified_new_type : Error< "'new' cannot allocate object of variably modified type %0">; // C99 Designated Initializers def ext_designated_init : Extension< "designated initializers are a C99 feature">, InGroup; def err_array_designator_negative : Error< "array designator value '%0' is negative">; def err_array_designator_empty_range : Error< "array designator range [%0, %1] is empty">; def err_array_designator_non_array : Error< "array designator cannot initialize non-array type %0">; def err_array_designator_too_large : Error< "array designator index (%0) exceeds array bounds (%1)">; def err_field_designator_non_aggr : Error< "field designator cannot initialize a " "%select{non-struct, non-union|non-class}0 type %1">; def err_field_designator_unknown : Error< "field designator %0 does not refer to any field in type %1">; def err_field_designator_nonfield : Error< "field designator %0 does not refer to a non-static data member">; def note_field_designator_found : Note<"field designator refers here">; def err_designator_for_scalar_init : Error< "designator in initializer for scalar type %0">; def warn_subobject_initializer_overrides : Warning< "subobject initialization overrides initialization of other fields " "within its enclosing subobject">, InGroup; def warn_initializer_overrides : Warning< "initializer overrides prior initialization of this subobject">, InGroup; def note_previous_initializer : Note< "previous initialization %select{|with side effects }0is here" "%select{| (side effects may not occur at run time)}0">; def err_designator_into_flexible_array_member : Error< "designator into flexible array member subobject">; def note_flexible_array_member : Note< "initialized flexible array member %0 is here">; def ext_flexible_array_init : Extension< "flexible array initialization is a GNU extension">, InGroup; // Declarations. def ext_plain_complex : ExtWarn< "plain '_Complex' requires a type specifier; assuming '_Complex double'">; def ext_imaginary_constant : Extension< "imaginary constants are a GNU extension">, InGroup; def ext_integer_complex : Extension< "complex integer types are a GNU extension">, InGroup; def err_invalid_saturation_spec : Error<"'_Sat' specifier is only valid on " "'_Fract' or '_Accum', not '%0'">; def err_invalid_sign_spec : Error<"'%0' cannot be signed or unsigned">; def err_invalid_width_spec : Error< "'%select{|short|long|long long}0 %1' is invalid">; def err_invalid_complex_spec : Error<"'_Complex %0' is invalid">; def ext_auto_type_specifier : ExtWarn< "'auto' type specifier is a C++11 extension">, InGroup; def warn_auto_storage_class : Warning< "'auto' storage class specifier is redundant and incompatible with C++11">, InGroup, DefaultIgnore; def warn_deprecated_register : Warning< "'register' storage class specifier is deprecated " "and incompatible with C++17">, InGroup; def ext_register_storage_class : ExtWarn< "ISO C++17 does not allow 'register' storage class specifier">, DefaultError, InGroup; def err_invalid_decl_spec_combination : Error< "cannot combine with previous '%0' declaration specifier">; def err_invalid_vector_decl_spec_combination : Error< "cannot combine with previous '%0' declaration specifier. " "'__vector' must be first">; def err_invalid_pixel_decl_spec_combination : Error< "'__pixel' must be preceded by '__vector'. " "'%0' declaration specifier not allowed here">; def err_invalid_vector_bool_decl_spec : Error< "cannot use '%0' with '__vector bool'">; def err_invalid_vector_long_decl_spec : Error< "cannot use 'long' with '__vector'">; def err_invalid_vector_float_decl_spec : Error< "cannot use 'float' with '__vector'">; def err_invalid_vector_double_decl_spec : Error < "use of 'double' with '__vector' requires VSX support to be enabled " "(available on POWER7 or later)">; def err_invalid_vector_long_long_decl_spec : Error < "use of 'long long' with '__vector bool' requires VSX support (available on " "POWER7 or later) or extended Altivec support (available on POWER8 or later) " "to be enabled">; def err_invalid_vector_long_double_decl_spec : Error< "cannot use 'long double' with '__vector'">; def warn_vector_long_decl_spec_combination : Warning< "Use of 'long' with '__vector' is deprecated">, InGroup; def err_redeclaration_different_type : Error< "redeclaration of %0 with a different type%diff{: $ vs $|}1,2">; def err_bad_variable_name : Error< "%0 cannot be the name of a variable or data member">; def err_bad_parameter_name : Error< "%0 cannot be the name of a parameter">; def err_parameter_name_omitted : Error<"parameter name omitted">; def err_anyx86_interrupt_attribute : Error< "%select{x86|x86-64}0 'interrupt' attribute only applies to functions that " "have %select{a 'void' return type|" "only a pointer parameter optionally followed by an integer parameter|" "a pointer as the first parameter|a %2 type as the second parameter}1">; def err_anyx86_interrupt_called : Error< "interrupt service routine cannot be called directly">; def warn_arm_interrupt_calling_convention : Warning< "call to function without interrupt attribute could clobber interruptee's VFP registers">, InGroup; def warn_mips_interrupt_attribute : Warning< "MIPS 'interrupt' attribute only applies to functions that have " "%select{no parameters|a 'void' return type}0">, InGroup; def warn_riscv_repeated_interrupt_attribute : Warning< "repeated RISC-V 'interrupt' attribute">, InGroup; def note_riscv_repeated_interrupt_attribute : Note< "repeated RISC-V 'interrupt' attribute is here">; def warn_riscv_interrupt_attribute : Warning< "RISC-V 'interrupt' attribute only applies to functions that have " "%select{no parameters|a 'void' return type}0">, InGroup; +def warn_msp430_interrupt_attribute : Warning< + "MSP430 'interrupt' attribute only applies to functions that have " + "%select{no parameters|a 'void' return type}0">, + InGroup; def warn_unused_parameter : Warning<"unused parameter %0">, InGroup, DefaultIgnore; def warn_unused_variable : Warning<"unused variable %0">, InGroup, DefaultIgnore; def warn_unused_local_typedef : Warning< "unused %select{typedef|type alias}0 %1">, InGroup, DefaultIgnore; def warn_unused_property_backing_ivar : Warning<"ivar %0 which backs the property is not " "referenced in this property's accessor">, InGroup, DefaultIgnore; def warn_unused_const_variable : Warning<"unused variable %0">, InGroup, DefaultIgnore; def warn_unused_exception_param : Warning<"unused exception parameter %0">, InGroup, DefaultIgnore; def warn_decl_in_param_list : Warning< "declaration of %0 will not be visible outside of this function">, InGroup; def warn_redefinition_in_param_list : Warning< "redefinition of %0 will not be visible outside of this function">, InGroup; def warn_empty_parens_are_function_decl : Warning< "empty parentheses interpreted as a function declaration">, InGroup; def warn_parens_disambiguated_as_function_declaration : Warning< "parentheses were disambiguated as a function declaration">, InGroup; def warn_parens_disambiguated_as_variable_declaration : Warning< "parentheses were disambiguated as redundant parentheses around declaration " "of variable named %0">, InGroup; def warn_redundant_parens_around_declarator : Warning< "redundant parentheses surrounding declarator">, InGroup>, DefaultIgnore; def note_additional_parens_for_variable_declaration : Note< "add a pair of parentheses to declare a variable">; def note_raii_guard_add_name : Note< "add a variable name to declare a %0 initialized with %1">; def note_function_style_cast_add_parentheses : Note< "add enclosing parentheses to perform a function-style cast">; def note_remove_parens_for_variable_declaration : Note< "remove parentheses to silence this warning">; def note_empty_parens_function_call : Note< "change this ',' to a ';' to call %0">; def note_empty_parens_default_ctor : Note< "remove parentheses to declare a variable">; def note_empty_parens_zero_initialize : Note< "replace parentheses with an initializer to declare a variable">; def warn_unused_function : Warning<"unused function %0">, InGroup, DefaultIgnore; def warn_unused_template : Warning<"unused %select{function|variable}0 template %1">, InGroup, DefaultIgnore; def warn_unused_member_function : Warning<"unused member function %0">, InGroup, DefaultIgnore; def warn_used_but_marked_unused: Warning<"%0 was marked unused but was used">, InGroup, DefaultIgnore; def warn_unneeded_internal_decl : Warning< "%select{function|variable}0 %1 is not needed and will not be emitted">, InGroup, DefaultIgnore; def warn_unneeded_static_internal_decl : Warning< "'static' function %0 declared in header file " "should be declared 'static inline'">, InGroup, DefaultIgnore; def warn_unneeded_member_function : Warning< "member function %0 is not needed and will not be emitted">, InGroup, DefaultIgnore; def warn_unused_private_field: Warning<"private field %0 is not used">, InGroup, DefaultIgnore; def warn_unused_lambda_capture: Warning<"lambda capture %0 is not " "%select{used|required to be captured for this use}1">, InGroup, DefaultIgnore; def warn_parameter_size: Warning< "%0 is a large (%1 bytes) pass-by-value argument; " "pass it by reference instead ?">, InGroup; def warn_return_value_size: Warning< "return value of %0 is a large (%1 bytes) pass-by-value object; " "pass it by reference instead ?">, InGroup; def warn_return_value_udt: Warning< "%0 has C-linkage specified, but returns user-defined type %1 which is " "incompatible with C">, InGroup; def warn_return_value_udt_incomplete: Warning< "%0 has C-linkage specified, but returns incomplete type %1 which could be " "incompatible with C">, InGroup; def warn_implicit_function_decl : Warning< "implicit declaration of function %0">, InGroup, DefaultIgnore; def ext_implicit_function_decl : ExtWarn< "implicit declaration of function %0 is invalid in C99">, InGroup; def note_function_suggestion : Note<"did you mean %0?">; def err_ellipsis_first_param : Error< "ISO C requires a named parameter before '...'">; def err_declarator_need_ident : Error<"declarator requires an identifier">; def err_language_linkage_spec_unknown : Error<"unknown linkage language">; def err_language_linkage_spec_not_ascii : Error< "string literal in language linkage specifier cannot have an " "encoding-prefix">; def ext_use_out_of_scope_declaration : ExtWarn< "use of out-of-scope declaration of %0%select{| whose type is not " "compatible with that of an implicit declaration}1">, InGroup>; def err_inline_non_function : Error< "'inline' can only appear on functions%select{| and non-local variables}0">; def err_noreturn_non_function : Error< "'_Noreturn' can only appear on functions">; def warn_qual_return_type : Warning< "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">, InGroup, DefaultIgnore; def warn_deprecated_redundant_constexpr_static_def : Warning< "out-of-line definition of constexpr static data member is redundant " "in C++17 and is deprecated">, InGroup, DefaultIgnore; def warn_decl_shadow : Warning<"declaration shadows a %select{" "local variable|" "variable in %2|" "static data member of %2|" "field of %2|" "typedef in %2|" "type alias in %2}1">, InGroup, DefaultIgnore; def warn_decl_shadow_uncaptured_local : Warning, InGroup, DefaultIgnore; def warn_ctor_parm_shadows_field: Warning<"constructor parameter %0 shadows the field %1 of %2">, InGroup, DefaultIgnore; def warn_modifying_shadowing_decl : Warning<"modifying constructor parameter %0 that shadows a " "field of %1">, InGroup, DefaultIgnore; // C++ decomposition declarations def err_decomp_decl_context : Error< "decomposition declaration not permitted in this context">; def warn_cxx14_compat_decomp_decl : Warning< "decomposition declarations are incompatible with " "C++ standards before C++17">, DefaultIgnore, InGroup; def ext_decomp_decl : ExtWarn< "decomposition declarations are a C++17 extension">, InGroup; def ext_decomp_decl_cond : ExtWarn< "ISO C++17 does not permit structured binding declaration in a condition">, InGroup>; def err_decomp_decl_spec : Error< "decomposition declaration cannot be declared " "%plural{1:'%1'|:with '%1' specifiers}0">; def err_decomp_decl_type : Error< "decomposition declaration cannot be declared with type %0; " "declared type must be 'auto' or reference to 'auto'">; def err_decomp_decl_parens : Error< "decomposition declaration cannot be declared with parentheses">; def err_decomp_decl_template : Error< "decomposition declaration template not supported">; def err_decomp_decl_not_alone : Error< "decomposition declaration must be the only declaration in its group">; def err_decomp_decl_requires_init : Error< "decomposition declaration %0 requires an initializer">; def err_decomp_decl_wrong_number_bindings : Error< "type %0 decomposes into %2 elements, but %select{only |}3%1 " "names were provided">; def err_decomp_decl_unbindable_type : Error< "cannot decompose %select{union|non-class, non-array}1 type %2">; def err_decomp_decl_multiple_bases_with_members : Error< "cannot decompose class type %1: " "%select{its base classes %2 and|both it and its base class}0 %3 " "have non-static data members">; def err_decomp_decl_ambiguous_base : Error< "cannot decompose members of ambiguous base class %1 of %0:%2">; def err_decomp_decl_inaccessible_base : Error< "cannot decompose members of inaccessible base class %1 of %0">, AccessControl; def err_decomp_decl_inaccessible_field : Error< "cannot decompose %select{private|protected}0 member %1 of %3">, AccessControl; def err_decomp_decl_anon_union_member : Error< "cannot decompose class type %0 because it has an anonymous " "%select{struct|union}1 member">; def err_decomp_decl_std_tuple_element_not_specialized : Error< "cannot decompose this type; 'std::tuple_element<%0>::type' " "does not name a type">; def err_decomp_decl_std_tuple_size_not_constant : Error< "cannot decompose this type; 'std::tuple_size<%0>::value' " "is not a valid integral constant expression">; def note_in_binding_decl_init : Note< "in implicit initialization of binding declaration %0">; def err_std_type_trait_not_class_template : Error< "unsupported standard library implementation: " "'std::%0' is not a class template">; // C++ using declarations def err_using_requires_qualname : Error< "using declaration requires a qualified name">; def err_using_typename_non_type : Error< "'typename' keyword used on a non-type">; def err_using_dependent_value_is_type : Error< "dependent using declaration resolved to type without 'typename'">; def err_using_decl_nested_name_specifier_is_not_class : Error< "using declaration in class refers into '%0', which is not a class">; def err_using_decl_nested_name_specifier_is_current_class : Error< "using declaration refers to its own class">; def err_using_decl_nested_name_specifier_is_not_base_class : Error< "using declaration refers into '%0', which is not a base class of %1">; def err_using_decl_constructor_not_in_direct_base : Error< "%0 is not a direct base of %1, cannot inherit constructors">; def err_using_decl_can_not_refer_to_class_member : Error< "using declaration cannot refer to class member">; def err_ambiguous_inherited_constructor : Error< "constructor of %0 inherited from multiple base class subobjects">; def note_ambiguous_inherited_constructor_using : Note< "inherited from base class %0 here">; def note_using_decl_class_member_workaround : Note< "use %select{an alias declaration|a typedef declaration|a reference|" "a const variable|a constexpr variable}0 instead">; def err_using_decl_can_not_refer_to_namespace : Error< "using declaration cannot refer to a namespace">; def err_using_decl_can_not_refer_to_scoped_enum : Error< "using declaration cannot refer to a scoped enumerator">; def err_using_decl_constructor : Error< "using declaration cannot refer to a constructor">; def warn_cxx98_compat_using_decl_constructor : Warning< "inheriting constructors are incompatible with C++98">, InGroup, DefaultIgnore; def err_using_decl_destructor : Error< "using declaration cannot refer to a destructor">; def err_using_decl_template_id : Error< "using declaration cannot refer to a template specialization">; def note_using_decl_target : Note<"target of using declaration">; def note_using_decl_conflict : Note<"conflicting declaration">; def err_using_decl_redeclaration : Error<"redeclaration of using declaration">; def err_using_decl_conflict : Error< "target of using declaration conflicts with declaration already in scope">; def err_using_decl_conflict_reverse : Error< "declaration conflicts with target of using declaration already in scope">; def note_using_decl : Note<"%select{|previous }0using declaration">; def err_using_decl_redeclaration_expansion : Error< "using declaration pack expansion at block scope produces multiple values">; def warn_access_decl_deprecated : Warning< "access declarations are deprecated; use using declarations instead">, InGroup; def err_access_decl : Error< "ISO C++11 does not allow access declarations; " "use using declarations instead">; def warn_deprecated_copy_operation : Warning< "definition of implicit copy %select{constructor|assignment operator}1 " "for %0 is deprecated because it has a user-declared " "%select{copy %select{assignment operator|constructor}1|destructor}2">, InGroup, DefaultIgnore; def warn_cxx17_compat_exception_spec_in_signature : Warning< "mangled name of %0 will change in C++17 due to non-throwing exception " "specification in function signature">, InGroup; def warn_global_constructor : Warning< "declaration requires a global constructor">, InGroup, DefaultIgnore; def warn_global_destructor : Warning< "declaration requires a global destructor">, InGroup, DefaultIgnore; def warn_exit_time_destructor : Warning< "declaration requires an exit-time destructor">, InGroup, DefaultIgnore; def err_invalid_thread : Error< "'%0' is only allowed on variable declarations">; def err_thread_non_global : Error< "'%0' variables must have global storage">; def err_thread_unsupported : Error< "thread-local storage is not supported for the current target">; def warn_maybe_falloff_nonvoid_function : Warning< "control may reach end of non-void function">, InGroup; def warn_falloff_nonvoid_function : Warning< "control reaches end of non-void function">, InGroup; def err_maybe_falloff_nonvoid_block : Error< "control may reach end of non-void block">; def err_falloff_nonvoid_block : Error< "control reaches end of non-void block">; def warn_maybe_falloff_nonvoid_coroutine : Warning< "control may reach end of coroutine; which is undefined behavior because the promise type %0 does not declare 'return_void()'">, InGroup; def warn_falloff_nonvoid_coroutine : Warning< "control reaches end of coroutine; which is undefined behavior because the promise type %0 does not declare 'return_void()'">, InGroup; def warn_suggest_noreturn_function : Warning< "%select{function|method}0 %1 could be declared with attribute 'noreturn'">, InGroup, DefaultIgnore; def warn_suggest_noreturn_block : Warning< "block could be declared with attribute 'noreturn'">, InGroup, DefaultIgnore; // Unreachable code. def warn_unreachable : Warning< "code will never be executed">, InGroup, DefaultIgnore; def warn_unreachable_break : Warning< "'break' will never be executed">, InGroup, DefaultIgnore; def warn_unreachable_return : Warning< "'return' will never be executed">, InGroup, DefaultIgnore; def warn_unreachable_loop_increment : Warning< "loop will run at most once (loop increment never executed)">, InGroup, DefaultIgnore; def note_unreachable_silence : Note< "silence by adding parentheses to mark code as explicitly dead">; /// Built-in functions. def ext_implicit_lib_function_decl : ExtWarn< "implicitly declaring library function '%0' with type %1">, InGroup; def note_include_header_or_declare : Note< "include the header <%0> or explicitly provide a declaration for '%1'">; def note_previous_builtin_declaration : Note<"%0 is a builtin with type %1">; def warn_implicit_decl_requires_sysheader : Warning< "declaration of built-in function '%1' requires inclusion of the header <%0>">, InGroup; def warn_redecl_library_builtin : Warning< "incompatible redeclaration of library function %0">, InGroup>; def err_builtin_definition : Error<"definition of builtin function %0">; def err_builtin_redeclare : Error<"cannot redeclare builtin function %0">; def err_arm_invalid_specialreg : Error<"invalid special register for builtin">; def err_invalid_cpu_supports : Error<"invalid cpu feature string for builtin">; def err_invalid_cpu_is : Error<"invalid cpu name for builtin">; def err_invalid_cpu_specific_dispatch_value : Error< "invalid option '%0' for %select{cpu_specific|cpu_dispatch}1">; def warn_builtin_unknown : Warning<"use of unknown builtin %0">, InGroup, DefaultError; def warn_cstruct_memaccess : Warning< "%select{destination for|source of|first operand of|second operand of}0 this " "%1 call is a pointer to record %2 that is not trivial to " "%select{primitive-default-initialize|primitive-copy}3">, InGroup; def note_nontrivial_field : Note< "field is non-trivial to %select{copy|default-initialize}0">; def warn_dyn_class_memaccess : Warning< "%select{destination for|source of|first operand of|second operand of}0 this " "%1 call is a pointer to %select{|class containing a }2dynamic class %3; " "vtable pointer will be %select{overwritten|copied|moved|compared}4">, InGroup; def note_bad_memaccess_silence : Note< "explicitly cast the pointer to silence this warning">; def warn_sizeof_pointer_expr_memaccess : Warning< "'%0' call operates on objects of type %1 while the size is based on a " "different type %2">, InGroup; def warn_sizeof_pointer_expr_memaccess_note : Note< "did you mean to %select{dereference the argument to 'sizeof' (and multiply " "it by the number of elements)|remove the addressof in the argument to " "'sizeof' (and multiply it by the number of elements)|provide an explicit " "length}0?">; def warn_sizeof_pointer_type_memaccess : Warning< "argument to 'sizeof' in %0 call is the same pointer type %1 as the " "%select{destination|source}2; expected %3 or an explicit length">, InGroup; def warn_strlcpycat_wrong_size : Warning< "size argument in %0 call appears to be size of the source; " "expected the size of the destination">, InGroup>; def note_strlcpycat_wrong_size : Note< "change size argument to be the size of the destination">; def warn_memsize_comparison : Warning< "size argument in %0 call is a comparison">, InGroup>; def note_memsize_comparison_paren : Note< "did you mean to compare the result of %0 instead?">; def note_memsize_comparison_cast_silence : Note< "explicitly cast the argument to size_t to silence this warning">; def warn_suspicious_sizeof_memset : Warning< "%select{'size' argument to memset is '0'|" "setting buffer to a 'sizeof' expression}0" "; did you mean to transpose the last two arguments?">, InGroup; def note_suspicious_sizeof_memset_silence : Note< "%select{parenthesize the third argument|" "cast the second argument to 'int'}0 to silence">; def warn_suspicious_bzero_size : Warning<"'size' argument to bzero is '0'">, InGroup; def note_suspicious_bzero_size_silence : Note< "parenthesize the second argument to silence">; def warn_strncat_large_size : Warning< "the value of the size argument in 'strncat' is too large, might lead to a " "buffer overflow">, InGroup; def warn_strncat_src_size : Warning<"size argument in 'strncat' call appears " "to be size of the source">, InGroup; def warn_strncat_wrong_size : Warning< "the value of the size argument to 'strncat' is wrong">, InGroup; def note_strncat_wrong_size : Note< "change the argument to be the free space in the destination buffer minus " "the terminating null byte">; def warn_assume_side_effects : Warning< "the argument to %0 has side effects that will be discarded">, InGroup>; def warn_memcpy_chk_overflow : Warning< "'%0' will always overflow; destination buffer has size %1," " but size argument is %2">, InGroup>; /// main() // static main() is not an error in C, just in C++. def warn_static_main : Warning<"'main' should not be declared static">, InGroup
; def err_static_main : Error<"'main' is not allowed to be declared static">; def err_inline_main : Error<"'main' is not allowed to be declared inline">; def ext_variadic_main : ExtWarn< "'main' is not allowed to be declared variadic">, InGroup
; def ext_noreturn_main : ExtWarn< "'main' is not allowed to be declared _Noreturn">, InGroup
; def note_main_remove_noreturn : Note<"remove '_Noreturn'">; def err_constexpr_main : Error< "'main' is not allowed to be declared constexpr">; def err_deleted_main : Error<"'main' is not allowed to be deleted">; def err_mainlike_template_decl : Error<"%0 cannot be a template">; def err_main_returns_nonint : Error<"'main' must return 'int'">; def ext_main_returns_nonint : ExtWarn<"return type of 'main' is not 'int'">, InGroup; def note_main_change_return_type : Note<"change return type to 'int'">; def err_main_surplus_args : Error<"too many parameters (%0) for 'main': " "must be 0, 2, or 3">; def warn_main_one_arg : Warning<"only one parameter on 'main' declaration">, InGroup
; def err_main_arg_wrong : Error<"%select{first|second|third|fourth}0 " "parameter of 'main' (%select{argument count|argument array|environment|" "platform-specific data}0) must be of type %1">; def warn_main_returns_bool_literal : Warning<"bool literal returned from " "'main'">, InGroup
; def err_main_global_variable : Error<"main cannot be declared as global variable">; def warn_main_redefined : Warning<"variable named 'main' with external linkage " "has undefined behavior">, InGroup
; def ext_main_used : Extension< "ISO C++ does not allow 'main' to be used by a program">, InGroup
; /// parser diagnostics def ext_no_declarators : ExtWarn<"declaration does not declare anything">, InGroup; def ext_typedef_without_a_name : ExtWarn<"typedef requires a name">, InGroup; def err_typedef_not_identifier : Error<"typedef name must be an identifier">; def err_typedef_changes_linkage : Error<"unsupported: typedef changes linkage" " of anonymous type, but linkage was already computed">; def note_typedef_changes_linkage : Note<"use a tag name here to establish " "linkage prior to definition">; def err_statically_allocated_object : Error< "interface type cannot be statically allocated">; def err_object_cannot_be_passed_returned_by_value : Error< "interface type %1 cannot be %select{returned|passed}0 by value" "; did you forget * in %1?">; def err_parameters_retval_cannot_have_fp16_type : Error< "%select{parameters|function return value}0 cannot have __fp16 type; did you forget * ?">; def err_opencl_half_load_store : Error< "%select{loading directly from|assigning directly to}0 pointer to type %1 requires " "cl_khr_fp16. Use vector data %select{load|store}0 builtin functions instead">; def err_opencl_cast_to_half : Error<"casting to type %0 is not allowed">; def err_opencl_half_declaration : Error< "declaring variable of type %0 is not allowed">; def err_opencl_half_param : Error< "declaring function parameter of type %0 is not allowed; did you forget * ?">; def err_opencl_invalid_return : Error< "declaring function return value of type %0 is not allowed %select{; did you forget * ?|}1">; def warn_enum_value_overflow : Warning<"overflow in enumeration value">; def warn_pragma_options_align_reset_failed : Warning< "#pragma options align=reset failed: %0">, InGroup; def err_pragma_options_align_mac68k_target_unsupported : Error< "mac68k alignment pragma is not supported on this target">; def warn_pragma_pack_invalid_alignment : Warning< "expected #pragma pack parameter to be '1', '2', '4', '8', or '16'">, InGroup; def warn_pragma_pack_non_default_at_include : Warning< "non-default #pragma pack value changes the alignment of struct or union " "members in the included file">, InGroup, DefaultIgnore; def warn_pragma_pack_modified_after_include : Warning< "the current #pragma pack alignment value is modified in the included " "file">, InGroup; def warn_pragma_pack_no_pop_eof : Warning<"unterminated " "'#pragma pack (push, ...)' at end of file">, InGroup; def note_pragma_pack_here : Note< "previous '#pragma pack' directive that modifies alignment is here">; def note_pragma_pack_pop_instead_reset : Note< "did you intend to use '#pragma pack (pop)' instead of '#pragma pack()'?">; // Follow the Microsoft implementation. def warn_pragma_pack_show : Warning<"value of #pragma pack(show) == %0">; def warn_pragma_pack_pop_identifier_and_alignment : Warning< "specifying both a name and alignment to 'pop' is undefined">; def warn_pragma_pop_failed : Warning<"#pragma %0(pop, ...) failed: %1">, InGroup; def warn_cxx_ms_struct : Warning<"ms_struct may not produce Microsoft-compatible layouts for classes " "with base classes or virtual functions">, DefaultError, InGroup; def err_section_conflict : Error<"%0 causes a section type conflict with %1">; def err_no_base_classes : Error<"invalid use of '__super', %0 has no base classes">; def err_invalid_super_scope : Error<"invalid use of '__super', " "this keyword can only be used inside class or member function scope">; def err_super_in_lambda_unsupported : Error< "use of '__super' inside a lambda is unsupported">; def warn_pragma_unused_undeclared_var : Warning< "undeclared variable %0 used as an argument for '#pragma unused'">, InGroup; def warn_atl_uuid_deprecated : Warning< "specifying 'uuid' as an ATL attribute is deprecated; use __declspec instead">, InGroup; def warn_pragma_unused_expected_var_arg : Warning< "only variables can be arguments to '#pragma unused'">, InGroup; def err_pragma_push_visibility_mismatch : Error< "#pragma visibility push with no matching #pragma visibility pop">; def note_surrounding_namespace_ends_here : Note< "surrounding namespace with visibility attribute ends here">; def err_pragma_pop_visibility_mismatch : Error< "#pragma visibility pop with no matching #pragma visibility push">; def note_surrounding_namespace_starts_here : Note< "surrounding namespace with visibility attribute starts here">; def err_pragma_loop_invalid_argument_type : Error< "invalid argument of type %0; expected an integer type">; def err_pragma_loop_invalid_argument_value : Error< "%select{invalid value '%0'; must be positive|value '%0' is too large}1">; def err_pragma_loop_compatibility : Error< "%select{incompatible|duplicate}0 directives '%1' and '%2'">; def err_pragma_loop_precedes_nonloop : Error< "expected a for, while, or do-while loop to follow '%0'">; def err_pragma_attribute_matcher_subrule_contradicts_rule : Error< "redundant attribute subject matcher sub-rule '%0'; '%1' already matches " "those declarations">; def err_pragma_attribute_matcher_negated_subrule_contradicts_subrule : Error< "negated attribute subject matcher sub-rule '%0' contradicts sub-rule '%1'">; def err_pragma_attribute_invalid_matchers : Error< "attribute %0 can't be applied to %1">; def err_pragma_attribute_stack_mismatch : Error< "'#pragma clang attribute %select{%1.|}0pop' with no matching" " '#pragma clang attribute %select{%1.|}0push'">; def warn_pragma_attribute_unused : Warning< "unused attribute %0 in '#pragma clang attribute push' region">, InGroup; def note_pragma_attribute_region_ends_here : Note< "'#pragma clang attribute push' regions ends here">; def err_pragma_attribute_no_pop_eof : Error<"unterminated " "'#pragma clang attribute push' at end of file">; def note_pragma_attribute_applied_decl_here : Note< "when applied to this declaration">; def err_pragma_attr_attr_no_push : Error< "'#pragma clang attribute' attribute with no matching " "'#pragma clang attribute push'">; /// Objective-C parser diagnostics def err_duplicate_class_def : Error< "duplicate interface definition for class %0">; def err_undef_superclass : Error< "cannot find interface declaration for %0, superclass of %1">; def err_forward_superclass : Error< "attempting to use the forward class %0 as superclass of %1">; def err_no_nsconstant_string_class : Error< "cannot find interface declaration for %0">; def err_recursive_superclass : Error< "trying to recursively use %0 as superclass of %1">; def err_conflicting_aliasing_type : Error<"conflicting types for alias %0">; def warn_undef_interface : Warning<"cannot find interface declaration for %0">; def warn_duplicate_protocol_def : Warning< "duplicate protocol definition of %0 is ignored">, InGroup>; def err_protocol_has_circular_dependency : Error< "protocol has circular dependency">; def err_undeclared_protocol : Error<"cannot find protocol declaration for %0">; def warn_undef_protocolref : Warning<"cannot find protocol definition for %0">; def err_atprotocol_protocol : Error< "@protocol is using a forward protocol declaration of %0">; def warn_readonly_property : Warning< "attribute 'readonly' of property %0 restricts attribute " "'readwrite' of property inherited from %1">, InGroup; def warn_property_attribute : Warning< "'%1' attribute on property %0 does not match the property inherited from %2">, InGroup; def warn_property_types_are_incompatible : Warning< "property type %0 is incompatible with type %1 inherited from %2">, InGroup>; def warn_protocol_property_mismatch : Warning< "property %select{of type %1|with attribute '%1'|without attribute '%1'|with " "getter %1|with setter %1}0 was selected for synthesis">, InGroup>; def err_protocol_property_mismatch: Error; def err_undef_interface : Error<"cannot find interface declaration for %0">; def err_category_forward_interface : Error< "cannot define %select{category|class extension}0 for undefined class %1">; def err_class_extension_after_impl : Error< "cannot declare class extension for %0 after class implementation">; def note_implementation_declared : Note< "class implementation is declared here">; def note_while_in_implementation : Note< "detected while default synthesizing properties in class implementation">; def note_class_declared : Note< "class is declared here">; def note_receiver_class_declared : Note< "receiver is instance of class declared here">; def note_receiver_expr_here : Note< "receiver expression is here">; def note_receiver_is_id : Note< "receiver is treated with 'id' type for purpose of method lookup">; def note_suppressed_class_declare : Note< "class with specified objc_requires_property_definitions attribute is declared here">; def err_objc_root_class_subclass : Error< "objc_root_class attribute may only be specified on a root class declaration">; def err_restricted_superclass_mismatch : Error< "cannot subclass a class that was declared with the " "'objc_subclassing_restricted' attribute">; def warn_objc_root_class_missing : Warning< "class %0 defined without specifying a base class">, InGroup; def err_objc_runtime_visible_category : Error< "cannot implement a category for class %0 that is only visible via the " "Objective-C runtime">; def err_objc_runtime_visible_subclass : Error< "cannot implement subclass %0 of a superclass %1 that is only visible via the " "Objective-C runtime">; def note_objc_needs_superclass : Note< "add a super class to fix this problem">; def err_conflicting_super_class : Error<"conflicting super class name %0">; def err_dup_implementation_class : Error<"reimplementation of class %0">; def err_dup_implementation_category : Error< "reimplementation of category %1 for class %0">; def err_conflicting_ivar_type : Error< "instance variable %0 has conflicting type%diff{: $ vs $|}1,2">; def err_duplicate_ivar_declaration : Error< "instance variable is already declared">; def warn_on_superclass_use : Warning< "class implementation may not have super class">; def err_conflicting_ivar_bitwidth : Error< "instance variable %0 has conflicting bit-field width">; def err_conflicting_ivar_name : Error< "conflicting instance variable names: %0 vs %1">; def err_inconsistent_ivar_count : Error< "inconsistent number of instance variables specified">; def warn_undef_method_impl : Warning<"method definition for %0 not found">, InGroup>; def warn_conflicting_overriding_ret_types : Warning< "conflicting return type in " "declaration of %0%diff{: $ vs $|}1,2">, InGroup, DefaultIgnore; def warn_conflicting_ret_types : Warning< "conflicting return type in " "implementation of %0%diff{: $ vs $|}1,2">, InGroup; def warn_conflicting_overriding_ret_type_modifiers : Warning< "conflicting distributed object modifiers on return type " "in declaration of %0">, InGroup, DefaultIgnore; def warn_conflicting_ret_type_modifiers : Warning< "conflicting distributed object modifiers on return type " "in implementation of %0">, InGroup; def warn_non_covariant_overriding_ret_types : Warning< "conflicting return type in " "declaration of %0: %1 vs %2">, InGroup, DefaultIgnore; def warn_non_covariant_ret_types : Warning< "conflicting return type in " "implementation of %0: %1 vs %2">, InGroup, DefaultIgnore; def warn_conflicting_overriding_param_types : Warning< "conflicting parameter types in " "declaration of %0%diff{: $ vs $|}1,2">, InGroup, DefaultIgnore; def warn_conflicting_param_types : Warning< "conflicting parameter types in " "implementation of %0%diff{: $ vs $|}1,2">, InGroup; def warn_conflicting_param_modifiers : Warning< "conflicting distributed object modifiers on parameter type " "in implementation of %0">, InGroup; def warn_conflicting_overriding_param_modifiers : Warning< "conflicting distributed object modifiers on parameter type " "in declaration of %0">, InGroup, DefaultIgnore; def warn_non_contravariant_overriding_param_types : Warning< "conflicting parameter types in " "declaration of %0: %1 vs %2">, InGroup, DefaultIgnore; def warn_non_contravariant_param_types : Warning< "conflicting parameter types in " "implementation of %0: %1 vs %2">, InGroup, DefaultIgnore; def warn_conflicting_overriding_variadic :Warning< "conflicting variadic declaration of method and its " "implementation">, InGroup, DefaultIgnore; def warn_conflicting_variadic :Warning< "conflicting variadic declaration of method and its " "implementation">; def warn_category_method_impl_match:Warning< "category is implementing a method which will also be implemented" " by its primary class">, InGroup; def warn_implements_nscopying : Warning< "default assign attribute on property %0 which implements " "NSCopying protocol is not appropriate with -fobjc-gc[-only]">; def warn_multiple_method_decl : Warning<"multiple methods named %0 found">, InGroup; def warn_strict_multiple_method_decl : Warning< "multiple methods named %0 found">, InGroup, DefaultIgnore; def warn_accessor_property_type_mismatch : Warning< "type of property %0 does not match type of accessor %1">; def note_conv_function_declared_at : Note<"type conversion function declared here">; def note_method_declared_at : Note<"method %0 declared here">; def note_property_attribute : Note<"property %0 is declared " "%select{deprecated|unavailable|partial}1 here">; def err_setter_type_void : Error<"type of setter must be void">; def err_duplicate_method_decl : Error<"duplicate declaration of method %0">; def warn_duplicate_method_decl : Warning<"multiple declarations of method %0 found and ignored">, InGroup, DefaultIgnore; def warn_objc_cdirective_format_string : Warning<"using %0 directive in %select{NSString|CFString}1 " "which is being passed as a formatting argument to the formatting " "%select{method|CFfunction}2">, InGroup, DefaultIgnore; def err_objc_var_decl_inclass : Error<"cannot declare variable inside @interface or @protocol">; def err_missing_method_context : Error< "missing context for method declaration">; def err_objc_property_attr_mutually_exclusive : Error< "property attributes '%0' and '%1' are mutually exclusive">; def err_objc_property_requires_object : Error< "property with '%0' attribute must be of object type">; def warn_objc_property_assign_on_object : Warning< "'assign' property of object type may become a dangling reference; consider using 'unsafe_unretained'">, InGroup, DefaultIgnore; def warn_objc_property_no_assignment_attribute : Warning< "no 'assign', 'retain', or 'copy' attribute is specified - " "'assign' is assumed">, InGroup; def warn_objc_isa_use : Warning< "direct access to Objective-C's isa is deprecated in favor of " "object_getClass()">, InGroup; def warn_objc_isa_assign : Warning< "assignment to Objective-C's isa is deprecated in favor of " "object_setClass()">, InGroup; def warn_objc_pointer_masking : Warning< "bitmasking for introspection of Objective-C object pointers is strongly " "discouraged">, InGroup; def warn_objc_pointer_masking_performSelector : Warning, InGroup; def warn_objc_property_default_assign_on_object : Warning< "default property attribute 'assign' not appropriate for object">, InGroup; def warn_property_attr_mismatch : Warning< "property attribute in class extension does not match the primary class">, InGroup; def warn_property_implicitly_mismatched : Warning < "primary property declaration is implicitly strong while redeclaration " "in class extension is weak">, InGroup>; def warn_objc_property_copy_missing_on_block : Warning< "'copy' attribute must be specified for the block property " "when -fobjc-gc-only is specified">; def warn_objc_property_retain_of_block : Warning< "retain'ed block property does not copy the block " "- use copy attribute instead">, InGroup; def warn_objc_readonly_property_has_setter : Warning< "setter cannot be specified for a readonly property">, InGroup; def warn_atomic_property_rule : Warning< "writable atomic property %0 cannot pair a synthesized %select{getter|setter}1 " "with a user defined %select{getter|setter}2">, InGroup>; def note_atomic_property_fixup_suggest : Note<"setter and getter must both be " "synthesized, or both be user defined,or the property must be nonatomic">; def err_atomic_property_nontrivial_assign_op : Error< "atomic property of reference type %0 cannot have non-trivial assignment" " operator">; def warn_cocoa_naming_owned_rule : Warning< "property follows Cocoa naming" " convention for returning 'owned' objects">, InGroup>; def err_cocoa_naming_owned_rule : Error< "property follows Cocoa naming" " convention for returning 'owned' objects">; def note_cocoa_naming_declare_family : Note< "explicitly declare getter %objcinstance0 with '%1' to return an 'unowned' " "object">; def warn_auto_synthesizing_protocol_property :Warning< "auto property synthesis will not synthesize property %0" " declared in protocol %1">, InGroup>; def note_add_synthesize_directive : Note< "add a '@synthesize' directive">; def warn_no_autosynthesis_shared_ivar_property : Warning < "auto property synthesis will not synthesize property " "%0 because it cannot share an ivar with another synthesized property">, InGroup; def warn_no_autosynthesis_property : Warning< "auto property synthesis will not synthesize property " "%0 because it is 'readwrite' but it will be synthesized 'readonly' " "via another property">, InGroup; def warn_autosynthesis_property_in_superclass : Warning< "auto property synthesis will not synthesize property " "%0; it will be implemented by its superclass, use @dynamic to " "acknowledge intention">, InGroup; def warn_autosynthesis_property_ivar_match :Warning< "autosynthesized property %0 will use %select{|synthesized}1 instance variable " "%2, not existing instance variable %3">, InGroup>; def warn_missing_explicit_synthesis : Warning < "auto property synthesis is synthesizing property not explicitly synthesized">, InGroup>, DefaultIgnore; def warn_property_getter_owning_mismatch : Warning< "property declared as returning non-retained objects" "; getter returning retained objects">; def warn_property_redecl_getter_mismatch : Warning< "getter name mismatch between property redeclaration (%1) and its original " "declaration (%0)">, InGroup; def err_property_setter_ambiguous_use : Error< "synthesized properties %0 and %1 both claim setter %2 -" " use of this setter will cause unexpected behavior">; def warn_default_atomic_custom_getter_setter : Warning< "atomic by default property %0 has a user defined %select{getter|setter}1 " "(property should be marked 'atomic' if this is intended)">, InGroup, DefaultIgnore; def err_use_continuation_class : Error< "illegal redeclaration of property in class extension %0" " (attribute must be 'readwrite', while its primary must be 'readonly')">; def err_type_mismatch_continuation_class : Error< "type of property %0 in class extension does not match " "property type in primary class">; def err_use_continuation_class_redeclaration_readwrite : Error< "illegal redeclaration of 'readwrite' property in class extension %0" " (perhaps you intended this to be a 'readwrite' redeclaration of a " "'readonly' public property?)">; def err_continuation_class : Error<"class extension has no primary class">; def err_property_type : Error<"property cannot have array or function type %0">; def err_missing_property_context : Error< "missing context for property implementation declaration">; def err_bad_property_decl : Error< "property implementation must have its declaration in interface %0 or one of " "its extensions">; def err_category_property : Error< "property declared in category %0 cannot be implemented in " "class implementation">; def note_property_declare : Note< "property declared here">; def note_protocol_property_declare : Note< "it could also be property " "%select{of type %1|without attribute '%1'|with attribute '%1'|with getter " "%1|with setter %1}0 declared here">; def note_property_synthesize : Note< "property synthesized here">; def err_synthesize_category_decl : Error< "@synthesize not allowed in a category's implementation">; def err_synthesize_on_class_property : Error< "@synthesize not allowed on a class property %0">; def err_missing_property_interface : Error< "property implementation in a category with no category declaration">; def err_bad_category_property_decl : Error< "property implementation must have its declaration in the category %0">; def err_bad_property_context : Error< "property implementation must be in a class or category implementation">; def err_missing_property_ivar_decl : Error< "synthesized property %0 must either be named the same as a compatible" " instance variable or must explicitly name an instance variable">; def err_arc_perform_selector_retains : Error< "performSelector names a selector which retains the object">; def warn_arc_perform_selector_leaks : Warning< "performSelector may cause a leak because its selector is unknown">, InGroup>; def warn_dealloc_in_category : Warning< "-dealloc is being overridden in a category">, InGroup; def err_gc_weak_property_strong_type : Error< "weak attribute declared on a __strong type property in GC mode">; def warn_arc_repeated_use_of_weak : Warning < "weak %select{variable|property|implicit property|instance variable}0 %1 is " "accessed multiple times in this %select{function|method|block|lambda}2 " "but may be unpredictably set to nil; assign to a strong variable to keep " "the object alive">, InGroup, DefaultIgnore; def warn_implicitly_retains_self : Warning < "block implicitly retains 'self'; explicitly mention 'self' to indicate " "this is intended behavior">, InGroup>, DefaultIgnore; def warn_arc_possible_repeated_use_of_weak : Warning < "weak %select{variable|property|implicit property|instance variable}0 %1 may " "be accessed multiple times in this %select{function|method|block|lambda}2 " "and may be unpredictably set to nil; assign to a strong variable to keep " "the object alive">, InGroup, DefaultIgnore; def note_arc_weak_also_accessed_here : Note< "also accessed here">; def err_incomplete_synthesized_property : Error< "cannot synthesize property %0 with incomplete type %1">; def err_property_ivar_type : Error< "type of property %0 (%1) does not match type of instance variable %2 (%3)">; def err_property_accessor_type : Error< "type of property %0 (%1) does not match type of accessor %2 (%3)">; def err_ivar_in_superclass_use : Error< "property %0 attempting to use instance variable %1 declared in super class %2">; def err_weak_property : Error< "existing instance variable %1 for __weak property %0 must be __weak">; def err_strong_property : Error< "existing instance variable %1 for strong property %0 may not be __weak">; def err_dynamic_property_ivar_decl : Error< "dynamic property cannot have instance variable specification">; def err_duplicate_ivar_use : Error< "synthesized properties %0 and %1 both claim instance variable %2">; def err_property_implemented : Error<"property %0 is already implemented">; def warn_objc_missing_super_call : Warning< "method possibly missing a [super %0] call">, InGroup; def err_dealloc_bad_result_type : Error< "dealloc return type must be correctly specified as 'void' under ARC, " "instead of %0">; def warn_undeclared_selector : Warning< "undeclared selector %0">, InGroup, DefaultIgnore; def warn_undeclared_selector_with_typo : Warning< "undeclared selector %0; did you mean %1?">, InGroup, DefaultIgnore; def warn_implicit_atomic_property : Warning< "property is assumed atomic by default">, InGroup, DefaultIgnore; def note_auto_readonly_iboutlet_fixup_suggest : Note< "property should be changed to be readwrite">; def warn_auto_readonly_iboutlet_property : Warning< "readonly IBOutlet property %0 when auto-synthesized may " "not work correctly with 'nib' loader">, InGroup>; def warn_auto_implicit_atomic_property : Warning< "property is assumed atomic when auto-synthesizing the property">, InGroup, DefaultIgnore; def warn_unimplemented_selector: Warning< "no method with selector %0 is implemented in this translation unit">, InGroup, DefaultIgnore; def warn_unimplemented_protocol_method : Warning< "method %0 in protocol %1 not implemented">, InGroup; def warn_multiple_selectors: Warning< "several methods with selector %0 of mismatched types are found " "for the @selector expression">, InGroup, DefaultIgnore; def err_objc_kindof_nonobject : Error< "'__kindof' specifier cannot be applied to non-object type %0">; def err_objc_kindof_wrong_position : Error< "'__kindof' type specifier must precede the declarator">; def err_objc_method_unsupported_param_ret_type : Error< "%0 %select{parameter|return}1 type is unsupported; " "support for vector types for this target is introduced in %2">; def warn_messaging_unqualified_id : Warning< "messaging unqualified id">, DefaultIgnore, InGroup>; // C++ declarations def err_static_assert_expression_is_not_constant : Error< "static_assert expression is not an integral constant expression">; def err_static_assert_failed : Error<"static_assert failed%select{ %1|}0">; def err_static_assert_requirement_failed : Error< "static_assert failed due to requirement '%0'%select{ %2|}1">; def ext_inline_variable : ExtWarn< "inline variables are a C++17 extension">, InGroup; def warn_cxx14_compat_inline_variable : Warning< "inline variables are incompatible with C++ standards before C++17">, DefaultIgnore, InGroup; def warn_inline_namespace_reopened_noninline : Warning< "inline namespace reopened as a non-inline namespace">; def err_inline_namespace_mismatch : Error< "non-inline namespace cannot be reopened as inline">; def err_unexpected_friend : Error< "friends can only be classes or functions">; def ext_enum_friend : ExtWarn< "befriending enumeration type %0 is a C++11 extension">, InGroup; def warn_cxx98_compat_enum_friend : Warning< "befriending enumeration type %0 is incompatible with C++98">, InGroup, DefaultIgnore; def ext_nonclass_type_friend : ExtWarn< "non-class friend type %0 is a C++11 extension">, InGroup; def warn_cxx98_compat_nonclass_type_friend : Warning< "non-class friend type %0 is incompatible with C++98">, InGroup, DefaultIgnore; def err_friend_is_member : Error< "friends cannot be members of the declaring class">; def warn_cxx98_compat_friend_is_member : Warning< "friend declaration naming a member of the declaring class is incompatible " "with C++98">, InGroup, DefaultIgnore; def ext_unelaborated_friend_type : ExtWarn< "unelaborated friend declaration is a C++11 extension; specify " "'%select{struct|interface|union|class|enum}0' to befriend %1">, InGroup; def warn_cxx98_compat_unelaborated_friend_type : Warning< "befriending %1 without '%select{struct|interface|union|class|enum}0' " "keyword is incompatible with C++98">, InGroup, DefaultIgnore; def err_qualified_friend_no_match : Error< "friend declaration of %0 does not match any declaration in %1">; def err_introducing_special_friend : Error< "%plural{[0,2]:must use a qualified name when declaring|3:cannot declare}0" " a %select{constructor|destructor|conversion operator|deduction guide}0 " "as a friend">; def err_tagless_friend_type_template : Error< "friend type templates must use an elaborated type">; def err_no_matching_local_friend : Error< "no matching function found in local scope">; def err_no_matching_local_friend_suggest : Error< "no matching function %0 found in local scope; did you mean %3?">; def err_partial_specialization_friend : Error< "partial specialization cannot be declared as a friend">; def err_qualified_friend_def : Error< "friend function definition cannot be qualified with '%0'">; def err_friend_def_in_local_class : Error< "friend function cannot be defined in a local class">; def err_friend_not_first_in_declaration : Error< "'friend' must appear first in a non-function declaration">; def err_using_decl_friend : Error< "cannot befriend target of using declaration">; def warn_template_qualified_friend_unsupported : Warning< "dependent nested name specifier '%0' for friend class declaration is " "not supported; turning off access control for %1">, InGroup; def warn_template_qualified_friend_ignored : Warning< "dependent nested name specifier '%0' for friend template declaration is " "not supported; ignoring this friend declaration">, InGroup; def ext_friend_tag_redecl_outside_namespace : ExtWarn< "unqualified friend declaration referring to type outside of the nearest " "enclosing namespace is a Microsoft extension; add a nested name specifier">, InGroup; def err_pure_friend : Error<"friend declaration cannot have a pure-specifier">; def err_invalid_base_in_interface : Error< "interface type cannot inherit from " "%select{struct|non-public interface|class}0 %1">; def err_abstract_type_in_decl : Error< "%select{return|parameter|variable|field|instance variable|" "synthesized instance variable}0 type %1 is an abstract class">; def err_allocation_of_abstract_type : Error< "allocating an object of abstract class type %0">; def err_throw_abstract_type : Error< "cannot throw an object of abstract type %0">; def err_array_of_abstract_type : Error<"array of abstract class type %0">; def err_capture_of_abstract_type : Error< "by-copy capture of value of abstract type %0">; def err_capture_of_incomplete_type : Error< "by-copy capture of variable %0 with incomplete type %1">; def err_capture_default_non_local : Error< "non-local lambda expression cannot have a capture-default">; def err_multiple_final_overriders : Error< "virtual function %q0 has more than one final overrider in %1">; def note_final_overrider : Note<"final overrider of %q0 in %1">; def err_type_defined_in_type_specifier : Error< "%0 cannot be defined in a type specifier">; def err_type_defined_in_result_type : Error< "%0 cannot be defined in the result type of a function">; def err_type_defined_in_param_type : Error< "%0 cannot be defined in a parameter type">; def err_type_defined_in_alias_template : Error< "%0 cannot be defined in a type alias template">; def err_type_defined_in_condition : Error< "%0 cannot be defined in a condition">; def err_type_defined_in_enum : Error< "%0 cannot be defined in an enumeration">; def note_pure_virtual_function : Note< "unimplemented pure virtual method %0 in %1">; def note_pure_qualified_call_kext : Note< "qualified call to %0::%1 is treated as a virtual call to %1 due to -fapple-kext">; def err_deleted_decl_not_first : Error< "deleted definition must be first declaration">; def err_deleted_override : Error< "deleted function %0 cannot override a non-deleted function">; def err_non_deleted_override : Error< "non-deleted function %0 cannot override a deleted function">; def warn_weak_vtable : Warning< "%0 has no out-of-line virtual method definitions; its vtable will be " "emitted in every translation unit">, InGroup>, DefaultIgnore; def warn_weak_template_vtable : Warning< "explicit template instantiation %0 will emit a vtable in every " "translation unit">, InGroup>, DefaultIgnore; def ext_using_undefined_std : ExtWarn< "using directive refers to implicitly-defined namespace 'std'">; // C++ exception specifications def err_exception_spec_in_typedef : Error< "exception specifications are not allowed in %select{typedefs|type aliases}0">; def err_distant_exception_spec : Error< "exception specifications are not allowed beyond a single level " "of indirection">; def err_incomplete_in_exception_spec : Error< "%select{|pointer to |reference to }0incomplete type %1 is not allowed " "in exception specification">; def ext_incomplete_in_exception_spec : ExtWarn, InGroup; def err_rref_in_exception_spec : Error< "rvalue reference type %0 is not allowed in exception specification">; def err_mismatched_exception_spec : Error< "exception specification in declaration does not match previous declaration">; def ext_mismatched_exception_spec : ExtWarn, InGroup; def err_override_exception_spec : Error< "exception specification of overriding function is more lax than " "base version">; def ext_override_exception_spec : ExtWarn, InGroup; def err_incompatible_exception_specs : Error< "target exception specification is not superset of source">; def warn_incompatible_exception_specs : Warning< err_incompatible_exception_specs.Text>, InGroup; def err_deep_exception_specs_differ : Error< "exception specifications of %select{return|argument}0 types differ">; def warn_deep_exception_specs_differ : Warning< err_deep_exception_specs_differ.Text>, InGroup; def err_missing_exception_specification : Error< "%0 is missing exception specification '%1'">; def ext_missing_exception_specification : ExtWarn< err_missing_exception_specification.Text>, InGroup>; def ext_ms_missing_exception_specification : ExtWarn< err_missing_exception_specification.Text>, InGroup; def err_noexcept_needs_constant_expression : Error< "argument to noexcept specifier must be a constant expression">; def err_exception_spec_not_parsed : Error< "exception specification is not available until end of class definition">; def err_exception_spec_cycle : Error< "exception specification of %0 uses itself">; def err_exception_spec_incomplete_type : Error< "exception specification needed for member of incomplete class %0">; // C++ access checking def err_class_redeclared_with_different_access : Error< "%0 redeclared with '%1' access">; def err_access : Error< "%1 is a %select{private|protected}0 member of %3">, AccessControl; def ext_ms_using_declaration_inaccessible : ExtWarn< "using declaration referring to inaccessible member '%0' (which refers " "to accessible member '%1') is a Microsoft compatibility extension">, AccessControl, InGroup; def err_access_ctor : Error< "calling a %select{private|protected}0 constructor of class %2">, AccessControl; def ext_rvalue_to_reference_access_ctor : Extension< "C++98 requires an accessible copy constructor for class %2 when binding " "a reference to a temporary; was %select{private|protected}0">, AccessControl, InGroup; def err_access_base_ctor : Error< // The ERRORs represent other special members that aren't constructors, in // hopes that someone will bother noticing and reporting if they appear "%select{base class|inherited virtual base class}0 %1 has %select{private|" "protected}3 %select{default |copy |move |*ERROR* |*ERROR* " "|*ERROR*|}2constructor">, AccessControl; def err_access_field_ctor : Error< // The ERRORs represent other special members that aren't constructors, in // hopes that someone will bother noticing and reporting if they appear "field of type %0 has %select{private|protected}2 " "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}1constructor">, AccessControl; def err_access_friend_function : Error< "friend function %1 is a %select{private|protected}0 member of %3">, AccessControl; def err_access_dtor : Error< "calling a %select{private|protected}1 destructor of class %0">, AccessControl; def err_access_dtor_base : Error<"base class %0 has %select{private|protected}1 destructor">, AccessControl; def err_access_dtor_vbase : Error<"inherited virtual base class %1 has " "%select{private|protected}2 destructor">, AccessControl; def err_access_dtor_temp : Error<"temporary of type %0 has %select{private|protected}1 destructor">, AccessControl; def err_access_dtor_exception : Error<"exception object of type %0 has %select{private|protected}1 " "destructor">, AccessControl; def err_access_dtor_field : Error<"field of type %1 has %select{private|protected}2 destructor">, AccessControl; def err_access_dtor_var : Error<"variable of type %1 has %select{private|protected}2 destructor">, AccessControl; def err_access_dtor_ivar : Error<"instance variable of type %0 has %select{private|protected}1 " "destructor">, AccessControl; def note_previous_access_declaration : Note< "previously declared '%1' here">; def note_access_natural : Note< "%select{|implicitly }1declared %select{private|protected}0 here">; def note_access_constrained_by_path : Note< "constrained by %select{|implicitly }1%select{private|protected}0" " inheritance here">; def note_access_protected_restricted_noobject : Note< "must name member using the type of the current context %0">; def note_access_protected_restricted_ctordtor : Note< "protected %select{constructor|destructor}0 can only be used to " "%select{construct|destroy}0 a base class subobject">; def note_access_protected_restricted_object : Note< "can only access this member on an object of type %0">; def warn_cxx98_compat_sfinae_access_control : Warning< "substitution failure due to access control is incompatible with C++98">, InGroup, DefaultIgnore, NoSFINAE; // C++ name lookup def err_incomplete_nested_name_spec : Error< "incomplete type %0 named in nested name specifier">; def err_dependent_nested_name_spec : Error< "nested name specifier for a declaration cannot depend on a template " "parameter">; def err_nested_name_member_ref_lookup_ambiguous : Error< "lookup of %0 in member access expression is ambiguous">; def ext_nested_name_member_ref_lookup_ambiguous : ExtWarn< "lookup of %0 in member access expression is ambiguous; using member of %1">, InGroup; def note_ambig_member_ref_object_type : Note< "lookup in the object type %0 refers here">; def note_ambig_member_ref_scope : Note< "lookup from the current scope refers here">; def err_qualified_member_nonclass : Error< "qualified member access refers to a member in %0">; def err_incomplete_member_access : Error< "member access into incomplete type %0">; def err_incomplete_type : Error< "incomplete type %0 where a complete type is required">; def warn_cxx98_compat_enum_nested_name_spec : Warning< "enumeration type in nested name specifier is incompatible with C++98">, InGroup, DefaultIgnore; def err_nested_name_spec_is_not_class : Error< "%0 cannot appear before '::' because it is not a class" "%select{ or namespace|, namespace, or enumeration}1; did you mean ':'?">; def ext_nested_name_spec_is_enum : ExtWarn< "use of enumeration in a nested name specifier is a C++11 extension">, InGroup; def err_out_of_line_qualified_id_type_names_constructor : Error< "qualified reference to %0 is a constructor name rather than a " "%select{template name|type}1 in this context">; def ext_out_of_line_qualified_id_type_names_constructor : ExtWarn< "ISO C++ specifies that " "qualified reference to %0 is a constructor name rather than a " "%select{template name|type}1 in this context, despite preceding " "%select{'typename'|'template'}2 keyword">, SFINAEFailure, InGroup>; // C++ class members def err_storageclass_invalid_for_member : Error< "storage class specified for a member declaration">; def err_mutable_function : Error<"'mutable' cannot be applied to functions">; def err_mutable_reference : Error<"'mutable' cannot be applied to references">; def ext_mutable_reference : ExtWarn< "'mutable' on a reference type is a Microsoft extension">, InGroup; def err_mutable_const : Error<"'mutable' and 'const' cannot be mixed">; def err_mutable_nonmember : Error< "'mutable' can only be applied to member variables">; def err_virtual_in_union : Error< "unions cannot have virtual functions">; def err_virtual_non_function : Error< "'virtual' can only appear on non-static member functions">; def err_virtual_out_of_class : Error< "'virtual' can only be specified inside the class definition">; def err_virtual_member_function_template : Error< "'virtual' cannot be specified on member function templates">; def err_static_overrides_virtual : Error< "'static' member function %0 overrides a virtual function in a base class">; def err_explicit_non_function : Error< "'explicit' can only appear on non-static member functions">; def err_explicit_out_of_class : Error< "'explicit' can only be specified inside the class definition">; def err_explicit_non_ctor_or_conv_function : Error< "'explicit' can only be applied to a constructor or conversion function">; def err_static_not_bitfield : Error<"static member %0 cannot be a bit-field">; def err_static_out_of_line : Error< "'static' can only be specified inside the class definition">; def err_storage_class_for_static_member : Error< "static data member definition cannot specify a storage class">; def err_typedef_not_bitfield : Error<"typedef member %0 cannot be a bit-field">; def err_not_integral_type_bitfield : Error< "bit-field %0 has non-integral type %1">; def err_not_integral_type_anon_bitfield : Error< "anonymous bit-field has non-integral type %0">; def err_anon_bitfield_qualifiers : Error< "anonymous bit-field cannot have qualifiers">; def err_member_function_initialization : Error< "initializer on function does not look like a pure-specifier">; def err_non_virtual_pure : Error< "%0 is not virtual and cannot be declared pure">; def ext_pure_function_definition : ExtWarn< "function definition with pure-specifier is a Microsoft extension">, InGroup; def err_qualified_member_of_unrelated : Error< "%q0 is not a member of class %1">; def err_member_function_call_bad_cvr : Error< "'this' argument to member function %0 has type %1, but function is not marked " "%select{const|restrict|const or restrict|volatile|const or volatile|" "volatile or restrict|const, volatile, or restrict}2">; def err_member_function_call_bad_ref : Error< "'this' argument to member function %0 is an %select{lvalue|rvalue}1, " "but function has %select{non-const lvalue|rvalue}2 ref-qualifier">; def err_member_function_call_bad_type : Error< "cannot initialize object parameter of type %0 with an expression " "of type %1">; def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning< "call to pure virtual member function %0 has undefined behavior; " "overrides of %0 in subclasses are not available in the " "%select{constructor|destructor}1 of %2">, InGroup; def select_special_member_kind : TextSubstitution< "%select{default constructor|copy constructor|move constructor|" "copy assignment operator|move assignment operator|destructor}0">; def note_member_declared_at : Note<"member is declared here">; def note_ivar_decl : Note<"instance variable is declared here">; def note_bitfield_decl : Note<"bit-field is declared here">; def note_implicit_param_decl : Note<"%0 is an implicit parameter">; def note_member_synthesized_at : Note< "in implicit %sub{select_special_member_kind}0 for %1 " "first required here">; def err_missing_default_ctor : Error< "%select{constructor for %1 must explicitly initialize the|" "implicit default constructor for %1 must explicitly initialize the|" "cannot use constructor inherited from base class %4;}0 " "%select{base class|member}2 %3 %select{which|which|of %1}0 " "does not have a default constructor">; def note_due_to_dllexported_class : Note< "due to %0 being dllexported%select{|; try compiling in C++11 mode}1">; def err_illegal_union_or_anon_struct_member : Error< "%select{anonymous struct|union}0 member %1 has a non-trivial " "%sub{select_special_member_kind}2">; def warn_cxx98_compat_nontrivial_union_or_anon_struct_member : Warning< "%select{anonymous struct|union}0 member %1 with a non-trivial " "%sub{select_special_member_kind}2 is incompatible with C++98">, InGroup, DefaultIgnore; def note_nontrivial_virtual_dtor : Note< "destructor for %0 is not trivial because it is virtual">; def note_nontrivial_has_virtual : Note< "because type %0 has a virtual %select{member function|base class}1">; def note_nontrivial_no_def_ctor : Note< "because %select{base class of |field of |}0type %1 has no " "default constructor">; def note_user_declared_ctor : Note< "implicit default constructor suppressed by user-declared constructor">; def note_nontrivial_no_copy : Note< "because no %select{<>|constructor|constructor|assignment operator|" "assignment operator|<>}2 can be used to " "%select{<>|copy|move|copy|move|<>}2 " "%select{base class|field|an object}0 of type %3">; def note_nontrivial_user_provided : Note< "because %select{base class of |field of |}0type %1 has a user-provided " "%sub{select_special_member_kind}2">; def note_nontrivial_in_class_init : Note< "because field %0 has an initializer">; def note_nontrivial_param_type : Note< "because its parameter is %diff{of type $, not $|of the wrong type}2,3">; def note_nontrivial_default_arg : Note<"because it has a default argument">; def note_nontrivial_variadic : Note<"because it is a variadic function">; def note_nontrivial_subobject : Note< "because the function selected to %select{construct|copy|move|copy|move|" "destroy}2 %select{base class|field}0 of type %1 is not trivial">; def note_nontrivial_objc_ownership : Note< "because type %0 has a member with %select{no|no|__strong|__weak|" "__autoreleasing}1 ownership">; def err_static_data_member_not_allowed_in_anon_struct : Error< "static data member %0 not allowed in anonymous struct">; def ext_static_data_member_in_union : ExtWarn< "static data member %0 in union is a C++11 extension">, InGroup; def warn_cxx98_compat_static_data_member_in_union : Warning< "static data member %0 in union is incompatible with C++98">, InGroup, DefaultIgnore; def ext_union_member_of_reference_type : ExtWarn< "union member %0 has reference type %1, which is a Microsoft extension">, InGroup; def err_union_member_of_reference_type : Error< "union member %0 has reference type %1">; def ext_anonymous_struct_union_qualified : Extension< "anonymous %select{struct|union}0 cannot be '%1'">; def err_different_return_type_for_overriding_virtual_function : Error< "virtual function %0 has a different return type " "%diff{($) than the function it overrides (which has return type $)|" "than the function it overrides}1,2">; def note_overridden_virtual_function : Note< "overridden virtual function is here">; def err_conflicting_overriding_cc_attributes : Error< "virtual function %0 has different calling convention attributes " "%diff{($) than the function it overrides (which has calling convention $)|" "than the function it overrides}1,2">; def warn_overriding_method_missing_noescape : Warning< "parameter of overriding method should be annotated with " "__attribute__((noescape))">, InGroup; def note_overridden_marked_noescape : Note< "parameter of overridden method is annotated with __attribute__((noescape))">; def note_cat_conform_to_noescape_prot : Note< "%select{category|class extension}0 conforms to protocol %1 which defines method %2">; def err_covariant_return_inaccessible_base : Error< "invalid covariant return for virtual function: %1 is a " "%select{private|protected}2 base class of %0">, AccessControl; def err_covariant_return_ambiguous_derived_to_base_conv : Error< "return type of virtual function %3 is not covariant with the return type of " "the function it overrides (ambiguous conversion from derived class " "%0 to base class %1:%2)">; def err_covariant_return_not_derived : Error< "return type of virtual function %0 is not covariant with the return type of " "the function it overrides (%1 is not derived from %2)">; def err_covariant_return_incomplete : Error< "return type of virtual function %0 is not covariant with the return type of " "the function it overrides (%1 is incomplete)">; def err_covariant_return_type_different_qualifications : Error< "return type of virtual function %0 is not covariant with the return type of " "the function it overrides (%1 has different qualifiers than %2)">; def err_covariant_return_type_class_type_more_qualified : Error< "return type of virtual function %0 is not covariant with the return type of " "the function it overrides (class type %1 is more qualified than class " "type %2">; // C++ implicit special member functions def note_in_declaration_of_implicit_special_member : Note< "while declaring the implicit %sub{select_special_member_kind}1" " for %0">; // C++ constructors def err_constructor_cannot_be : Error<"constructor cannot be declared '%0'">; def err_invalid_qualified_constructor : Error< "'%0' qualifier is not allowed on a constructor">; def err_ref_qualifier_constructor : Error< "ref-qualifier '%select{&&|&}0' is not allowed on a constructor">; def err_constructor_return_type : Error< "constructor cannot have a return type">; def err_constructor_redeclared : Error<"constructor cannot be redeclared">; def err_constructor_byvalue_arg : Error< "copy constructor must pass its first argument by reference">; def warn_no_constructor_for_refconst : Warning< "%select{struct|interface|union|class|enum}0 %1 does not declare any " "constructor to initialize its non-modifiable members">; def note_refconst_member_not_initialized : Note< "%select{const|reference}0 member %1 will never be initialized">; def ext_ms_explicit_constructor_call : ExtWarn< "explicit constructor calls are a Microsoft extension">, InGroup; // C++ destructors def err_destructor_not_member : Error< "destructor must be a non-static member function">; def err_destructor_cannot_be : Error<"destructor cannot be declared '%0'">; def err_invalid_qualified_destructor : Error< "'%0' qualifier is not allowed on a destructor">; def err_ref_qualifier_destructor : Error< "ref-qualifier '%select{&&|&}0' is not allowed on a destructor">; def err_destructor_return_type : Error<"destructor cannot have a return type">; def err_destructor_redeclared : Error<"destructor cannot be redeclared">; def err_destructor_with_params : Error<"destructor cannot have any parameters">; def err_destructor_variadic : Error<"destructor cannot be variadic">; def err_destructor_typedef_name : Error< "destructor cannot be declared using a %select{typedef|type alias}1 %0 of the class name">; def err_destructor_name : Error< "expected the class name after '~' to name the enclosing class">; def err_destructor_class_name : Error< "expected the class name after '~' to name a destructor">; def err_ident_in_dtor_not_a_type : Error< "identifier %0 in object destruction expression does not name a type">; def err_destructor_expr_type_mismatch : Error< "destructor type %0 in object destruction expression does not match the " "type %1 of the object being destroyed">; def note_destructor_type_here : Note< "type %0 is declared here">; def err_destroy_attr_on_non_static_var : Error< "%select{no_destroy|always_destroy}0 attribute can only be applied to a" " variable with static or thread storage duration">; def err_destructor_template : Error< "destructor cannot be declared as a template">; // C++ initialization def err_init_conversion_failed : Error< "cannot initialize %select{a variable|a parameter|return object|" "statement expression result|an " "exception object|a member subobject|an array element|a new value|a value|a " "base class|a constructor delegation|a vector element|a block element|a " "block element|a complex element|a lambda capture|a compound literal " "initializer|a related result|a parameter of CF audited function}0 " "%diff{of type $ with an %select{rvalue|lvalue}2 of type $|" "with an %select{rvalue|lvalue}2 of incompatible type}1,3" "%select{|: different classes%diff{ ($ vs $)|}5,6" "|: different number of parameters (%5 vs %6)" "|: type mismatch at %ordinal5 parameter%diff{ ($ vs $)|}6,7" "|: different return type%diff{ ($ vs $)|}5,6" "|: different qualifiers (%5 vs %6)" "|: different exception specifications}4">; def err_lvalue_to_rvalue_ref : Error<"rvalue reference %diff{to type $ cannot " "bind to lvalue of type $|cannot bind to incompatible lvalue}0,1">; def err_lvalue_reference_bind_to_initlist : Error< "%select{non-const|volatile}0 lvalue reference to type %1 cannot bind to an " "initializer list temporary">; def err_lvalue_reference_bind_to_temporary : Error< "%select{non-const|volatile}0 lvalue reference %diff{to type $ cannot bind " "to a temporary of type $|cannot bind to incompatible temporary}1,2">; def err_lvalue_reference_bind_to_unrelated : Error< "%select{non-const|volatile}0 lvalue reference " "%diff{to type $ cannot bind to a value of unrelated type $|" "cannot bind to a value of unrelated type}1,2">; def err_reference_bind_drops_quals : Error< "binding value %diff{of type $ to reference to type $|to reference}0,1 " "drops %select{<>|'const'|'restrict'|'const' and 'restrict'|" "'volatile'|'const' and 'volatile'|'restrict' and 'volatile'|" "'const', 'restrict', and 'volatile'}2 qualifier%plural{1:|2:|4:|:s}2">; def err_reference_bind_failed : Error< "reference %diff{to type $ could not bind to an %select{rvalue|lvalue}1 of " "type $|could not bind to %select{rvalue|lvalue}1 of incompatible type}0,2">; def err_reference_bind_init_list : Error< "reference to type %0 cannot bind to an initializer list">; def err_init_list_bad_dest_type : Error< "%select{|non-aggregate }0type %1 cannot be initialized with an initializer " "list">; def warn_cxx2a_compat_aggregate_init_with_ctors : Warning< "aggregate initialization of type %0 with user-declared constructors " "is incompatible with C++2a">, DefaultIgnore, InGroup; def err_reference_bind_to_bitfield : Error< "%select{non-const|volatile}0 reference cannot bind to " "bit-field%select{| %1}2">; def err_reference_bind_to_vector_element : Error< "%select{non-const|volatile}0 reference cannot bind to vector element">; def err_reference_var_requires_init : Error< "declaration of reference variable %0 requires an initializer">; def err_reference_without_init : Error< "reference to type %0 requires an initializer">; def note_value_initialization_here : Note< "in value-initialization of type %0 here">; def err_reference_has_multiple_inits : Error< "reference cannot be initialized with multiple values">; def err_init_non_aggr_init_list : Error< "initialization of non-aggregate type %0 with an initializer list">; def err_init_reference_member_uninitialized : Error< "reference member of type %0 uninitialized">; def note_uninit_reference_member : Note< "uninitialized reference member is here">; def warn_field_is_uninit : Warning<"field %0 is uninitialized when used here">, InGroup; def warn_base_class_is_uninit : Warning< "base class %0 is uninitialized when used here to access %q1">, InGroup; def warn_reference_field_is_uninit : Warning< "reference %0 is not yet bound to a value when used here">, InGroup; def note_uninit_in_this_constructor : Note< "during field initialization in %select{this|the implicit default}0 " "constructor">; def warn_static_self_reference_in_init : Warning< "static variable %0 is suspiciously used within its own initialization">, InGroup; def warn_uninit_self_reference_in_init : Warning< "variable %0 is uninitialized when used within its own initialization">, InGroup; def warn_uninit_self_reference_in_reference_init : Warning< "reference %0 is not yet bound to a value when used within its own" " initialization">, InGroup; def warn_uninit_var : Warning< "variable %0 is uninitialized when %select{used here|captured by block}1">, InGroup, DefaultIgnore; def warn_sometimes_uninit_var : Warning< "variable %0 is %select{used|captured}1 uninitialized whenever " "%select{'%3' condition is %select{true|false}4|" "'%3' loop %select{is entered|exits because its condition is false}4|" "'%3' loop %select{condition is true|exits because its condition is false}4|" "switch %3 is taken|" "its declaration is reached|" "%3 is called}2">, InGroup, DefaultIgnore; def warn_maybe_uninit_var : Warning< "variable %0 may be uninitialized when " "%select{used here|captured by block}1">, InGroup, DefaultIgnore; def note_var_declared_here : Note<"variable %0 is declared here">; def note_uninit_var_use : Note< "%select{uninitialized use occurs|variable is captured by block}0 here">; def warn_uninit_byref_blockvar_captured_by_block : Warning< "block pointer variable %0 is uninitialized when captured by block">, InGroup, DefaultIgnore; def note_block_var_fixit_add_initialization : Note< "did you mean to use __block %0?">; def note_in_omitted_aggregate_initializer : Note< "in implicit initialization of %select{" "array element %1 with omitted initializer|" "field %1 with omitted initializer|" "trailing array elements in runtime-sized array new}0">; def note_in_reference_temporary_list_initializer : Note< "in initialization of temporary of type %0 created to " "list-initialize this reference">; def note_var_fixit_add_initialization : Note< "initialize the variable %0 to silence this warning">; def note_uninit_fixit_remove_cond : Note< "remove the %select{'%1' if its condition|condition if it}0 " "is always %select{false|true}2">; def err_init_incomplete_type : Error<"initialization of incomplete type %0">; def err_list_init_in_parens : Error< "cannot initialize %select{non-class|reference}0 type %1 with a " "parenthesized initializer list">; def warn_unsequenced_mod_mod : Warning< "multiple unsequenced modifications to %0">, InGroup; def warn_unsequenced_mod_use : Warning< "unsequenced modification and access to %0">, InGroup; def select_initialized_entity_kind : TextSubstitution< "%select{copying variable|copying parameter|" "returning object|initializing statement expression result|" "throwing object|copying member subobject|copying array element|" "allocating object|copying temporary|initializing base subobject|" "initializing vector element|capturing value}0">; def err_temp_copy_no_viable : Error< "no viable constructor %sub{select_initialized_entity_kind}0 of type %1">; def ext_rvalue_to_reference_temp_copy_no_viable : Extension< "no viable constructor %sub{select_initialized_entity_kind}0 of type %1; " "C++98 requires a copy constructor when binding a reference to a temporary">, InGroup; def err_temp_copy_ambiguous : Error< "ambiguous constructor call when %sub{select_initialized_entity_kind}0 " "of type %1">; def err_temp_copy_deleted : Error< "%sub{select_initialized_entity_kind}0 of type %1 " "invokes deleted constructor">; def err_temp_copy_incomplete : Error< "copying a temporary object of incomplete type %0">; def warn_cxx98_compat_temp_copy : Warning< "%sub{select_initialized_entity_kind}1 " "of type %2 when binding a reference to a temporary would %select{invoke " "an inaccessible constructor|find no viable constructor|find ambiguous " "constructors|invoke a deleted constructor}0 in C++98">, InGroup, DefaultIgnore; def err_selected_explicit_constructor : Error< "chosen constructor is explicit in copy-initialization">; def note_explicit_ctor_deduction_guide_here : Note< "explicit %select{constructor|deduction guide}0 declared here">; // C++11 decltype def err_decltype_in_declarator : Error< "'decltype' cannot be used to name a declaration">; // C++11 auto def warn_cxx98_compat_auto_type_specifier : Warning< "'auto' type specifier is incompatible with C++98">, InGroup, DefaultIgnore; def err_auto_variable_cannot_appear_in_own_initializer : Error< "variable %0 declared with deduced type %1 " "cannot appear in its own initializer">; def err_binding_cannot_appear_in_own_initializer : Error< "binding %0 cannot appear in the initializer of its own " "decomposition declaration">; def err_illegal_decl_array_of_auto : Error< "'%0' declared as array of %1">; def err_new_array_of_auto : Error< "cannot allocate array of 'auto'">; def err_auto_not_allowed : Error< "%select{'auto'|'decltype(auto)'|'__auto_type'|" "use of " "%select{class template|function template|variable template|alias template|" "template template parameter|template}2 %3 requires template arguments; " "argument deduction}0 not allowed " "%select{in function prototype" "|in non-static struct member|in struct member" "|in non-static union member|in union member" "|in non-static class member|in interface member" "|in exception declaration|in template parameter until C++17|in block literal" "|in template argument|in typedef|in type alias|in function return type" "|in conversion function type|here|in lambda parameter" "|in type allocated by 'new'|in K&R-style function parameter" "|in template parameter|in friend declaration}1">; def err_dependent_deduced_tst : Error< "typename specifier refers to " "%select{class template|function template|variable template|alias template|" "template template parameter|template}0 member in %1; " "argument deduction not allowed here">; def err_auto_not_allowed_var_inst : Error< "'auto' variable template instantiation is not allowed">; def err_auto_var_requires_init : Error< "declaration of variable %0 with deduced type %1 requires an initializer">; def err_auto_new_requires_ctor_arg : Error< "new expression for type %0 requires a constructor argument">; def ext_auto_new_list_init : Extension< "ISO C++ standards before C++17 do not allow new expression for " "type %0 to use list-initialization">, InGroup; def err_auto_var_init_no_expression : Error< "initializer for variable %0 with type %1 is empty">; def err_auto_var_init_multiple_expressions : Error< "initializer for variable %0 with type %1 contains multiple expressions">; def err_auto_var_init_paren_braces : Error< "cannot deduce type for variable %1 with type %2 from " "%select{parenthesized|nested}0 initializer list">; def err_auto_new_ctor_multiple_expressions : Error< "new expression for type %0 contains multiple constructor arguments">; def err_auto_missing_trailing_return : Error< "'auto' return without trailing return type; deduced return types are a " "C++14 extension">; def err_deduced_return_type : Error< "deduced return types are a C++14 extension">; def err_trailing_return_without_auto : Error< "function with trailing return type must specify return type 'auto', not %0">; def err_trailing_return_in_parens : Error< "trailing return type may not be nested within parentheses">; def err_auto_var_deduction_failure : Error< "variable %0 with type %1 has incompatible initializer of type %2">; def err_auto_var_deduction_failure_from_init_list : Error< "cannot deduce actual type for variable %0 with type %1 from initializer list">; def err_auto_new_deduction_failure : Error< "new expression for type %0 has incompatible constructor argument of type %1">; def err_auto_inconsistent_deduction : Error< "deduced conflicting types %diff{($ vs $) |}0,1" "for initializer list element type">; def err_auto_different_deductions : Error< "%select{'auto'|'decltype(auto)'|'__auto_type'|template arguments}0 " "deduced as %1 in declaration of %2 and " "deduced as %3 in declaration of %4">; def err_auto_non_deduced_not_alone : Error< "%select{function with deduced return type|" "declaration with trailing return type}0 " "must be the only declaration in its group">; def err_implied_std_initializer_list_not_found : Error< "cannot deduce type of initializer list because std::initializer_list was " "not found; include ">; def err_malformed_std_initializer_list : Error< "std::initializer_list must be a class template with a single type parameter">; def err_auto_init_list_from_c : Error< "cannot use __auto_type with initializer list in C">; def err_auto_bitfield : Error< "cannot pass bit-field as __auto_type initializer in C">; // C++1y decltype(auto) type def err_decltype_auto_invalid : Error< "'decltype(auto)' not allowed here">; def err_decltype_auto_cannot_be_combined : Error< "'decltype(auto)' cannot be combined with other type specifiers">; def err_decltype_auto_function_declarator_not_declaration : Error< "'decltype(auto)' can only be used as a return type " "in a function declaration">; def err_decltype_auto_compound_type : Error< "cannot form %select{pointer to|reference to|array of}0 'decltype(auto)'">; def err_decltype_auto_initializer_list : Error< "cannot deduce 'decltype(auto)' from initializer list">; // C++17 deduced class template specialization types def err_deduced_class_template_compound_type : Error< "cannot %select{form pointer to|form reference to|form array of|" "form function returning|use parentheses when declaring variable with}0 " "deduced class template specialization type">; def err_deduced_non_class_template_specialization_type : Error< "%select{|function template|variable template|alias template|" "template template parameter|template}0 %1 requires template arguments; " "argument deduction only allowed for class templates">; def err_deduced_class_template_ctor_ambiguous : Error< "ambiguous deduction for template arguments of %0">; def err_deduced_class_template_ctor_no_viable : Error< "no viable constructor or deduction guide for deduction of " "template arguments of %0">; def err_deduced_class_template_incomplete : Error< "template %0 has no definition and no %select{|viable }1deduction guides " "for deduction of template arguments">; def err_deduced_class_template_deleted : Error< "class template argument deduction for %0 selected a deleted constructor">; def err_deduced_class_template_explicit : Error< "class template argument deduction for %0 selected an explicit " "%select{constructor|deduction guide}1 for copy-list-initialization">; def err_deduction_guide_no_trailing_return_type : Error< "deduction guide declaration without trailing return type">; def err_deduction_guide_bad_trailing_return_type : Error< "deduced type %1 of deduction guide is not %select{|written as }2" "a specialization of template %0">; def err_deduction_guide_with_complex_decl : Error< "cannot specify any part of a return type in the " "declaration of a deduction guide">; def err_deduction_guide_invalid_specifier : Error< "deduction guide cannot be declared '%0'">; def err_deduction_guide_name_not_class_template : Error< "cannot specify deduction guide for " "%select{|function template|variable template|alias template|" "template template parameter|dependent template name}0 %1">; def err_deduction_guide_wrong_scope : Error< "deduction guide must be declared in the same scope as template %q0">; def err_deduction_guide_defines_function : Error< "deduction guide cannot have a function definition">; def err_deduction_guide_explicit_mismatch : Error< "deduction guide is %select{not |}0declared 'explicit' but " "previous declaration was%select{ not|}0">; def err_deduction_guide_specialized : Error<"deduction guide cannot be " "%select{explicitly instantiated|explicitly specialized}0">; def err_deduction_guide_template_not_deducible : Error< "deduction guide template contains " "%select{a template parameter|template parameters}0 that cannot be " "deduced">; def err_deduction_guide_wrong_access : Error< "deduction guide has different access from the corresponding " "member template">; def note_deduction_guide_template_access : Note< "member template declared %0 here">; def note_deduction_guide_access : Note< "deduction guide declared %0 by intervening access specifier">; def warn_cxx14_compat_class_template_argument_deduction : Warning< "class template argument deduction is incompatible with C++ standards " "before C++17%select{|; for compatibility, use explicit type name %1}0">, InGroup, DefaultIgnore; // C++14 deduced return types def err_auto_fn_deduction_failure : Error< "cannot deduce return type %0 from returned value of type %1">; def err_auto_fn_different_deductions : Error< "'%select{auto|decltype(auto)}0' in return type deduced as %1 here but " "deduced as %2 in earlier return statement">; def err_auto_fn_used_before_defined : Error< "function %0 with deduced return type cannot be used before it is defined">; def err_auto_fn_no_return_but_not_auto : Error< "cannot deduce return type %0 for function with no return statements">; def err_auto_fn_return_void_but_not_auto : Error< "cannot deduce return type %0 from omitted return expression">; def err_auto_fn_return_init_list : Error< "cannot deduce return type from initializer list">; def err_auto_fn_virtual : Error< "function with deduced return type cannot be virtual">; def warn_cxx11_compat_deduced_return_type : Warning< "return type deduction is incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; // C++11 override control def override_keyword_only_allowed_on_virtual_member_functions : Error< "only virtual member functions can be marked '%0'">; def override_keyword_hides_virtual_member_function : Error< "non-virtual member function marked '%0' hides virtual member " "%select{function|functions}1">; def err_function_marked_override_not_overriding : Error< "%0 marked 'override' but does not override any member functions">; def warn_destructor_marked_not_override_overriding : Warning < "%0 overrides a destructor but is not marked 'override'">, InGroup, DefaultIgnore; def warn_function_marked_not_override_overriding : Warning < "%0 overrides a member function but is not marked 'override'">, InGroup; def err_class_marked_final_used_as_base : Error< "base %0 is marked '%select{final|sealed}1'">; def warn_abstract_final_class : Warning< "abstract class is marked '%select{final|sealed}0'">, InGroup; // C++11 attributes def err_repeat_attribute : Error<"%0 attribute cannot be repeated">; // C++11 final def err_final_function_overridden : Error< "declaration of %0 overrides a '%select{final|sealed}1' function">; // C++11 scoped enumerations def err_enum_invalid_underlying : Error< "non-integral type %0 is an invalid underlying type">; def err_enumerator_too_large : Error< "enumerator value is not representable in the underlying type %0">; def ext_enumerator_too_large : Extension< "enumerator value is not representable in the underlying type %0">, InGroup; def err_enumerator_wrapped : Error< "enumerator value %0 is not representable in the underlying type %1">; def err_enum_redeclare_type_mismatch : Error< "enumeration redeclared with different underlying type %0 (was %1)">; def err_enum_redeclare_fixed_mismatch : Error< "enumeration previously declared with %select{non|}0fixed underlying type">; def err_enum_redeclare_scoped_mismatch : Error< "enumeration previously declared as %select{un|}0scoped">; def err_enum_class_reference : Error< "reference to %select{|scoped }0enumeration must use 'enum' " "not 'enum class'">; def err_only_enums_have_underlying_types : Error< "only enumeration types have underlying types">; def err_underlying_type_of_incomplete_enum : Error< "cannot determine underlying type of incomplete enumeration type %0">; // C++11 delegating constructors def err_delegating_ctor : Error< "delegating constructors are permitted only in C++11">; def warn_cxx98_compat_delegating_ctor : Warning< "delegating constructors are incompatible with C++98">, InGroup, DefaultIgnore; def err_delegating_initializer_alone : Error< "an initializer for a delegating constructor must appear alone">; def warn_delegating_ctor_cycle : Warning< "constructor for %0 creates a delegation cycle">, DefaultError, InGroup; def note_it_delegates_to : Note<"it delegates to">; def note_which_delegates_to : Note<"which delegates to">; // C++11 range-based for loop def err_for_range_decl_must_be_var : Error< "for range declaration must declare a variable">; def err_for_range_storage_class : Error< "loop variable %0 may not be declared %select{'extern'|'static'|" "'__private_extern__'|'auto'|'register'|'constexpr'}1">; def err_type_defined_in_for_range : Error< "types may not be defined in a for range declaration">; def err_for_range_deduction_failure : Error< "cannot use type %0 as a range">; def err_for_range_incomplete_type : Error< "cannot use incomplete type %0 as a range">; def err_for_range_iter_deduction_failure : Error< "cannot use type %0 as an iterator">; def ext_for_range_begin_end_types_differ : ExtWarn< "'begin' and 'end' returning different types (%0 and %1) is a C++17 extension">, InGroup; def warn_for_range_begin_end_types_differ : Warning< "'begin' and 'end' returning different types (%0 and %1) is incompatible " "with C++ standards before C++17">, InGroup, DefaultIgnore; def note_in_for_range: Note< "when looking up '%select{begin|end}0' function for range expression " "of type %1">; def err_for_range_invalid: Error< "invalid range expression of type %0; no viable '%select{begin|end}1' " "function available">; def note_for_range_member_begin_end_ignored : Note< "member is not a candidate because range type %0 has no '%select{end|begin}1' member">; def err_range_on_array_parameter : Error< "cannot build range expression with array function parameter %0 since " "parameter with array type %1 is treated as pointer type %2">; def err_for_range_dereference : Error< "invalid range expression of type %0; did you mean to dereference it " "with '*'?">; def note_for_range_invalid_iterator : Note < "in implicit call to 'operator%select{!=|*|++}0' for iterator of type %1">; def note_for_range_begin_end : Note< "selected '%select{begin|end}0' %select{function|template }1%2 with iterator type %3">; def warn_for_range_const_reference_copy : Warning< "loop variable %0 " "%diff{has type $ but is initialized with type $" "| is initialized with a value of a different type}1,2 resulting in a copy">, InGroup, DefaultIgnore; def note_use_type_or_non_reference : Note< "use non-reference type %0 to keep the copy or type %1 to prevent copying">; def warn_for_range_variable_always_copy : Warning< "loop variable %0 is always a copy because the range of type %1 does not " "return a reference">, InGroup, DefaultIgnore; def note_use_non_reference_type : Note<"use non-reference type %0">; def warn_for_range_copy : Warning< "loop variable %0 of type %1 creates a copy from type %2">, InGroup, DefaultIgnore; def note_use_reference_type : Note<"use reference type %0 to prevent copying">; def err_objc_for_range_init_stmt : Error< "initialization statement is not supported when iterating over Objective-C " "collection">; // C++11 constexpr def warn_cxx98_compat_constexpr : Warning< "'constexpr' specifier is incompatible with C++98">, InGroup, DefaultIgnore; // FIXME: Maybe this should also go in -Wc++14-compat? def warn_cxx14_compat_constexpr_not_const : Warning< "'constexpr' non-static member function will not be implicitly 'const' " "in C++14; add 'const' to avoid a change in behavior">, InGroup>; def err_invalid_constexpr : Error< "%select{function parameter|typedef|non-static data member}0 " "cannot be constexpr">; def err_invalid_constexpr_member : Error<"non-static data member cannot be " "constexpr%select{; did you intend to make it %select{const|static}0?|}1">; def err_constexpr_tag : Error< "%select{class|struct|interface|union|enum}0 cannot be marked constexpr">; def err_constexpr_dtor : Error<"destructor cannot be marked constexpr">; def err_constexpr_no_declarators : Error< "constexpr can only be used in variable and function declarations">; def err_invalid_constexpr_var_decl : Error< "constexpr variable declaration must be a definition">; def err_constexpr_static_mem_var_requires_init : Error< "declaration of constexpr static data member %0 requires an initializer">; def err_constexpr_var_non_literal : Error< "constexpr variable cannot have non-literal type %0">; def err_constexpr_var_requires_const_init : Error< "constexpr variable %0 must be initialized by a constant expression">; def err_constexpr_redecl_mismatch : Error< "%select{non-constexpr declaration of %0 follows constexpr declaration" "|constexpr declaration of %0 follows non-constexpr declaration}1">; def err_constexpr_virtual : Error<"virtual function cannot be constexpr">; def err_constexpr_virtual_base : Error< "constexpr %select{member function|constructor}0 not allowed in " "%select{struct|interface|class}1 with virtual base " "%plural{1:class|:classes}2">; def note_non_literal_incomplete : Note< "incomplete type %0 is not a literal type">; def note_non_literal_virtual_base : Note<"%select{struct|interface|class}0 " "with virtual base %plural{1:class|:classes}1 is not a literal type">; def note_constexpr_virtual_base_here : Note<"virtual base class declared here">; def err_constexpr_non_literal_return : Error< "constexpr function's return type %0 is not a literal type">; def err_constexpr_non_literal_param : Error< "constexpr %select{function|constructor}1's %ordinal0 parameter type %2 is " "not a literal type">; def err_constexpr_body_invalid_stmt : Error< "statement not allowed in constexpr %select{function|constructor}0">; def ext_constexpr_body_invalid_stmt : ExtWarn< "use of this statement in a constexpr %select{function|constructor}0 " "is a C++14 extension">, InGroup; def warn_cxx11_compat_constexpr_body_invalid_stmt : Warning< "use of this statement in a constexpr %select{function|constructor}0 " "is incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; def ext_constexpr_body_invalid_stmt_cxx2a : ExtWarn< "use of this statement in a constexpr %select{function|constructor}0 " "is a C++2a extension">, InGroup; def warn_cxx17_compat_constexpr_body_invalid_stmt : Warning< "use of this statement in a constexpr %select{function|constructor}0 " "is incompatible with C++ standards before C++2a">, InGroup, DefaultIgnore; def ext_constexpr_type_definition : ExtWarn< "type definition in a constexpr %select{function|constructor}0 " "is a C++14 extension">, InGroup; def warn_cxx11_compat_constexpr_type_definition : Warning< "type definition in a constexpr %select{function|constructor}0 " "is incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; def err_constexpr_vla : Error< "variably-modified type %0 cannot be used in a constexpr " "%select{function|constructor}1">; def ext_constexpr_local_var : ExtWarn< "variable declaration in a constexpr %select{function|constructor}0 " "is a C++14 extension">, InGroup; def warn_cxx11_compat_constexpr_local_var : Warning< "variable declaration in a constexpr %select{function|constructor}0 " "is incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; def err_constexpr_local_var_static : Error< "%select{static|thread_local}1 variable not permitted in a constexpr " "%select{function|constructor}0">; def err_constexpr_local_var_non_literal_type : Error< "variable of non-literal type %1 cannot be defined in a constexpr " "%select{function|constructor}0">; def err_constexpr_local_var_no_init : Error< "variables defined in a constexpr %select{function|constructor}0 must be " "initialized">; def ext_constexpr_function_never_constant_expr : ExtWarn< "constexpr %select{function|constructor}0 never produces a " "constant expression">, InGroup>, DefaultError; def err_attr_cond_never_constant_expr : Error< "%0 attribute expression never produces a constant expression">; def err_diagnose_if_invalid_diagnostic_type : Error< "invalid diagnostic type for 'diagnose_if'; use \"error\" or \"warning\" " "instead">; def err_constexpr_body_no_return : Error< "no return statement in constexpr function">; def err_constexpr_return_missing_expr : Error< "non-void constexpr function %0 should return a value">; def warn_cxx11_compat_constexpr_body_no_return : Warning< "constexpr function with no return statements is incompatible with C++ " "standards before C++14">, InGroup, DefaultIgnore; def ext_constexpr_body_multiple_return : ExtWarn< "multiple return statements in constexpr function is a C++14 extension">, InGroup; def warn_cxx11_compat_constexpr_body_multiple_return : Warning< "multiple return statements in constexpr function " "is incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; def note_constexpr_body_previous_return : Note< "previous return statement is here">; def err_constexpr_function_try_block : Error< "function try block not allowed in constexpr %select{function|constructor}0">; // c++2a function try blocks in constexpr def ext_constexpr_function_try_block_cxx2a : ExtWarn< "function try block in constexpr %select{function|constructor}0 is " "a C++2a extension">, InGroup; def warn_cxx17_compat_constexpr_function_try_block : Warning< "function try block in constexpr %select{function|constructor}0 is " "incompatible with C++ standards before C++2a">, InGroup, DefaultIgnore; def err_constexpr_union_ctor_no_init : Error< "constexpr union constructor does not initialize any member">; def err_constexpr_ctor_missing_init : Error< "constexpr constructor must initialize all members">; def note_constexpr_ctor_missing_init : Note< "member not initialized by constructor">; def note_non_literal_no_constexpr_ctors : Note< "%0 is not literal because it is not an aggregate and has no constexpr " "constructors other than copy or move constructors">; def note_non_literal_base_class : Note< "%0 is not literal because it has base class %1 of non-literal type">; def note_non_literal_field : Note< "%0 is not literal because it has data member %1 of " "%select{non-literal|volatile}3 type %2">; def note_non_literal_user_provided_dtor : Note< "%0 is not literal because it has a user-provided destructor">; def note_non_literal_nontrivial_dtor : Note< "%0 is not literal because it has a non-trivial destructor">; def note_non_literal_lambda : Note< "lambda closure types are non-literal types before C++17">; def warn_private_extern : Warning< "use of __private_extern__ on a declaration may not produce external symbol " "private to the linkage unit and is deprecated">, InGroup; def note_private_extern : Note< "use __attribute__((visibility(\"hidden\"))) attribute instead">; // C++ Concepts TS def err_concept_wrong_decl_kind : Error< "'concept' can only appear on the definition of a function template or variable template">; def err_concept_decls_may_only_appear_in_namespace_scope : Error< "concept declarations may only appear in namespace scope">; def err_function_concept_not_defined : Error< "function concept declaration must be a definition">; def err_var_concept_not_initialized : Error< "variable concept declaration must be initialized">; def err_function_concept_exception_spec : Error< "function concept cannot have exception specification">; def err_concept_decl_invalid_specifiers : Error< "%select{variable|function}0 concept cannot be declared " "'%select{thread_local|inline|friend|constexpr}1'">; def err_function_concept_with_params : Error< "function concept cannot have any parameters">; def err_function_concept_bool_ret : Error< "declared return type of function concept must be 'bool'">; def err_variable_concept_bool_decl : Error< "declared type of variable concept must be 'bool'">; def err_concept_specified_specialization : Error< "'concept' cannot be applied on an " "%select{explicit instantiation|explicit specialization|partial specialization}0">; def err_concept_specialized : Error< "%select{function|variable}0 concept cannot be " "%select{explicitly instantiated|explicitly specialized|partially specialized}1">; def err_template_different_associated_constraints : Error< "associated constraints differ in template redeclaration">; // C++11 char16_t/char32_t def warn_cxx98_compat_unicode_type : Warning< "'%0' type specifier is incompatible with C++98">, InGroup, DefaultIgnore; def warn_cxx17_compat_unicode_type : Warning< "'char8_t' type specifier is incompatible with C++ standards before C++20">, InGroup, DefaultIgnore; // __make_integer_seq def err_integer_sequence_negative_length : Error< "integer sequences must have non-negative sequence length">; def err_integer_sequence_integral_element_type : Error< "integer sequences must have integral element type">; // __type_pack_element def err_type_pack_element_out_of_bounds : Error< "a parameter pack may not be accessed at an out of bounds index">; // Objective-C++ def err_objc_decls_may_only_appear_in_global_scope : Error< "Objective-C declarations may only appear in global scope">; def warn_auto_var_is_id : Warning< "'auto' deduced as 'id' in declaration of %0">, InGroup>; // Attributes def err_nsobject_attribute : Error< "'NSObject' attribute is for pointer types only">; def err_attributes_are_not_compatible : Error< "%0 and %1 attributes are not compatible">; def err_attribute_wrong_number_arguments : Error< "%0 attribute %plural{0:takes no arguments|1:takes one argument|" ":requires exactly %1 arguments}1">; def err_attribute_too_many_arguments : Error< "%0 attribute takes no more than %1 argument%s1">; def err_attribute_too_few_arguments : Error< "%0 attribute takes at least %1 argument%s1">; def err_attribute_invalid_vector_type : Error<"invalid vector element type %0">; def err_attribute_bad_neon_vector_size : Error< "Neon vector size must be 64 or 128 bits">; def err_attribute_requires_positive_integer : Error< "%0 attribute requires a %select{positive|non-negative}1 " "integral compile time constant expression">; def err_attribute_requires_opencl_version : Error< "%0 attribute requires OpenCL version %1%select{| or above}2">; def warn_unsupported_target_attribute : Warning<"%select{unsupported|duplicate}0%select{| architecture}1 '%2' in" " the 'target' attribute string; 'target' attribute ignored">, InGroup; def err_attribute_unsupported : Error<"%0 attribute is not supported for this target">; // The err_*_attribute_argument_not_int are separate because they're used by // VerifyIntegerConstantExpression. def err_aligned_attribute_argument_not_int : Error< "'aligned' attribute requires integer constant">; def err_align_value_attribute_argument_not_int : Error< "'align_value' attribute requires integer constant">; def err_alignas_attribute_wrong_decl_type : Error< "%0 attribute cannot be applied to a %select{function parameter|" "variable with 'register' storage class|'catch' variable|bit-field}1">; def err_alignas_missing_on_definition : Error< "%0 must be specified on definition if it is specified on any declaration">; def note_alignas_on_declaration : Note<"declared with %0 attribute here">; def err_alignas_mismatch : Error< "redeclaration has different alignment requirement (%1 vs %0)">; def err_alignas_underaligned : Error< "requested alignment is less than minimum alignment of %1 for type %0">; def err_attribute_argument_n_type : Error< "%0 attribute requires parameter %1 to be %select{int or bool|an integer " "constant|a string|an identifier}2">; def err_attribute_argument_type : Error< "%0 attribute requires %select{int or bool|an integer " "constant|a string|an identifier}1">; def err_attribute_argument_outof_range : Error< "%0 attribute requires integer constant between %1 and %2 inclusive">; def err_init_priority_object_attr : Error< "can only use 'init_priority' attribute on file-scope definitions " "of objects of class type">; def err_attribute_argument_vec_type_hint : Error< "invalid attribute argument %0 - expecting a vector or vectorizable scalar type">; def err_attribute_argument_out_of_bounds : Error< "%0 attribute parameter %1 is out of bounds">; def err_attribute_only_once_per_parameter : Error< "%0 attribute can only be applied once per parameter">; def err_mismatched_uuid : Error<"uuid does not match previous declaration">; def note_previous_uuid : Note<"previous uuid specified here">; def warn_attribute_pointers_only : Warning< "%0 attribute only applies to%select{| constant}1 pointer arguments">, InGroup; def err_attribute_pointers_only : Error; def err_attribute_integers_only : Error< "%0 attribute argument may only refer to a function parameter of integer " "type">; def warn_attribute_return_pointers_only : Warning< "%0 attribute only applies to return values that are pointers">, InGroup; def warn_attribute_return_pointers_refs_only : Warning< "%0 attribute only applies to return values that are pointers or references">, InGroup; def warn_attribute_pointer_or_reference_only : Warning< "%0 attribute only applies to a pointer or reference (%1 is invalid)">, InGroup; def err_attribute_no_member_pointers : Error< "%0 attribute cannot be used with pointers to members">; def err_attribute_invalid_implicit_this_argument : Error< "%0 attribute is invalid for the implicit this argument">; def err_ownership_type : Error< "%0 attribute only applies to %select{pointer|integer}1 arguments">; def err_ownership_returns_index_mismatch : Error< "'ownership_returns' attribute index does not match; here it is %0">; def note_ownership_returns_index_mismatch : Note< "declared with index %0 here">; def err_format_strftime_third_parameter : Error< "strftime format attribute requires 3rd parameter to be 0">; def err_format_attribute_requires_variadic : Error< "format attribute requires variadic function">; def err_format_attribute_not : Error<"format argument not %0">; def err_format_attribute_result_not : Error<"function does not return %0">; def err_format_attribute_implicit_this_format_string : Error< "format attribute cannot specify the implicit this argument as the format " "string">; def err_init_method_bad_return_type : Error< "init methods must return an object pointer type, not %0">; def err_attribute_invalid_size : Error< "vector size not an integral multiple of component size">; def err_attribute_zero_size : Error<"zero vector size">; def err_attribute_size_too_large : Error<"vector size too large">; def err_typecheck_vector_not_convertable_implict_truncation : Error< "cannot convert between %select{scalar|vector}0 type %1 and vector type" " %2 as implicit conversion would cause truncation">; def err_typecheck_vector_not_convertable : Error< "cannot convert between vector values of different size (%0 and %1)">; def err_typecheck_vector_not_convertable_non_scalar : Error< "cannot convert between vector and non-scalar values (%0 and %1)">; def err_typecheck_vector_lengths_not_equal : Error< "vector operands do not have the same number of elements (%0 and %1)">; def warn_typecheck_vector_element_sizes_not_equal : Warning< "vector operands do not have the same elements sizes (%0 and %1)">, InGroup>, DefaultError; def err_ext_vector_component_exceeds_length : Error< "vector component access exceeds type %0">; def err_ext_vector_component_name_illegal : Error< "illegal vector component name '%0'">; def err_attribute_address_space_negative : Error< "address space is negative">; def err_attribute_address_space_too_high : Error< "address space is larger than the maximum supported (%0)">; def err_attribute_address_multiple_qualifiers : Error< "multiple address spaces specified for type">; def warn_attribute_address_multiple_identical_qualifiers : Warning< "multiple identical address spaces specified for type">, InGroup; def err_attribute_address_function_type : Error< "function type may not be qualified with an address space">; def err_as_qualified_auto_decl : Error< "automatic variable qualified with an%select{| invalid}0 address space">; def err_arg_with_address_space : Error< "parameter may not be qualified with an address space">; def err_field_with_address_space : Error< "field may not be qualified with an address space">; def err_compound_literal_with_address_space : Error< "compound literal in function scope may not be qualified with an address space">; def err_address_space_mismatch_templ_inst : Error< "conflicting address space qualifiers are provided between types %0 and %1">; def err_attr_objc_ownership_redundant : Error< "the type %0 is already explicitly ownership-qualified">; def err_invalid_nsnumber_type : Error< "%0 is not a valid literal type for NSNumber">; def err_objc_illegal_boxed_expression_type : Error< "illegal type %0 used in a boxed expression">; def err_objc_non_trivially_copyable_boxed_expression_type : Error< "non-trivially copyable type %0 cannot be used in a boxed expression">; def err_objc_incomplete_boxed_expression_type : Error< "incomplete type %0 used in a boxed expression">; def err_undeclared_objc_literal_class : Error< "definition of class %0 must be available to use Objective-C " "%select{array literals|dictionary literals|numeric literals|boxed expressions|" "string literals}1">; def err_undeclared_boxing_method : Error< "declaration of %0 is missing in %1 class">; def err_objc_literal_method_sig : Error< "literal construction method %0 has incompatible signature">; def note_objc_literal_method_param : Note< "%select{first|second|third}0 parameter has unexpected type %1 " "(should be %2)">; def note_objc_literal_method_return : Note< "method returns unexpected type %0 (should be an object type)">; def err_invalid_collection_element : Error< "collection element of type %0 is not an Objective-C object">; def err_box_literal_collection : Error< "%select{string|character|boolean|numeric}0 literal must be prefixed by '@' " "in a collection">; def warn_objc_literal_comparison : Warning< "direct comparison of %select{an array literal|a dictionary literal|" "a numeric literal|a boxed expression|}0 has undefined behavior">, InGroup; def err_missing_atsign_prefix : Error< "string literal must be prefixed by '@' ">; def warn_objc_string_literal_comparison : Warning< "direct comparison of a string literal has undefined behavior">, InGroup; def warn_concatenated_nsarray_literal : Warning< "concatenated NSString literal for an NSArray expression - " "possibly missing a comma">, InGroup; def note_objc_literal_comparison_isequal : Note< "use 'isEqual:' instead">; def warn_objc_collection_literal_element : Warning< "object of type %0 is not compatible with " "%select{array element type|dictionary key type|dictionary value type}1 %2">, InGroup; def err_swift_param_attr_not_swiftcall : Error< "'%0' parameter can only be used with swiftcall calling convention">; def err_swift_indirect_result_not_first : Error< "'swift_indirect_result' parameters must be first parameters of function">; def err_swift_error_result_not_after_swift_context : Error< "'swift_error_result' parameter must follow 'swift_context' parameter">; def err_swift_abi_parameter_wrong_type : Error< "'%0' parameter must have pointer%select{| to unqualified pointer}1 type; " "type here is %2">; def err_attribute_argument_invalid : Error< "%0 attribute argument is invalid: %select{max must be 0 since min is 0|" "min must not be greater than max}1">; def err_attribute_argument_is_zero : Error< "%0 attribute must be greater than 0">; def warn_attribute_argument_n_negative : Warning< "%0 attribute parameter %1 is negative and will be ignored">, InGroup; def err_property_function_in_objc_container : Error< "use of Objective-C property in function nested in Objective-C " "container not supported, move function outside its container">; let CategoryName = "Cocoa API Issue" in { def warn_objc_redundant_literal_use : Warning< "using %0 with a literal is redundant">, InGroup; } def err_attr_tlsmodel_arg : Error<"tls_model must be \"global-dynamic\", " "\"local-dynamic\", \"initial-exec\" or \"local-exec\"">; def err_tls_var_aligned_over_maximum : Error< "alignment (%0) of thread-local variable %1 is greater than the maximum supported " "alignment (%2) for a thread-local variable on this target">; def err_only_annotate_after_access_spec : Error< "access specifier can only have annotation attributes">; def err_attribute_section_invalid_for_target : Error< "argument to %select{'code_seg'|'section'}1 attribute is not valid for this target: %0">; def warn_mismatched_section : Warning< "%select{codeseg|section}0 does not match previous declaration">, InGroup
; def warn_attribute_section_on_redeclaration : Warning< "section attribute is specified on redeclared variable">, InGroup
; def err_mismatched_code_seg_base : Error< "derived class must specify the same code segment as its base classes">; def err_mismatched_code_seg_override : Error< "overriding virtual function must specify the same code segment as its overridden function">; def err_conflicting_codeseg_attribute : Error< "conflicting code segment specifiers">; def warn_duplicate_codeseg_attribute : Warning< "duplicate code segment specifiers">, InGroup
; def err_anonymous_property: Error< "anonymous property is not supported">; def err_property_is_variably_modified : Error< "property %0 has a variably modified type">; def err_no_accessor_for_property : Error< "no %select{getter|setter}0 defined for property %1">; def err_cannot_find_suitable_accessor : Error< "cannot find suitable %select{getter|setter}0 for property %1">; def warn_alloca_align_alignof : Warning< "second argument to __builtin_alloca_with_align is supposed to be in bits">, InGroup>; def err_alignment_too_small : Error< "requested alignment must be %0 or greater">; def err_alignment_too_big : Error< "requested alignment must be %0 or smaller">; def err_alignment_not_power_of_two : Error< "requested alignment is not a power of 2">; def err_alignment_dependent_typedef_name : Error< "requested alignment is dependent but declaration is not dependent">; def err_attribute_aligned_too_great : Error< "requested alignment must be %0 bytes or smaller">; def warn_redeclaration_without_attribute_prev_attribute_ignored : Warning< "%q0 redeclared without %1 attribute: previous %1 ignored">, InGroup; def warn_redeclaration_without_import_attribute : Warning< "%q0 redeclared without 'dllimport' attribute: 'dllexport' attribute added">, InGroup; def warn_dllimport_dropped_from_inline_function : Warning< "%q0 redeclared inline; %1 attribute ignored">, InGroup; def warn_attribute_ignored : Warning<"%0 attribute ignored">, InGroup; def warn_attribute_ignored_on_inline : Warning<"%0 attribute ignored on inline function">, InGroup; def warn_nocf_check_attribute_ignored : Warning<"'nocf_check' attribute ignored; use -fcf-protection to enable the attribute">, InGroup; def warn_attribute_after_definition_ignored : Warning< "attribute %0 after definition is ignored">, InGroup; def warn_cxx11_gnu_attribute_on_type : Warning< "attribute %0 ignored, because it cannot be applied to a type">, InGroup; def warn_unhandled_ms_attribute_ignored : Warning< "__declspec attribute %0 is not supported">, InGroup; def err_decl_attribute_invalid_on_stmt : Error< "%0 attribute cannot be applied to a statement">; def err_stmt_attribute_invalid_on_decl : Error< "%0 attribute cannot be applied to a declaration">; def warn_declspec_attribute_ignored : Warning< "attribute %0 is ignored, place it after " "\"%select{class|struct|interface|union|enum}1\" to apply attribute to " "type declaration">, InGroup; def warn_attribute_precede_definition : Warning< "attribute declaration must precede definition">, InGroup; def warn_attribute_void_function_method : Warning< "attribute %0 cannot be applied to " "%select{functions|Objective-C method}1 without return value">, InGroup; def warn_attribute_weak_on_field : Warning< "__weak attribute cannot be specified on a field declaration">, InGroup; def warn_gc_attribute_weak_on_local : Warning< "Objective-C GC does not allow weak variables on the stack">, InGroup; def warn_nsobject_attribute : Warning< "'NSObject' attribute may be put on a typedef only; attribute is ignored">, InGroup; def warn_independentclass_attribute : Warning< "'objc_independent_class' attribute may be put on a typedef only; " "attribute is ignored">, InGroup; def warn_ptr_independentclass_attribute : Warning< "'objc_independent_class' attribute may be put on Objective-C object " "pointer type only; attribute is ignored">, InGroup; def warn_attribute_weak_on_local : Warning< "__weak attribute cannot be specified on an automatic variable when ARC " "is not enabled">, InGroup; def warn_weak_identifier_undeclared : Warning< "weak identifier %0 never declared">; def err_attribute_weak_static : Error< "weak declaration cannot have internal linkage">; def err_attribute_selectany_non_extern_data : Error< "'selectany' can only be applied to data items with external linkage">; def err_declspec_thread_on_thread_variable : Error< "'__declspec(thread)' applied to variable that already has a " "thread-local storage specifier">; def err_attribute_dll_not_extern : Error< "%q0 must have external linkage when declared %q1">; def err_attribute_dll_thread_local : Error< "%q0 cannot be thread local when declared %q1">; def err_attribute_dll_lambda : Error< "lambda cannot be declared %0">; def warn_attribute_invalid_on_definition : Warning< "'%0' attribute cannot be specified on a definition">, InGroup; def err_attribute_dll_redeclaration : Error< "redeclaration of %q0 cannot add %q1 attribute">; def warn_attribute_dll_redeclaration : Warning< "redeclaration of %q0 should not add %q1 attribute">, InGroup>; def err_attribute_dllimport_function_definition : Error< "dllimport cannot be applied to non-inline function definition">; def err_attribute_dll_deleted : Error< "attribute %q0 cannot be applied to a deleted function">; def err_attribute_dllimport_data_definition : Error< "definition of dllimport data">; def err_attribute_dllimport_static_field_definition : Error< "definition of dllimport static field not allowed">; def warn_attribute_dllimport_static_field_definition : Warning< "definition of dllimport static field">, InGroup>; def warn_attribute_dllexport_explicit_instantiation_decl : Warning< "explicit instantiation declaration should not be 'dllexport'">, InGroup>; def warn_invalid_initializer_from_system_header : Warning< "invalid constructor form class in system header, should not be explicit">, InGroup>; def note_used_in_initialization_here : Note<"used in initialization here">; def err_attribute_dll_member_of_dll_class : Error< "attribute %q0 cannot be applied to member of %q1 class">; def warn_attribute_dll_instantiated_base_class : Warning< "propagating dll attribute to %select{already instantiated|explicitly specialized}0 " "base class template without dll attribute is not supported">, InGroup>, DefaultIgnore; def err_attribute_dll_ambiguous_default_ctor : Error< "'__declspec(dllexport)' cannot be applied to more than one default constructor in %0">; def err_attribute_weakref_not_static : Error< "weakref declaration must have internal linkage">; def err_attribute_weakref_not_global_context : Error< "weakref declaration of %0 must be in a global context">; def err_attribute_weakref_without_alias : Error< "weakref declaration of %0 must also have an alias attribute">; def err_alias_not_supported_on_darwin : Error < "aliases are not supported on darwin">; def warn_attribute_wrong_decl_type_str : Warning< "%0 attribute only applies to %1">, InGroup; def err_attribute_wrong_decl_type_str : Error< warn_attribute_wrong_decl_type_str.Text>; def warn_attribute_wrong_decl_type : Warning< "%0 attribute only applies to %select{" "functions" "|unions" "|variables and functions" "|functions and methods" "|functions, methods and blocks" "|functions, methods, and parameters" "|variables" "|variables and fields" "|variables, data members and tag types" "|types and namespaces" "|variables, functions and classes" "|kernel functions" "|non-K&R-style functions}1">, InGroup; def err_attribute_wrong_decl_type : Error; def warn_type_attribute_wrong_type : Warning< "'%0' only applies to %select{function|pointer|" "Objective-C object or block pointer}1 types; type here is %2">, InGroup; def warn_incomplete_encoded_type : Warning< "encoding of %0 type is incomplete because %1 component has unknown encoding">, InGroup>; def warn_gnu_inline_attribute_requires_inline : Warning< "'gnu_inline' attribute requires function to be marked 'inline'," " attribute ignored">, InGroup; def err_attribute_vecreturn_only_vector_member : Error< "the vecreturn attribute can only be used on a class or structure with one member, which must be a vector">; def err_attribute_vecreturn_only_pod_record : Error< "the vecreturn attribute can only be used on a POD (plain old data) class or structure (i.e. no virtual functions)">; def err_cconv_change : Error< "function declared '%0' here was previously declared " "%select{'%2'|without calling convention}1">; def warn_cconv_ignored : Warning< "calling convention %0 ignored for this target">, InGroup; def err_cconv_knr : Error< "function with no prototype cannot use the %0 calling convention">; def warn_cconv_knr : Warning< err_cconv_knr.Text>, InGroup>; def err_cconv_varargs : Error< "variadic function cannot use %0 calling convention">; def warn_cconv_varargs : Warning< "%0 calling convention ignored on variadic function">, InGroup; def warn_cconv_structors : Warning< "%0 calling convention ignored on constructor/destructor">, InGroup; def err_regparm_mismatch : Error<"function declared with regparm(%0) " "attribute was previously declared " "%plural{0:without the regparm|:with the regparm(%1)}1 attribute">; def err_function_attribute_mismatch : Error< "function declared with %0 attribute " "was previously declared without the %0 attribute">; def err_objc_precise_lifetime_bad_type : Error< "objc_precise_lifetime only applies to retainable types; type here is %0">; def warn_objc_precise_lifetime_meaningless : Error< "objc_precise_lifetime is not meaningful for " "%select{__unsafe_unretained|__autoreleasing}0 objects">; def err_invalid_pcs : Error<"invalid PCS type">; def warn_attribute_not_on_decl : Warning< "%0 attribute ignored when parsing type">, InGroup; def err_base_specifier_attribute : Error< "%0 attribute cannot be applied to a base specifier">; def err_invalid_attribute_on_virtual_function : Error< "%0 attribute cannot be applied to virtual functions">; def ext_cannot_use_trivial_abi : ExtWarn< "'trivial_abi' cannot be applied to %0">, InGroup; // Availability attribute def warn_availability_unknown_platform : Warning< "unknown platform %0 in availability macro">, InGroup; def warn_availability_version_ordering : Warning< "feature cannot be %select{introduced|deprecated|obsoleted}0 in %1 version " "%2 before it was %select{introduced|deprecated|obsoleted}3 in version %4; " "attribute ignored">, InGroup; def warn_mismatched_availability: Warning< "availability does not match previous declaration">, InGroup; def warn_mismatched_availability_override : Warning< "%select{|overriding }4method %select{introduced after|" "deprecated before|obsoleted before}0 " "%select{the protocol method it implements|overridden method}4 " "on %1 (%2 vs. %3)">, InGroup; def warn_mismatched_availability_override_unavail : Warning< "%select{|overriding }1method cannot be unavailable on %0 when " "%select{the protocol method it implements|its overridden method}1 is " "available">, InGroup; def warn_availability_on_static_initializer : Warning< "ignoring availability attribute %select{on '+load' method|" "with constructor attribute|with destructor attribute}0">, InGroup; def note_overridden_method : Note< "overridden method is here">; def warn_availability_swift_unavailable_deprecated_only : Warning< "only 'unavailable' and 'deprecated' are supported for Swift availability">, InGroup; def note_protocol_method : Note< "protocol method is here">; def warn_unguarded_availability : Warning<"%0 is only available on %1 %2 or newer">, InGroup, DefaultIgnore; def warn_unguarded_availability_new : Warning, InGroup; def note_decl_unguarded_availability_silence : Note< "annotate %select{%1|anonymous %1}0 with an availability attribute to silence this warning">; def note_unguarded_available_silence : Note< "enclose %0 in %select{an @available|a __builtin_available}1 check to silence" " this warning">; def warn_at_available_unchecked_use : Warning< "%select{@available|__builtin_available}0 does not guard availability here; " "use if (%select{@available|__builtin_available}0) instead">, InGroup>; // Thread Safety Attributes def warn_invalid_capability_name : Warning< "invalid capability name '%0'; capability name must be 'mutex' or 'role'">, InGroup, DefaultIgnore; def warn_thread_attribute_ignored : Warning< "ignoring %0 attribute because its argument is invalid">, InGroup, DefaultIgnore; def warn_thread_attribute_not_on_non_static_member : Warning< "%0 attribute without capability arguments can only be applied to non-static " "methods of a class">, InGroup, DefaultIgnore; def warn_thread_attribute_not_on_capability_member : Warning< "%0 attribute without capability arguments refers to 'this', but %1 isn't " "annotated with 'capability' or 'scoped_lockable' attribute">, InGroup, DefaultIgnore; def warn_thread_attribute_argument_not_lockable : Warning< "%0 attribute requires arguments whose type is annotated " "with 'capability' attribute; type here is %1">, InGroup, DefaultIgnore; def warn_thread_attribute_decl_not_lockable : Warning< "%0 attribute can only be applied in a context annotated " "with 'capability(\"mutex\")' attribute">, InGroup, DefaultIgnore; def warn_thread_attribute_decl_not_pointer : Warning< "%0 only applies to pointer types; type here is %1">, InGroup, DefaultIgnore; def err_attribute_argument_out_of_range : Error< "%0 attribute parameter %1 is out of bounds: " "%plural{0:no parameters to index into|" "1:can only be 1, since there is one parameter|" ":must be between 1 and %2}2">; // Thread Safety Analysis def warn_unlock_but_no_lock : Warning<"releasing %0 '%1' that was not held">, InGroup, DefaultIgnore; def warn_unlock_kind_mismatch : Warning< "releasing %0 '%1' using %select{shared|exclusive}2 access, expected " "%select{shared|exclusive}3 access">, InGroup, DefaultIgnore; def warn_double_lock : Warning<"acquiring %0 '%1' that is already held">, InGroup, DefaultIgnore; def warn_no_unlock : Warning< "%0 '%1' is still held at the end of function">, InGroup, DefaultIgnore; def warn_expecting_locked : Warning< "expecting %0 '%1' to be held at the end of function">, InGroup, DefaultIgnore; // FIXME: improve the error message about locks not in scope def warn_lock_some_predecessors : Warning< "%0 '%1' is not held on every path through here">, InGroup, DefaultIgnore; def warn_expecting_lock_held_on_loop : Warning< "expecting %0 '%1' to be held at start of each loop">, InGroup, DefaultIgnore; def note_locked_here : Note<"%0 acquired here">; def warn_lock_exclusive_and_shared : Warning< "%0 '%1' is acquired exclusively and shared in the same scope">, InGroup, DefaultIgnore; def note_lock_exclusive_and_shared : Note< "the other acquisition of %0 '%1' is here">; def warn_variable_requires_any_lock : Warning< "%select{reading|writing}1 variable %0 requires holding " "%select{any mutex|any mutex exclusively}1">, InGroup, DefaultIgnore; def warn_var_deref_requires_any_lock : Warning< "%select{reading|writing}1 the value pointed to by %0 requires holding " "%select{any mutex|any mutex exclusively}1">, InGroup, DefaultIgnore; def warn_fun_excludes_mutex : Warning< "cannot call function '%1' while %0 '%2' is held">, InGroup, DefaultIgnore; def warn_cannot_resolve_lock : Warning< "cannot resolve lock expression">, InGroup, DefaultIgnore; def warn_acquired_before : Warning< "%0 '%1' must be acquired before '%2'">, InGroup, DefaultIgnore; def warn_acquired_before_after_cycle : Warning< "Cycle in acquired_before/after dependencies, starting with '%0'">, InGroup, DefaultIgnore; // Thread safety warnings negative capabilities def warn_acquire_requires_negative_cap : Warning< "acquiring %0 '%1' requires negative capability '%2'">, InGroup, DefaultIgnore; // Thread safety warnings on pass by reference def warn_guarded_pass_by_reference : Warning< "passing variable %1 by reference requires holding %0 " "%select{'%2'|'%2' exclusively}3">, InGroup, DefaultIgnore; def warn_pt_guarded_pass_by_reference : Warning< "passing the value that %1 points to by reference requires holding %0 " "%select{'%2'|'%2' exclusively}3">, InGroup, DefaultIgnore; // Imprecise thread safety warnings def warn_variable_requires_lock : Warning< "%select{reading|writing}3 variable %1 requires holding %0 " "%select{'%2'|'%2' exclusively}3">, InGroup, DefaultIgnore; def warn_var_deref_requires_lock : Warning< "%select{reading|writing}3 the value pointed to by %1 requires " "holding %0 %select{'%2'|'%2' exclusively}3">, InGroup, DefaultIgnore; def warn_fun_requires_lock : Warning< "calling function %1 requires holding %0 %select{'%2'|'%2' exclusively}3">, InGroup, DefaultIgnore; // Precise thread safety warnings def warn_variable_requires_lock_precise : Warning, InGroup, DefaultIgnore; def warn_var_deref_requires_lock_precise : Warning, InGroup, DefaultIgnore; def warn_fun_requires_lock_precise : Warning, InGroup, DefaultIgnore; def note_found_mutex_near_match : Note<"found near match '%0'">; // Verbose thread safety warnings def warn_thread_safety_verbose : Warning<"Thread safety verbose warning.">, InGroup, DefaultIgnore; def note_thread_warning_in_fun : Note<"Thread warning in function %0">; def note_guarded_by_declared_here : Note<"Guarded_by declared here.">; // Dummy warning that will trigger "beta" warnings from the analysis if enabled. def warn_thread_safety_beta : Warning<"Thread safety beta warning.">, InGroup, DefaultIgnore; // Consumed warnings def warn_use_in_invalid_state : Warning< "invalid invocation of method '%0' on object '%1' while it is in the '%2' " "state">, InGroup, DefaultIgnore; def warn_use_of_temp_in_invalid_state : Warning< "invalid invocation of method '%0' on a temporary object while it is in the " "'%1' state">, InGroup, DefaultIgnore; def warn_attr_on_unconsumable_class : Warning< "consumed analysis attribute is attached to member of class '%0' which isn't " "marked as consumable">, InGroup, DefaultIgnore; def warn_return_typestate_for_unconsumable_type : Warning< "return state set for an unconsumable type '%0'">, InGroup, DefaultIgnore; def warn_return_typestate_mismatch : Warning< "return value not in expected state; expected '%0', observed '%1'">, InGroup, DefaultIgnore; def warn_loop_state_mismatch : Warning< "state of variable '%0' must match at the entry and exit of loop">, InGroup, DefaultIgnore; def warn_param_return_typestate_mismatch : Warning< "parameter '%0' not in expected state when the function returns: expected " "'%1', observed '%2'">, InGroup, DefaultIgnore; def warn_param_typestate_mismatch : Warning< "argument not in expected state; expected '%0', observed '%1'">, InGroup, DefaultIgnore; // no_sanitize attribute def warn_unknown_sanitizer_ignored : Warning< "unknown sanitizer '%0' ignored">, InGroup; def warn_impcast_vector_scalar : Warning< "implicit conversion turns vector to scalar: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_complex_scalar : Warning< "implicit conversion discards imaginary component: %0 to %1">, InGroup, DefaultIgnore; def err_impcast_complex_scalar : Error< "implicit conversion from %0 to %1 is not permitted in C++">; def warn_impcast_float_precision : Warning< "implicit conversion loses floating-point precision: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_float_result_precision : Warning< "implicit conversion when assigning computation result loses floating-point precision: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_double_promotion : Warning< "implicit conversion increases floating-point precision: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_integer_sign : Warning< "implicit conversion changes signedness: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_integer_sign_conditional : Warning< "operand of ? changes signedness: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_integer_precision : Warning< "implicit conversion loses integer precision: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_high_order_zero_bits : Warning< "higher order bits are zeroes after implicit conversion">, InGroup, DefaultIgnore; def warn_impcast_nonnegative_result : Warning< "the resulting value is always non-negative after implicit conversion">, InGroup, DefaultIgnore; def warn_impcast_integer_64_32 : Warning< "implicit conversion loses integer precision: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_integer_precision_constant : Warning< "implicit conversion from %2 to %3 changes value from %0 to %1">, InGroup; def warn_impcast_bitfield_precision_constant : Warning< "implicit truncation from %2 to bit-field changes value from %0 to %1">, InGroup; def warn_impcast_literal_float_to_integer : Warning< "implicit conversion from %0 to %1 changes value from %2 to %3">, InGroup; def warn_impcast_literal_float_to_integer_out_of_range : Warning< "implicit conversion of out of range value from %0 to %1 is undefined">, InGroup; def warn_impcast_float_integer : Warning< "implicit conversion turns floating-point number into integer: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_float_to_integer : Warning< "implicit conversion from %0 to %1 changes value from %2 to %3">, InGroup, DefaultIgnore; def warn_impcast_float_to_integer_out_of_range : Warning< "implicit conversion of out of range value from %0 to %1 is undefined">, InGroup, DefaultIgnore; def warn_impcast_float_to_integer_zero : Warning< "implicit conversion from %0 to %1 changes non-zero value from %2 to %3">, InGroup, DefaultIgnore; def warn_impcast_string_literal_to_bool : Warning< "implicit conversion turns string literal into bool: %0 to %1">, InGroup, DefaultIgnore; def warn_impcast_different_enum_types : Warning< "implicit conversion from enumeration type %0 to different enumeration type " "%1">, InGroup; def warn_impcast_bool_to_null_pointer : Warning< "initialization of pointer of type %0 to null from a constant boolean " "expression">, InGroup; def warn_non_literal_null_pointer : Warning< "expression which evaluates to zero treated as a null pointer constant of " "type %0">, InGroup; def warn_impcast_null_pointer_to_integer : Warning< "implicit conversion of %select{NULL|nullptr}0 constant to %1">, InGroup; def warn_impcast_floating_point_to_bool : Warning< "implicit conversion turns floating-point number into bool: %0 to %1">, InGroup; def ext_ms_impcast_fn_obj : ExtWarn< "implicit conversion between pointer-to-function and pointer-to-object is a " "Microsoft extension">, InGroup; def warn_impcast_pointer_to_bool : Warning< "address of%select{| function| array}0 '%1' will always evaluate to " "'true'">, InGroup; def warn_cast_nonnull_to_bool : Warning< "nonnull %select{function call|parameter}0 '%1' will evaluate to " "'true' on first encounter">, InGroup; def warn_this_bool_conversion : Warning< "'this' pointer cannot be null in well-defined C++ code; pointer may be " "assumed to always convert to true">, InGroup; def warn_address_of_reference_bool_conversion : Warning< "reference cannot be bound to dereferenced null pointer in well-defined C++ " "code; pointer may be assumed to always convert to true">, InGroup; def warn_null_pointer_compare : Warning< "comparison of %select{address of|function|array}0 '%1' %select{not |}2" "equal to a null pointer is always %select{true|false}2">, InGroup; def warn_nonnull_expr_compare : Warning< "comparison of nonnull %select{function call|parameter}0 '%1' " "%select{not |}2equal to a null pointer is '%select{true|false}2' on first " "encounter">, InGroup; def warn_this_null_compare : Warning< "'this' pointer cannot be null in well-defined C++ code; comparison may be " "assumed to always evaluate to %select{true|false}0">, InGroup; def warn_address_of_reference_null_compare : Warning< "reference cannot be bound to dereferenced null pointer in well-defined C++ " "code; comparison may be assumed to always evaluate to " "%select{true|false}0">, InGroup; def note_reference_is_return_value : Note<"%0 returns a reference">; def warn_division_sizeof_ptr : Warning< "'%0' will return the size of the pointer, not the array itself">, InGroup>; def note_function_warning_silence : Note< "prefix with the address-of operator to silence this warning">; def note_function_to_function_call : Note< "suffix with parentheses to turn this into a function call">; def warn_impcast_objective_c_literal_to_bool : Warning< "implicit boolean conversion of Objective-C object literal always " "evaluates to true">, InGroup; def warn_cast_align : Warning< "cast from %0 to %1 increases required alignment from %2 to %3">, InGroup, DefaultIgnore; def warn_old_style_cast : Warning< "use of old-style cast">, InGroup, DefaultIgnore; // Separate between casts to void* and non-void* pointers. // Some APIs use (abuse) void* for something like a user context, // and often that value is an integer even if it isn't a pointer itself. // Having a separate warning flag allows users to control the warning // for their workflow. def warn_int_to_pointer_cast : Warning< "cast to %1 from smaller integer type %0">, InGroup; def warn_int_to_void_pointer_cast : Warning< "cast to %1 from smaller integer type %0">, InGroup; def warn_attribute_ignored_for_field_of_type : Warning< "%0 attribute ignored for field of type %1">, InGroup; def warn_no_underlying_type_specified_for_enum_bitfield : Warning< "enums in the Microsoft ABI are signed integers by default; consider giving " "the enum %0 an unsigned underlying type to make this code portable">, InGroup, DefaultIgnore; def warn_attribute_packed_for_bitfield : Warning< "'packed' attribute was ignored on bit-fields with single-byte alignment " "in older versions of GCC and Clang">, InGroup>; def warn_transparent_union_attribute_field_size_align : Warning< "%select{alignment|size}0 of field %1 (%2 bits) does not match the " "%select{alignment|size}0 of the first field in transparent union; " "transparent_union attribute ignored">, InGroup; def note_transparent_union_first_field_size_align : Note< "%select{alignment|size}0 of first field is %1 bits">; def warn_transparent_union_attribute_not_definition : Warning< "transparent_union attribute can only be applied to a union definition; " "attribute ignored">, InGroup; def warn_transparent_union_attribute_floating : Warning< "first field of a transparent union cannot have %select{floating point|" "vector}0 type %1; transparent_union attribute ignored">, InGroup; def warn_transparent_union_attribute_zero_fields : Warning< "transparent union definition must contain at least one field; " "transparent_union attribute ignored">, InGroup; def warn_attribute_type_not_supported : Warning< "%0 attribute argument not supported: %1">, InGroup; def warn_attribute_unknown_visibility : Warning<"unknown visibility %0">, InGroup; def warn_attribute_protected_visibility : Warning<"target does not support 'protected' visibility; using 'default'">, InGroup>; def err_mismatched_visibility: Error<"visibility does not match previous declaration">; def note_previous_attribute : Note<"previous attribute is here">; def note_conflicting_attribute : Note<"conflicting attribute is here">; def note_attribute : Note<"attribute is here">; def err_mismatched_ms_inheritance : Error< "inheritance model does not match %select{definition|previous declaration}0">; def warn_ignored_ms_inheritance : Warning< "inheritance model ignored on %select{primary template|partial specialization}0">, InGroup; def note_previous_ms_inheritance : Note< "previous inheritance model specified here">; def err_machine_mode : Error<"%select{unknown|unsupported}0 machine mode %1">; def err_mode_not_primitive : Error< "mode attribute only supported for integer and floating-point types">; def err_mode_wrong_type : Error< "type of machine mode does not match type of base type">; def warn_vector_mode_deprecated : Warning< "specifying vector types with the 'mode' attribute is deprecated; " "use the 'vector_size' attribute instead">, InGroup; def err_complex_mode_vector_type : Error< "type of machine mode does not support base vector types">; def err_enum_mode_vector_type : Error< "mode %0 is not supported for enumeration types">; def warn_attribute_nonnull_no_pointers : Warning< "'nonnull' attribute applied to function with no pointer arguments">, InGroup; def warn_attribute_nonnull_parm_no_args : Warning< "'nonnull' attribute when used on parameters takes no arguments">, InGroup; def note_declared_nonnull : Note< "declared %select{'returns_nonnull'|'nonnull'}0 here">; def warn_attribute_sentinel_named_arguments : Warning< "'sentinel' attribute requires named arguments">, InGroup; def warn_attribute_sentinel_not_variadic : Warning< "'sentinel' attribute only supported for variadic %select{functions|blocks}0">, InGroup; def err_attribute_sentinel_less_than_zero : Error< "'sentinel' parameter 1 less than zero">; def err_attribute_sentinel_not_zero_or_one : Error< "'sentinel' parameter 2 not 0 or 1">; def warn_cleanup_ext : Warning< "GCC does not allow the 'cleanup' attribute argument to be anything other " "than a simple identifier">, InGroup; def err_attribute_cleanup_arg_not_function : Error< "'cleanup' argument %select{|%1 |%1 }0is not a %select{||single }0function">; def err_attribute_cleanup_func_must_take_one_arg : Error< "'cleanup' function %0 must take 1 parameter">; def err_attribute_cleanup_func_arg_incompatible_type : Error< "'cleanup' function %0 parameter has " "%diff{type $ which is incompatible with type $|incompatible type}1,2">; def err_attribute_regparm_wrong_platform : Error< "'regparm' is not valid on this platform">; def err_attribute_regparm_invalid_number : Error< "'regparm' parameter must be between 0 and %0 inclusive">; def err_attribute_not_supported_in_lang : Error< "%0 attribute is not supported in %select{C|C++|Objective-C}1">; def err_attribute_not_supported_on_arch : Error<"%0 attribute is not supported on '%1'">; def warn_gcc_ignores_type_attr : Warning< "GCC does not allow the %0 attribute to be written on a type">, InGroup; // Clang-Specific Attributes def warn_attribute_iboutlet : Warning< "%0 attribute can only be applied to instance variables or properties">, InGroup; def err_iboutletcollection_type : Error< "invalid type %0 as argument of iboutletcollection attribute">; def err_iboutletcollection_builtintype : Error< "type argument of iboutletcollection attribute cannot be a builtin type">; def warn_iboutlet_object_type : Warning< "%select{instance variable|property}2 with %0 attribute must " "be an object type (invalid %1)">, InGroup; def warn_iboutletcollection_property_assign : Warning< "IBOutletCollection properties should be copy/strong and not assign">, InGroup; def err_attribute_overloadable_mismatch : Error< "redeclaration of %0 must %select{not |}1have the 'overloadable' attribute">; def note_attribute_overloadable_prev_overload : Note< "previous %select{unmarked |}0overload of function is here">; def err_attribute_overloadable_no_prototype : Error< "'overloadable' function %0 must have a prototype">; def err_attribute_overloadable_multiple_unmarked_overloads : Error< "at most one overload for a given name may lack the 'overloadable' " "attribute">; def warn_ns_attribute_wrong_return_type : Warning< "%0 attribute only applies to %select{functions|methods|properties}1 that " "return %select{an Objective-C object|a pointer|a non-retainable pointer}2">, InGroup; def err_ns_attribute_wrong_parameter_type : Error< "%0 attribute only applies to " "%select{Objective-C object|pointer|pointer-to-CF-pointer}1 parameters">; def warn_ns_attribute_wrong_parameter_type : Warning< "%0 attribute only applies to " "%select{Objective-C object|pointer|pointer-to-CF-pointer|pointer/reference-to-OSObject-pointer}1 parameters">, InGroup; def warn_objc_requires_super_protocol : Warning< "%0 attribute cannot be applied to %select{methods in protocols|dealloc}1">, InGroup>; def note_protocol_decl : Note< "protocol is declared here">; def note_protocol_decl_undefined : Note< "protocol %0 has no definition">; // objc_designated_initializer attribute diagnostics. def warn_objc_designated_init_missing_super_call : Warning< "designated initializer missing a 'super' call to a designated initializer of the super class">, InGroup; def note_objc_designated_init_marked_here : Note< "method marked as designated initializer of the class here">; def warn_objc_designated_init_non_super_designated_init_call : Warning< "designated initializer should only invoke a designated initializer on 'super'">, InGroup; def warn_objc_designated_init_non_designated_init_call : Warning< "designated initializer invoked a non-designated initializer">, InGroup; def warn_objc_secondary_init_super_init_call : Warning< "convenience initializer should not invoke an initializer on 'super'">, InGroup; def warn_objc_secondary_init_missing_init_call : Warning< "convenience initializer missing a 'self' call to another initializer">, InGroup; def warn_objc_implementation_missing_designated_init_override : Warning< "method override for the designated initializer of the superclass %objcinstance0 not found">, InGroup; // objc_bridge attribute diagnostics. def err_objc_attr_not_id : Error< "parameter of %0 attribute must be a single name of an Objective-C %select{class|protocol}1">; def err_objc_attr_typedef_not_id : Error< "parameter of %0 attribute must be 'id' when used on a typedef">; def err_objc_attr_typedef_not_void_pointer : Error< "'objc_bridge(id)' is only allowed on structs and typedefs of void pointers">; def err_objc_cf_bridged_not_interface : Error< "CF object of type %0 is bridged to %1, which is not an Objective-C class">; def err_objc_ns_bridged_invalid_cfobject : Error< "ObjectiveC object of type %0 is bridged to %1, which is not valid CF object">; def warn_objc_invalid_bridge : Warning< "%0 bridges to %1, not %2">, InGroup; def warn_objc_invalid_bridge_to_cf : Warning< "%0 cannot bridge to %1">, InGroup; // objc_bridge_related attribute diagnostics. def err_objc_bridged_related_invalid_class : Error< "could not find Objective-C class %0 to convert %1 to %2">; def err_objc_bridged_related_invalid_class_name : Error< "%0 must be name of an Objective-C class to be able to convert %1 to %2">; def err_objc_bridged_related_known_method : Error< "%0 must be explicitly converted to %1; use %select{%objcclass2|%objcinstance2}3 " "method for this conversion">; def err_objc_attr_protocol_requires_definition : Error< "attribute %0 can only be applied to @protocol definitions, not forward declarations">; def warn_ignored_objc_externally_retained : Warning< "'objc_externally_retained' can only be applied to local variables " "%select{of retainable type|with strong ownership}0">, InGroup; // Function Parameter Semantic Analysis. def err_param_with_void_type : Error<"argument may not have 'void' type">; def err_void_only_param : Error< "'void' must be the first and only parameter if specified">; def err_void_param_qualified : Error< "'void' as parameter must not have type qualifiers">; def err_ident_list_in_fn_declaration : Error< "a parameter list without types is only allowed in a function definition">; def ext_param_not_declared : Extension< "parameter %0 was not declared, defaulting to type 'int'">; def err_param_default_argument : Error< "C does not support default arguments">; def err_param_default_argument_redefinition : Error< "redefinition of default argument">; def ext_param_default_argument_redefinition : ExtWarn< err_param_default_argument_redefinition.Text>, InGroup; def err_param_default_argument_missing : Error< "missing default argument on parameter">; def err_param_default_argument_missing_name : Error< "missing default argument on parameter %0">; def err_param_default_argument_references_param : Error< "default argument references parameter %0">; def err_param_default_argument_references_local : Error< "default argument references local variable %0 of enclosing function">; def err_param_default_argument_references_this : Error< "default argument references 'this'">; def err_param_default_argument_nonfunc : Error< "default arguments can only be specified for parameters in a function " "declaration">; def err_param_default_argument_template_redecl : Error< "default arguments cannot be added to a function template that has already " "been declared">; def err_param_default_argument_member_template_redecl : Error< "default arguments cannot be added to an out-of-line definition of a member " "of a %select{class template|class template partial specialization|nested " "class in a template}0">; def err_param_default_argument_on_parameter_pack : Error< "parameter pack cannot have a default argument">; def err_uninitialized_member_for_assign : Error< "cannot define the implicit copy assignment operator for %0, because " "non-static %select{reference|const}1 member %2 cannot use copy " "assignment operator">; def err_uninitialized_member_in_ctor : Error< "%select{constructor for %1|" "implicit default constructor for %1|" "cannot use constructor inherited from %1:}0 must explicitly " "initialize the %select{reference|const}2 member %3">; def err_default_arg_makes_ctor_special : Error< "addition of default argument on redeclaration makes this constructor a " "%select{default|copy|move}0 constructor">; def err_use_of_default_argument_to_function_declared_later : Error< "use of default argument to function %0 that is declared later in class %1">; def note_default_argument_declared_here : Note< "default argument declared here">; def err_recursive_default_argument : Error<"recursive evaluation of default argument">; def ext_param_promoted_not_compatible_with_prototype : ExtWarn< "%diff{promoted type $ of K&R function parameter is not compatible with the " "parameter type $|promoted type of K&R function parameter is not compatible " "with parameter type}0,1 declared in a previous prototype">, InGroup; // C++ Overloading Semantic Analysis. def err_ovl_diff_return_type : Error< "functions that differ only in their return type cannot be overloaded">; def err_ovl_static_nonstatic_member : Error< "static and non-static member functions with the same parameter types " "cannot be overloaded">; def err_ovl_no_viable_function_in_call : Error< "no matching function for call to %0">; def err_ovl_no_viable_member_function_in_call : Error< "no matching member function for call to %0">; def err_ovl_ambiguous_call : Error< "call to %0 is ambiguous">; def err_ovl_deleted_call : Error< "call to %select{unavailable|deleted}0 function %1%2">; def err_ovl_ambiguous_member_call : Error< "call to member function %0 is ambiguous">; def err_ovl_deleted_member_call : Error< "call to %select{unavailable|deleted}0 member function %1%2">; def note_ovl_too_many_candidates : Note< "remaining %0 candidate%s0 omitted; " "pass -fshow-overloads=all to show them">; def select_ovl_candidate_kind : TextSubstitution< "%select{function|function|constructor|" "constructor (the implicit default constructor)|" "constructor (the implicit copy constructor)|" "constructor (the implicit move constructor)|" "function (the implicit copy assignment operator)|" "function (the implicit move assignment operator)|" "inherited constructor}0%select{| template| %2}1">; def note_ovl_candidate : Note< "candidate %sub{select_ovl_candidate_kind}0,1,3" "%select{| has different class%diff{ (expected $ but has $)|}5,6" "| has different number of parameters (expected %5 but has %6)" "| has type mismatch at %ordinal5 parameter" "%diff{ (expected $ but has $)|}6,7" "| has different return type%diff{ ($ expected but has $)|}5,6" "| has different qualifiers (expected %5 but found %6)" "| has different exception specification}4">; def note_ovl_candidate_inherited_constructor : Note< "constructor from base class %0 inherited here">; def note_ovl_candidate_inherited_constructor_slice : Note< "candidate %select{constructor|template}0 ignored: " "inherited constructor cannot be used to %select{copy|move}1 object">; def note_ovl_candidate_illegal_constructor : Note< "candidate %select{constructor|template}0 ignored: " "instantiation %select{takes|would take}0 its own class type by value">; def note_ovl_candidate_bad_deduction : Note< "candidate template ignored: failed template argument deduction">; def note_ovl_candidate_incomplete_deduction : Note<"candidate template ignored: " "couldn't infer template argument %0">; def note_ovl_candidate_incomplete_deduction_pack : Note<"candidate template ignored: " "deduced too few arguments for expanded pack %0; no argument for %ordinal1 " "expanded parameter in deduced argument pack %2">; def note_ovl_candidate_inconsistent_deduction : Note< "candidate template ignored: deduced conflicting %select{types|values|" "templates}0 for parameter %1%diff{ ($ vs. $)|}2,3">; def note_ovl_candidate_inconsistent_deduction_types : Note< "candidate template ignored: deduced values %diff{" "of conflicting types for parameter %0 (%1 of type $ vs. %3 of type $)|" "%1 and %3 of conflicting types for parameter %0}2,4">; def note_ovl_candidate_explicit_arg_mismatch_named : Note< "candidate template ignored: invalid explicitly-specified argument " "for template parameter %0">; def note_ovl_candidate_explicit_arg_mismatch_unnamed : Note< "candidate template ignored: invalid explicitly-specified argument " "for %ordinal0 template parameter">; def note_ovl_candidate_instantiation_depth : Note< "candidate template ignored: substitution exceeded maximum template " "instantiation depth">; def note_ovl_candidate_underqualified : Note< "candidate template ignored: cannot deduce a type for %0 that would " "make %2 equal %1">; def note_ovl_candidate_substitution_failure : Note< "candidate template ignored: substitution failure%0%1">; def note_ovl_candidate_disabled_by_enable_if : Note< "candidate template ignored: disabled by %0%1">; def note_ovl_candidate_disabled_by_requirement : Note< "candidate template ignored: requirement '%0' was not satisfied%1">; def note_ovl_candidate_has_pass_object_size_params: Note< "candidate address cannot be taken because parameter %0 has " "pass_object_size attribute">; def err_diagnose_if_succeeded : Error<"%0">; def warn_diagnose_if_succeeded : Warning<"%0">, InGroup, ShowInSystemHeader; def note_ovl_candidate_disabled_by_function_cond_attr : Note< "candidate disabled: %0">; def note_ovl_candidate_disabled_by_extension : Note< "candidate unavailable as it requires OpenCL extension '%0' to be enabled">; def err_addrof_function_disabled_by_enable_if_attr : Error< "cannot take address of function %0 because it has one or more " "non-tautological enable_if conditions">; def note_addrof_ovl_candidate_disabled_by_enable_if_attr : Note< "candidate function made ineligible by enable_if">; def note_ovl_candidate_deduced_mismatch : Note< "candidate template ignored: deduced type " "%diff{$ of %select{|element of }4%ordinal0 parameter does not match " "adjusted type $ of %select{|element of }4argument" "|of %select{|element of }4%ordinal0 parameter does not match " "adjusted type of %select{|element of }4argument}1,2%3">; def note_ovl_candidate_non_deduced_mismatch : Note< "candidate template ignored: could not match %diff{$ against $|types}0,1">; // This note is needed because the above note would sometimes print two // different types with the same name. Remove this note when the above note // can handle that case properly. def note_ovl_candidate_non_deduced_mismatch_qualified : Note< "candidate template ignored: could not match %q0 against %q1">; // Note that we don't treat templates differently for this diagnostic. def note_ovl_candidate_arity : Note<"candidate " "%sub{select_ovl_candidate_kind}0,1,2 not viable: " "requires%select{ at least| at most|}3 %4 argument%s4, but %5 " "%plural{1:was|:were}5 provided">; def note_ovl_candidate_arity_one : Note<"candidate " "%sub{select_ovl_candidate_kind}0,1,2 not viable: " "%select{requires at least|allows at most single|requires single}3 " "argument %4, but %plural{0:no|:%5}5 arguments were provided">; def note_ovl_candidate_deleted : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 has been " "%select{explicitly made unavailable|explicitly deleted|" "implicitly deleted}3">; // Giving the index of the bad argument really clutters this message, and // it's relatively unimportant because 1) it's generally obvious which // argument(s) are of the given object type and 2) the fix is usually // to complete the type, which doesn't involve changes to the call line // anyway. If people complain, we can change it. def note_ovl_candidate_bad_conv_incomplete : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "cannot convert argument of incomplete type " "%diff{$ to $|to parameter type}3,4 for " "%select{%ordinal6 argument|object argument}5" "%select{|; dereference the argument with *|" "; take the address of the argument with &|" "; remove *|" "; remove &}7">; def note_ovl_candidate_bad_list_argument : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "cannot convert initializer list argument to %4">; def note_ovl_candidate_bad_overload : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "no overload of %4 matching %3 for %ordinal5 argument">; def note_ovl_candidate_bad_conv : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "no known conversion " "%diff{from $ to $|from argument type to parameter type}3,4 for " "%select{%ordinal6 argument|object argument}5" "%select{|; dereference the argument with *|" "; take the address of the argument with &|" "; remove *|" "; remove &}7">; def note_ovl_candidate_bad_arc_conv : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "cannot implicitly convert argument " "%diff{of type $ to $|type to parameter type}3,4 for " "%select{%ordinal6 argument|object argument}5 under ARC">; def note_ovl_candidate_bad_lvalue : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "expects an l-value for " "%select{%ordinal4 argument|object argument}3">; def note_ovl_candidate_bad_addrspace : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "address space mismatch in %select{%ordinal6|'this'}5 argument (%3), " "parameter type must be %4">; def note_ovl_candidate_bad_gc : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "%select{%ordinal7|'this'}6 argument (%3) has %select{no|__weak|__strong}4 " "ownership, but parameter has %select{no|__weak|__strong}5 ownership">; def note_ovl_candidate_bad_ownership : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "%select{%ordinal7|'this'}6 argument (%3) has " "%select{no|__unsafe_unretained|__strong|__weak|__autoreleasing}4 ownership," " but parameter has %select{no|__unsafe_unretained|__strong|__weak|" "__autoreleasing}5 ownership">; def note_ovl_candidate_bad_cvr_this : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "'this' argument has type %3, but method is not marked " "%select{const|restrict|const or restrict|volatile|const or volatile|" "volatile or restrict|const, volatile, or restrict}4">; def note_ovl_candidate_bad_cvr : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "%ordinal5 argument (%3) would lose " "%select{const|restrict|const and restrict|volatile|const and volatile|" "volatile and restrict|const, volatile, and restrict}4 qualifier" "%select{||s||s|s|s}4">; def note_ovl_candidate_bad_unaligned : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "%ordinal5 argument (%3) would lose __unaligned qualifier">; def note_ovl_candidate_bad_base_to_derived_conv : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "cannot %select{convert from|convert from|bind}3 " "%select{base class pointer|superclass|base class object of type}3 %4 to " "%select{derived class pointer|subclass|derived class reference}3 %5 for " "%ordinal6 argument">; def note_ovl_candidate_bad_target : Note< "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: " "call to " "%select{__device__|__global__|__host__|__host__ __device__|invalid}3 function from" " %select{__device__|__global__|__host__|__host__ __device__|invalid}4 function">; def note_implicit_member_target_infer_collision : Note< "implicit %sub{select_special_member_kind}0 inferred target collision: call to both " "%select{__device__|__global__|__host__|__host__ __device__}1 and " "%select{__device__|__global__|__host__|__host__ __device__}2 members">; def note_ambiguous_type_conversion: Note< "because of ambiguity in conversion %diff{of $ to $|between types}0,1">; def note_ovl_builtin_binary_candidate : Note< "built-in candidate %0">; def note_ovl_builtin_unary_candidate : Note< "built-in candidate %0">; def err_ovl_no_viable_function_in_init : Error< "no matching constructor for initialization of %0">; def err_ovl_no_conversion_in_cast : Error< "cannot convert %1 to %2 without a conversion operator">; def err_ovl_no_viable_conversion_in_cast : Error< "no matching conversion for %select{|static_cast|reinterpret_cast|" "dynamic_cast|C-style cast|functional-style cast}0 from %1 to %2">; def err_ovl_ambiguous_conversion_in_cast : Error< "ambiguous conversion for %select{|static_cast|reinterpret_cast|" "dynamic_cast|C-style cast|functional-style cast}0 from %1 to %2">; def err_ovl_deleted_conversion_in_cast : Error< "%select{|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from %1 to %2 uses deleted function">; def err_ovl_ambiguous_init : Error<"call to constructor of %0 is ambiguous">; def err_ref_init_ambiguous : Error< "reference initialization of type %0 with initializer of type %1 is ambiguous">; def err_ovl_deleted_init : Error< "call to %select{unavailable|deleted}0 constructor of %1">; def err_ovl_deleted_special_init : Error< "call to implicitly-deleted %select{default constructor|copy constructor|" "move constructor|copy assignment operator|move assignment operator|" "destructor|function}0 of %1">; def err_ovl_ambiguous_oper_unary : Error< "use of overloaded operator '%0' is ambiguous (operand type %1)">; def err_ovl_ambiguous_oper_binary : Error< "use of overloaded operator '%0' is ambiguous (with operand types %1 and %2)">; def err_ovl_no_viable_oper : Error<"no viable overloaded '%0'">; def note_assign_lhs_incomplete : Note<"type %0 is incomplete">; def err_ovl_deleted_oper : Error< "overload resolution selected %select{unavailable|deleted}0 operator '%1'%2">; def err_ovl_deleted_special_oper : Error< "object of type %0 cannot be %select{constructed|copied|moved|assigned|" "assigned|destroyed}1 because its %sub{select_special_member_kind}1 is implicitly deleted">; def err_ovl_no_viable_subscript : Error<"no viable overloaded operator[] for type %0">; def err_ovl_no_oper : Error<"type %0 does not provide a %select{subscript|call}1 operator">; def err_ovl_unresolvable : Error< "reference to %select{overloaded|multiversioned}1 function could not be " "resolved; did you mean to call it%select{| with no arguments}0?">; def err_bound_member_function : Error< "reference to non-static member function must be called" "%select{|; did you mean to call it with no arguments?}0">; def note_possible_target_of_call : Note<"possible target for call">; def err_ovl_no_viable_object_call : Error< "no matching function for call to object of type %0">; def err_ovl_ambiguous_object_call : Error< "call to object of type %0 is ambiguous">; def err_ovl_deleted_object_call : Error< "call to %select{unavailable|deleted}0 function call operator in type %1%2">; def note_ovl_surrogate_cand : Note<"conversion candidate of type %0">; def err_member_call_without_object : Error< "call to non-static member function without an object argument">; // C++ Address of Overloaded Function def err_addr_ovl_no_viable : Error< "address of overloaded function %0 does not match required type %1">; def err_addr_ovl_ambiguous : Error< "address of overloaded function %0 is ambiguous">; def err_addr_ovl_not_func_ptrref : Error< "address of overloaded function %0 cannot be converted to type %1">; def err_addr_ovl_no_qualifier : Error< "cannot form member pointer of type %0 without '&' and class name">; // C++11 Literal Operators def err_ovl_no_viable_literal_operator : Error< "no matching literal operator for call to %0" "%select{| with argument of type %2| with arguments of types %2 and %3}1" "%select{| or 'const char *'}4" "%select{|, and no matching literal operator template}5">; // C++ Template Declarations def err_template_param_shadow : Error< "declaration of %0 shadows template parameter">; def note_template_param_here : Note<"template parameter is declared here">; def warn_template_export_unsupported : Warning< "exported templates are unsupported">; def err_template_outside_namespace_or_class_scope : Error< "templates can only be declared in namespace or class scope">; def err_template_inside_local_class : Error< "templates cannot be declared inside of a local class">; def err_template_linkage : Error<"templates must have C++ linkage">; def err_template_typedef : Error<"a typedef cannot be a template">; def err_template_unnamed_class : Error< "cannot declare a class template with no name">; def err_template_param_list_different_arity : Error< "%select{too few|too many}0 template parameters in template " "%select{|template parameter }1redeclaration">; def note_template_param_list_different_arity : Note< "%select{too few|too many}0 template parameters in template template " "argument">; def note_template_prev_declaration : Note< "previous template %select{declaration|template parameter}0 is here">; def err_template_param_different_kind : Error< "template parameter has a different kind in template " "%select{|template parameter }0redeclaration">; def note_template_param_different_kind : Note< "template parameter has a different kind in template argument">; def err_invalid_decl_specifier_in_nontype_parm : Error< "invalid declaration specifier in template non-type parameter">; def err_template_nontype_parm_different_type : Error< "template non-type parameter has a different type %0 in template " "%select{|template parameter }1redeclaration">; def note_template_nontype_parm_different_type : Note< "template non-type parameter has a different type %0 in template argument">; def note_template_nontype_parm_prev_declaration : Note< "previous non-type template parameter with type %0 is here">; def err_template_nontype_parm_bad_type : Error< "a non-type template parameter cannot have type %0">; def warn_cxx14_compat_template_nontype_parm_auto_type : Warning< "non-type template parameters declared with %0 are incompatible with C++ " "standards before C++17">, DefaultIgnore, InGroup; def err_template_param_default_arg_redefinition : Error< "template parameter redefines default argument">; def note_template_param_prev_default_arg : Note< "previous default template argument defined here">; def err_template_param_default_arg_missing : Error< "template parameter missing a default argument">; def ext_template_parameter_default_in_function_template : ExtWarn< "default template arguments for a function template are a C++11 extension">, InGroup; def warn_cxx98_compat_template_parameter_default_in_function_template : Warning< "default template arguments for a function template are incompatible with C++98">, InGroup, DefaultIgnore; def err_template_parameter_default_template_member : Error< "cannot add a default template argument to the definition of a member of a " "class template">; def err_template_parameter_default_friend_template : Error< "default template argument not permitted on a friend template">; def err_template_template_parm_no_parms : Error< "template template parameter must have its own template parameters">; def ext_variable_template : ExtWarn<"variable templates are a C++14 extension">, InGroup; def warn_cxx11_compat_variable_template : Warning< "variable templates are incompatible with C++ standards before C++14">, InGroup, DefaultIgnore; def err_template_variable_noparams : Error< "extraneous 'template<>' in declaration of variable %0">; def err_template_member : Error<"member %0 declared as a template">; def err_template_member_noparams : Error< "extraneous 'template<>' in declaration of member %0">; def err_template_tag_noparams : Error< "extraneous 'template<>' in declaration of %0 %1">; // C++ Template Argument Lists def err_template_missing_args : Error< "use of " "%select{class template|function template|variable template|alias template|" "template template parameter|template}0 %1 requires template arguments">; def err_template_arg_list_different_arity : Error< "%select{too few|too many}0 template arguments for " "%select{class template|function template|variable template|alias template|" "template template parameter|template}1 %2">; def note_template_decl_here : Note<"template is declared here">; def err_template_arg_must_be_type : Error< "template argument for template type parameter must be a type">; def err_template_arg_must_be_type_suggest : Error< "template argument for template type parameter must be a type; " "did you forget 'typename'?">; def ext_ms_template_type_arg_missing_typename : ExtWarn< "template argument for template type parameter must be a type; " "omitted 'typename' is a Microsoft extension">, InGroup; def err_template_arg_must_be_expr : Error< "template argument for non-type template parameter must be an expression">; def err_template_arg_nontype_ambig : Error< "template argument for non-type template parameter is treated as function type %0">; def err_template_arg_must_be_template : Error< "template argument for template template parameter must be a class template%select{| or type alias template}0">; def ext_template_arg_local_type : ExtWarn< "template argument uses local type %0">, InGroup; def ext_template_arg_unnamed_type : ExtWarn< "template argument uses unnamed type">, InGroup; def warn_cxx98_compat_template_arg_local_type : Warning< "local type %0 as template argument is incompatible with C++98">, InGroup, DefaultIgnore; def warn_cxx98_compat_template_arg_unnamed_type : Warning< "unnamed type as template argument is incompatible with C++98">, InGroup, DefaultIgnore; def note_template_unnamed_type_here : Note< "unnamed type used in template argument was declared here">; def err_template_arg_overload_type : Error< "template argument is the type of an unresolved overloaded function">; def err_template_arg_not_valid_template : Error< "template argument does not refer to a class or alias template, or template " "template parameter">; def note_template_arg_refers_here_func : Note< "template argument refers to function template %0, here">; def err_template_arg_template_params_mismatch : Error< "template template argument has different template parameters than its " "corresponding template template parameter">; def err_template_arg_not_integral_or_enumeral : Error< "non-type template argument of type %0 must have an integral or enumeration" " type">; def err_template_arg_not_ice : Error< "non-type template argument of type %0 is not an integral constant " "expression">; def err_template_arg_not_address_constant : Error< "non-type template argument of type %0 is not a constant expression">; def warn_cxx98_compat_template_arg_null : Warning< "use of null pointer as non-type template argument is incompatible with " "C++98">, InGroup, DefaultIgnore; def err_template_arg_untyped_null_constant : Error< "null non-type template argument must be cast to template parameter type %0">; def err_template_arg_wrongtype_null_constant : Error< "null non-type template argument of type %0 does not match template parameter " "of type %1">; def err_non_type_template_parm_type_deduction_failure : Error< "non-type template parameter %0 with type %1 has incompatible initializer of type %2">; def err_deduced_non_type_template_arg_type_mismatch : Error< "deduced non-type template argument does not have the same type as the " "corresponding template parameter%diff{ ($ vs $)|}0,1">; def err_non_type_template_arg_subobject : Error< "non-type template argument refers to subobject '%0'">; def err_non_type_template_arg_addr_label_diff : Error< "template argument / label address difference / what did you expect?">; def err_template_arg_not_convertible : Error< "non-type template argument of type %0 cannot be converted to a value " "of type %1">; def warn_template_arg_negative : Warning< "non-type template argument with value '%0' converted to '%1' for unsigned " "template parameter of type %2">, InGroup, DefaultIgnore; def warn_template_arg_too_large : Warning< "non-type template argument value '%0' truncated to '%1' for " "template parameter of type %2">, InGroup, DefaultIgnore; def err_template_arg_no_ref_bind : Error< "non-type template parameter of reference type " "%diff{$ cannot bind to template argument of type $" "|cannot bind to template of incompatible argument type}0,1">; def err_template_arg_ref_bind_ignores_quals : Error< "reference binding of non-type template parameter " "%diff{of type $ to template argument of type $|to template argument}0,1 " "ignores qualifiers">; def err_template_arg_not_decl_ref : Error< "non-type template argument does not refer to any declaration">; def err_template_arg_not_address_of : Error< "non-type template argument for template parameter of pointer type %0 must " "have its address taken">; def err_template_arg_address_of_non_pointer : Error< "address taken in non-type template argument for template parameter of " "reference type %0">; def err_template_arg_reference_var : Error< "non-type template argument of reference type %0 is not an object">; def err_template_arg_field : Error< "non-type template argument refers to non-static data member %0">; def err_template_arg_method : Error< "non-type template argument refers to non-static member function %0">; def err_template_arg_object_no_linkage : Error< "non-type template argument refers to %select{function|object}0 %1 that " "does not have linkage">; def warn_cxx98_compat_template_arg_object_internal : Warning< "non-type template argument referring to %select{function|object}0 %1 with " "internal linkage is incompatible with C++98">, InGroup, DefaultIgnore; def ext_template_arg_object_internal : ExtWarn< "non-type template argument referring to %select{function|object}0 %1 with " "internal linkage is a C++11 extension">, InGroup; def err_template_arg_thread_local : Error< "non-type template argument refers to thread-local object">; def note_template_arg_internal_object : Note< "non-type template argument refers to %select{function|object}0 here">; def note_template_arg_refers_here : Note< "non-type template argument refers here">; def err_template_arg_not_object_or_func : Error< "non-type template argument does not refer to an object or function">; def err_template_arg_not_pointer_to_member_form : Error< "non-type template argument is not a pointer to member constant">; def err_template_arg_member_ptr_base_derived_not_supported : Error< "sorry, non-type template argument of pointer-to-member type %1 that refers " "to member %q0 of a different class is not supported yet">; def ext_template_arg_extra_parens : ExtWarn< "address non-type template argument cannot be surrounded by parentheses">; def warn_cxx98_compat_template_arg_extra_parens : Warning< "redundant parentheses surrounding address non-type template argument are " "incompatible with C++98">, InGroup, DefaultIgnore; def err_pointer_to_member_type : Error< "invalid use of pointer to member type after %select{.*|->*}0">; def err_pointer_to_member_call_drops_quals : Error< "call to pointer to member function of type %0 drops '%1' qualifier%s2">; def err_pointer_to_member_oper_value_classify: Error< "pointer-to-member function type %0 can only be called on an " "%select{rvalue|lvalue}1">; def ext_pointer_to_const_ref_member_on_rvalue : Extension< "invoking a pointer to a 'const &' member function on an rvalue is a C++2a extension">, InGroup, SFINAEFailure; def warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue : Warning< "invoking a pointer to a 'const &' member function on an rvalue is " "incompatible with C++ standards before C++2a">, InGroup, DefaultIgnore; def ext_ms_deref_template_argument: ExtWarn< "non-type template argument containing a dereference operation is a " "Microsoft extension">, InGroup; def ext_ms_delayed_template_argument: ExtWarn< "using the undeclared type %0 as a default template argument is a " "Microsoft extension">, InGroup; def err_template_arg_deduced_incomplete_pack : Error< "deduced incomplete pack %0 for template parameter %1">; // C++ template specialization def err_template_spec_unknown_kind : Error< "can only provide an explicit specialization for a class template, function " "template, variable template, or a member function, static data member, " "%select{or member class|member class, or member enumeration}0 of a " "class template">; def note_specialized_entity : Note< "explicitly specialized declaration is here">; def note_explicit_specialization_declared_here : Note< "explicit specialization declared here">; def err_template_spec_decl_function_scope : Error< "explicit specialization of %0 in function scope">; def err_template_spec_decl_friend : Error< "cannot declare an explicit specialization in a friend">; def err_template_spec_redecl_out_of_scope : Error< "%select{class template|class template partial|variable template|" "variable template partial|function template|member " "function|static data member|member class|member enumeration}0 " "specialization of %1 not in %select{a namespace enclosing %2|" "class %2 or an enclosing namespace}3">; def ext_ms_template_spec_redecl_out_of_scope: ExtWarn< "%select{class template|class template partial|variable template|" "variable template partial|function template|member " "function|static data member|member class|member enumeration}0 " "specialization of %1 not in %select{a namespace enclosing %2|" "class %2 or an enclosing namespace}3 " "is a Microsoft extension">, InGroup; def err_template_spec_redecl_global_scope : Error< "%select{class template|class template partial|variable template|" "variable template partial|function template|member " "function|static data member|member class|member enumeration}0 " "specialization of %1 must occur at global scope">; def err_spec_member_not_instantiated : Error< "specialization of member %q0 does not specialize an instantiated member">; def note_specialized_decl : Note<"attempt to specialize declaration here">; def err_specialization_after_instantiation : Error< "explicit specialization of %0 after instantiation">; def note_instantiation_required_here : Note< "%select{implicit|explicit}0 instantiation first required here">; def err_template_spec_friend : Error< "template specialization declaration cannot be a friend">; def err_template_spec_default_arg : Error< "default argument not permitted on an explicit " "%select{instantiation|specialization}0 of function %1">; def err_not_class_template_specialization : Error< "cannot specialize a %select{dependent template|template template " "parameter}0">; def ext_explicit_specialization_storage_class : ExtWarn< "explicit specialization cannot have a storage class">; def err_explicit_specialization_inconsistent_storage_class : Error< "explicit specialization has extraneous, inconsistent storage class " "'%select{none|extern|static|__private_extern__|auto|register}0'">; def err_dependent_function_template_spec_no_match : Error< "no candidate function template was found for dependent" " friend function template specialization">; def note_dependent_function_template_spec_discard_reason : Note< "candidate ignored: %select{not a function template" "|not a member of the enclosing namespace;" " did you mean to explicitly qualify the specialization?}0">; // C++ class template specializations and out-of-line definitions def err_template_spec_needs_header : Error< "template specialization requires 'template<>'">; def err_template_spec_needs_template_parameters : Error< "template specialization or definition requires a template parameter list " "corresponding to the nested type %0">; def err_template_param_list_matches_nontemplate : Error< "template parameter list matching the non-templated nested type %0 should " "be empty ('template<>')">; def err_alias_template_extra_headers : Error< "extraneous template parameter list in alias template declaration">; def err_template_spec_extra_headers : Error< "extraneous template parameter list in template specialization or " "out-of-line template definition">; def warn_template_spec_extra_headers : Warning< "extraneous template parameter list in template specialization">; def note_explicit_template_spec_does_not_need_header : Note< "'template<>' header not required for explicitly-specialized class %0 " "declared here">; def err_template_qualified_declarator_no_match : Error< "nested name specifier '%0' for declaration does not refer into a class, " "class template or class template partial specialization">; def err_specialize_member_of_template : Error< "cannot specialize %select{|(with 'template<>') }0a member of an " "unspecialized template">; // C++ Class Template Partial Specialization def err_default_arg_in_partial_spec : Error< "default template argument in a class template partial specialization">; def err_dependent_non_type_arg_in_partial_spec : Error< "type of specialized non-type template argument depends on a template " "parameter of the partial specialization">; def note_dependent_non_type_default_arg_in_partial_spec : Note< "template parameter is used in default argument declared here">; def err_dependent_typed_non_type_arg_in_partial_spec : Error< "non-type template argument specializes a template parameter with " "dependent type %0">; def err_partial_spec_args_match_primary_template : Error< "%select{class|variable}0 template partial specialization does not " "specialize any template argument; to %select{declare|define}1 the " "primary template, remove the template argument list">; def ext_partial_spec_not_more_specialized_than_primary : ExtWarn< "%select{class|variable}0 template partial specialization is not " "more specialized than the primary template">, DefaultError, InGroup>; def note_partial_spec_not_more_specialized_than_primary : Note<"%0">; def ext_partial_specs_not_deducible : ExtWarn< "%select{class|variable}0 template partial specialization contains " "%select{a template parameter|template parameters}1 that cannot be " "deduced; this partial specialization will never be used">, DefaultError, InGroup>; def note_non_deducible_parameter : Note< "non-deducible template parameter %0">; def err_partial_spec_ordering_ambiguous : Error< "ambiguous partial specializations of %0">; def note_partial_spec_match : Note<"partial specialization matches %0">; def err_partial_spec_redeclared : Error< "class template partial specialization %0 cannot be redeclared">; def note_partial_specialization_declared_here : Note< "explicit specialization declared here">; def note_prev_partial_spec_here : Note< "previous declaration of class template partial specialization %0 is here">; def err_partial_spec_fully_specialized : Error< "partial specialization of %0 does not use any of its template parameters">; // C++ Variable Template Partial Specialization def err_var_partial_spec_redeclared : Error< "variable template partial specialization %0 cannot be redefined">; def note_var_prev_partial_spec_here : Note< "previous declaration of variable template partial specialization is here">; def err_var_spec_no_template : Error< "no variable template matches%select{| partial}0 specialization">; def err_var_spec_no_template_but_method : Error< "no variable template matches specialization; " "did you mean to use %0 as function template instead?">; // C++ Function template specializations def err_function_template_spec_no_match : Error< "no function template matches function template specialization %0">; def err_function_template_spec_ambiguous : Error< "function template specialization %0 ambiguously refers to more than one " "function template; explicitly specify%select{| additional}1 template " "arguments to identify a particular function template">; def note_function_template_spec_matched : Note< "function template %q0 matches specialization %1">; def err_function_template_partial_spec : Error< "function template partial specialization is not allowed">; // C++ Template Instantiation def err_template_recursion_depth_exceeded : Error< "recursive template instantiation exceeded maximum depth of %0">, DefaultFatal, NoSFINAE; def note_template_recursion_depth : Note< "use -ftemplate-depth=N to increase recursive template instantiation depth">; def err_template_instantiate_within_definition : Error< "%select{implicit|explicit}0 instantiation of template %1 within its" " own definition">; def err_template_instantiate_undefined : Error< "%select{implicit|explicit}0 instantiation of undefined template %1">; def err_implicit_instantiate_member_undefined : Error< "implicit instantiation of undefined member %0">; def note_template_class_instantiation_was_here : Note< "class template %0 was instantiated here">; def note_template_class_explicit_specialization_was_here : Note< "class template %0 was explicitly specialized here">; def note_template_class_instantiation_here : Note< "in instantiation of template class %q0 requested here">; def note_template_member_class_here : Note< "in instantiation of member class %q0 requested here">; def note_template_member_function_here : Note< "in instantiation of member function %q0 requested here">; def note_function_template_spec_here : Note< "in instantiation of function template specialization %q0 requested here">; def note_template_static_data_member_def_here : Note< "in instantiation of static data member %q0 requested here">; def note_template_variable_def_here : Note< "in instantiation of variable template specialization %q0 requested here">; def note_template_enum_def_here : Note< "in instantiation of enumeration %q0 requested here">; def note_template_nsdmi_here : Note< "in instantiation of default member initializer %q0 requested here">; def note_template_type_alias_instantiation_here : Note< "in instantiation of template type alias %0 requested here">; def note_template_exception_spec_instantiation_here : Note< "in instantiation of exception specification for %0 requested here">; def warn_var_template_missing : Warning<"instantiation of variable %q0 " "required here, but no definition is available">, InGroup; def warn_func_template_missing : Warning<"instantiation of function %q0 " "required here, but no definition is available">, InGroup, DefaultIgnore; def note_forward_template_decl : Note< "forward declaration of template entity is here">; def note_inst_declaration_hint : Note<"add an explicit instantiation " "declaration to suppress this warning if %q0 is explicitly instantiated in " "another translation unit">; def note_evaluating_exception_spec_here : Note< "in evaluation of exception specification for %q0 needed here">; def note_default_arg_instantiation_here : Note< "in instantiation of default argument for '%0' required here">; def note_default_function_arg_instantiation_here : Note< "in instantiation of default function argument expression " "for '%0' required here">; def note_explicit_template_arg_substitution_here : Note< "while substituting explicitly-specified template arguments into function " "template %0 %1">; def note_function_template_deduction_instantiation_here : Note< "while substituting deduced template arguments into function template %0 " "%1">; def note_deduced_template_arg_substitution_here : Note< "during template argument deduction for %select{class|variable}0 template " "%select{partial specialization |}1%2 %3">; def note_prior_template_arg_substitution : Note< "while substituting prior template arguments into %select{non-type|template}0" " template parameter%1 %2">; def note_template_default_arg_checking : Note< "while checking a default template argument used here">; def note_instantiation_contexts_suppressed : Note< "(skipping %0 context%s0 in backtrace; use -ftemplate-backtrace-limit=0 to " "see all)">; def err_field_instantiates_to_function : Error< "data member instantiated with function type %0">; def err_variable_instantiates_to_function : Error< "%select{variable|static data member}0 instantiated with function type %1">; def err_nested_name_spec_non_tag : Error< "type %0 cannot be used prior to '::' because it has no members">; def err_using_pack_expansion_empty : Error< "%select{|member}0 using declaration %1 instantiates to an empty pack">; // C++ Explicit Instantiation def err_explicit_instantiation_duplicate : Error< "duplicate explicit instantiation of %0">; def ext_explicit_instantiation_duplicate : ExtWarn< "duplicate explicit instantiation of %0 ignored as a Microsoft extension">, InGroup; def note_previous_explicit_instantiation : Note< "previous explicit instantiation is here">; def warn_explicit_instantiation_after_specialization : Warning< "explicit instantiation of %0 that occurs after an explicit " "specialization has no effect">, InGroup>; def note_previous_template_specialization : Note< "previous template specialization is here">; def err_explicit_instantiation_nontemplate_type : Error< "explicit instantiation of non-templated type %0">; def note_nontemplate_decl_here : Note< "non-templated declaration is here">; def err_explicit_instantiation_in_class : Error< "explicit instantiation of %0 in class scope">; def err_explicit_instantiation_out_of_scope : Error< "explicit instantiation of %0 not in a namespace enclosing %1">; def err_explicit_instantiation_must_be_global : Error< "explicit instantiation of %0 must occur at global scope">; def warn_explicit_instantiation_out_of_scope_0x : Warning< "explicit instantiation of %0 not in a namespace enclosing %1">, InGroup, DefaultIgnore; def warn_explicit_instantiation_must_be_global_0x : Warning< "explicit instantiation of %0 must occur at global scope">, InGroup, DefaultIgnore; def err_explicit_instantiation_requires_name : Error< "explicit instantiation declaration requires a name">; def err_explicit_instantiation_of_typedef : Error< "explicit instantiation of typedef %0">; def err_explicit_instantiation_storage_class : Error< "explicit instantiation cannot have a storage class">; def err_explicit_instantiation_not_known : Error< "explicit instantiation of %0 does not refer to a function template, " "variable template, member function, member class, or static data member">; def note_explicit_instantiation_here : Note< "explicit instantiation refers here">; def err_explicit_instantiation_data_member_not_instantiated : Error< "explicit instantiation refers to static data member %q0 that is not an " "instantiation">; def err_explicit_instantiation_member_function_not_instantiated : Error< "explicit instantiation refers to member function %q0 that is not an " "instantiation">; def err_explicit_instantiation_ambiguous : Error< "partial ordering for explicit instantiation of %0 is ambiguous">; def note_explicit_instantiation_candidate : Note< "explicit instantiation candidate function %q0 template here %1">; def err_explicit_instantiation_inline : Error< "explicit instantiation cannot be 'inline'">; def warn_explicit_instantiation_inline_0x : Warning< "explicit instantiation cannot be 'inline'">, InGroup, DefaultIgnore; def err_explicit_instantiation_constexpr : Error< "explicit instantiation cannot be 'constexpr'">; def ext_explicit_instantiation_without_qualified_id : Extension< "qualifier in explicit instantiation of %q0 requires a template-id " "(a typedef is not permitted)">; def err_explicit_instantiation_without_template_id : Error< "explicit instantiation of %q0 must specify a template argument list">; def err_explicit_instantiation_unqualified_wrong_namespace : Error< "explicit instantiation of %q0 must occur in namespace %1">; def warn_explicit_instantiation_unqualified_wrong_namespace_0x : Warning< "explicit instantiation of %q0 must occur in namespace %1">, InGroup, DefaultIgnore; def err_explicit_instantiation_undefined_member : Error< "explicit instantiation of undefined %select{member class|member function|" "static data member}0 %1 of class template %2">; def err_explicit_instantiation_undefined_func_template : Error< "explicit instantiation of undefined function template %0">; def err_explicit_instantiation_undefined_var_template : Error< "explicit instantiation of undefined variable template %q0">; def err_explicit_instantiation_declaration_after_definition : Error< "explicit instantiation declaration (with 'extern') follows explicit " "instantiation definition (without 'extern')">; def note_explicit_instantiation_definition_here : Note< "explicit instantiation definition is here">; def err_invalid_var_template_spec_type : Error<"type %2 " "of %select{explicit instantiation|explicit specialization|" "partial specialization|redeclaration}0 of %1 does not match" " expected type %3">; def err_mismatched_exception_spec_explicit_instantiation : Error< "exception specification in explicit instantiation does not match " "instantiated one">; def ext_mismatched_exception_spec_explicit_instantiation : ExtWarn< err_mismatched_exception_spec_explicit_instantiation.Text>, InGroup; // C++ typename-specifiers def err_typename_nested_not_found : Error<"no type named %0 in %1">; def err_typename_nested_not_found_enable_if : Error< "no type named 'type' in %0; 'enable_if' cannot be used to disable " "this declaration">; def err_typename_nested_not_found_requirement : Error< "failed requirement '%0'; 'enable_if' cannot be used to disable this " "declaration">; def err_typename_nested_not_type : Error< "typename specifier refers to non-type member %0 in %1">; def note_typename_refers_here : Note< "referenced member %0 is declared here">; def err_typename_missing : Error< "missing 'typename' prior to dependent type name '%0%1'">; def err_typename_missing_template : Error< "missing 'typename' prior to dependent type template name '%0%1'">; def ext_typename_missing : ExtWarn< "missing 'typename' prior to dependent type name '%0%1'">, InGroup>; def ext_typename_outside_of_template : ExtWarn< "'typename' occurs outside of a template">, InGroup; def warn_cxx98_compat_typename_outside_of_template : Warning< "use of 'typename' outside of a template is incompatible with C++98">, InGroup, DefaultIgnore; def err_typename_refers_to_using_value_decl : Error< "typename specifier refers to a dependent using declaration for a value " "%0 in %1">; def note_using_value_decl_missing_typename : Note< "add 'typename' to treat this using declaration as a type">; def err_template_kw_refers_to_non_template : Error< "%0 following the 'template' keyword does not refer to a template">; def note_template_kw_refers_to_non_template : Note< "declared as a non-template here">; def err_template_kw_refers_to_class_template : Error< "'%0%1' instantiated to a class template, not a function template">; def note_referenced_class_template : Note< "class template declared here">; def err_template_kw_missing : Error< "missing 'template' keyword prior to dependent template name '%0%1'">; def ext_template_outside_of_template : ExtWarn< "'template' keyword outside of a template">, InGroup; def warn_cxx98_compat_template_outside_of_template : Warning< "use of 'template' keyword outside of a template is incompatible with C++98">, InGroup, DefaultIgnore; def err_non_type_template_in_nested_name_specifier : Error< "qualified name refers into a specialization of %select{function|variable}0 " "template %1">; def err_template_id_not_a_type : Error< "template name refers to non-type template %0">; def note_template_declared_here : Note< "%select{function template|class template|variable template" "|type alias template|template template parameter}0 " "%1 declared here">; def err_alias_template_expansion_into_fixed_list : Error< "pack expansion used as argument for non-pack parameter of alias template">; def note_parameter_type : Note< "parameter of type %0 is declared here">; // C++11 Variadic Templates def err_template_param_pack_default_arg : Error< "template parameter pack cannot have a default argument">; def err_template_param_pack_must_be_last_template_parameter : Error< "template parameter pack must be the last template parameter">; def err_template_parameter_pack_non_pack : Error< "%select{template type|non-type template|template template}0 parameter" "%select{| pack}1 conflicts with previous %select{template type|" "non-type template|template template}0 parameter%select{ pack|}1">; def note_template_parameter_pack_non_pack : Note< "%select{template type|non-type template|template template}0 parameter" "%select{| pack}1 does not match %select{template type|non-type template" "|template template}0 parameter%select{ pack|}1 in template argument">; def note_template_parameter_pack_here : Note< "previous %select{template type|non-type template|template template}0 " "parameter%select{| pack}1 declared here">; def err_unexpanded_parameter_pack : Error< "%select{expression|base type|declaration type|data member type|bit-field " "size|static assertion|fixed underlying type|enumerator value|" "using declaration|friend declaration|qualifier|initializer|default argument|" "non-type template parameter type|exception type|partial specialization|" "__if_exists name|__if_not_exists name|lambda|block}0 contains" "%plural{0: an|:}1 unexpanded parameter pack" "%plural{0:|1: %2|2:s %2 and %3|:s %2, %3, ...}1">; def err_pack_expansion_without_parameter_packs : Error< "pack expansion does not contain any unexpanded parameter packs">; def err_pack_expansion_length_conflict : Error< "pack expansion contains parameter packs %0 and %1 that have different " "lengths (%2 vs. %3)">; def err_pack_expansion_length_conflict_multilevel : Error< "pack expansion contains parameter pack %0 that has a different " "length (%1 vs. %2) from outer parameter packs">; def err_pack_expansion_length_conflict_partial : Error< "pack expansion contains parameter pack %0 that has a different " "length (at least %1 vs. %2) from outer parameter packs">; def err_pack_expansion_member_init : Error< "pack expansion for initialization of member %0">; def err_function_parameter_pack_without_parameter_packs : Error< "type %0 of function parameter pack does not contain any unexpanded " "parameter packs">; def err_ellipsis_in_declarator_not_parameter : Error< "only function and template parameters can be parameter packs">; def err_sizeof_pack_no_pack_name : Error< "%0 does not refer to the name of a parameter pack">; def err_fold_expression_packs_both_sides : Error< "binary fold expression has unexpanded parameter packs in both operands">; def err_fold_expression_empty : Error< "unary fold expression has empty expansion for operator '%0' " "with no fallback value">; def err_fold_expression_bad_operand : Error< "expression not permitted as operand of fold expression">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< "unexpected namespace name %0: expected expression">; def err_undeclared_var_use : Error<"use of undeclared identifier %0">; def ext_undeclared_unqual_id_with_dependent_base : ExtWarn< "use of undeclared identifier %0; " "unqualified lookup into dependent bases of class template %1 is a Microsoft extension">, InGroup; def ext_found_via_dependent_bases_lookup : ExtWarn<"use of identifier %0 " "found via unqualified lookup into dependent bases of class templates is a " "Microsoft extension">, InGroup; def note_dependent_var_use : Note<"must qualify identifier to find this " "declaration in dependent base class">; def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither " "visible in the template definition nor found by argument-dependent lookup">; def note_not_found_by_two_phase_lookup : Note<"%0 should be declared prior to the " "call site%select{| or in %2| or in an associated namespace of one of its arguments}1">; def err_undeclared_use : Error<"use of undeclared %0">; def warn_deprecated : Warning<"%0 is deprecated">, InGroup; def note_from_diagnose_if : Note<"from 'diagnose_if' attribute on %0:">; def warn_property_method_deprecated : Warning<"property access is using %0 method which is deprecated">, InGroup; def warn_deprecated_message : Warning<"%0 is deprecated: %1">, InGroup; def warn_deprecated_anonymous_namespace : Warning< "'deprecated' attribute on anonymous namespace ignored">, InGroup; def warn_deprecated_fwdclass_message : Warning< "%0 may be deprecated because the receiver type is unknown">, InGroup; def warn_deprecated_def : Warning< "implementing deprecated %select{method|class|category}0">, InGroup, DefaultIgnore; def warn_unavailable_def : Warning< "implementing unavailable method">, InGroup, DefaultIgnore; def err_unavailable : Error<"%0 is unavailable">; def err_property_method_unavailable : Error<"property access is using %0 method which is unavailable">; def err_unavailable_message : Error<"%0 is unavailable: %1">; def warn_unavailable_fwdclass_message : Warning< "%0 may be unavailable because the receiver type is unknown">, InGroup; def note_availability_specified_here : Note< "%0 has been explicitly marked " "%select{unavailable|deleted|deprecated}1 here">; def note_partial_availability_specified_here : Note< "%0 has been marked as being introduced in %1 %2 here, " "but the deployment target is %1 %3">; def note_implicitly_deleted : Note< "explicitly defaulted function was implicitly deleted here">; def warn_not_enough_argument : Warning< "not enough variable arguments in %0 declaration to fit a sentinel">, InGroup; def warn_missing_sentinel : Warning < "missing sentinel in %select{function call|method dispatch|block call}0">, InGroup; def note_sentinel_here : Note< "%select{function|method|block}0 has been explicitly marked sentinel here">; def warn_missing_prototype : Warning< "no previous prototype for function %0">, InGroup>, DefaultIgnore; def note_declaration_not_a_prototype : Note< "this declaration is not a prototype; add 'void' to make it a prototype for a zero-parameter function">; def warn_strict_prototypes : Warning< "this %select{function declaration is not|block declaration is not|" "old-style function definition is not preceded by}0 a prototype">, InGroup>, DefaultIgnore; def warn_missing_variable_declarations : Warning< "no previous extern declaration for non-static variable %0">, InGroup>, DefaultIgnore; def err_static_data_member_reinitialization : Error<"static data member %0 already has an initializer">; def err_redefinition : Error<"redefinition of %0">; def err_alias_after_tentative : Error<"alias definition of %0 after tentative definition">; def err_alias_is_definition : Error<"definition %0 cannot also be an %select{alias|ifunc}1">; def err_definition_of_implicitly_declared_member : Error< "definition of implicitly declared %select{default constructor|copy " "constructor|move constructor|copy assignment operator|move assignment " "operator|destructor|function}1">; def err_definition_of_explicitly_defaulted_member : Error< "definition of explicitly defaulted %select{default constructor|copy " "constructor|move constructor|copy assignment operator|move assignment " "operator|destructor|function}0">; def err_redefinition_extern_inline : Error< "redefinition of a 'extern inline' function %0 is not supported in " "%select{C99 mode|C++}1">; def warn_attr_abi_tag_namespace : Warning< "'abi_tag' attribute on %select{non-inline|anonymous}0 namespace ignored">, InGroup; def err_abi_tag_on_redeclaration : Error< "cannot add 'abi_tag' attribute in a redeclaration">; def err_new_abi_tag_on_redeclaration : Error< "'abi_tag' %0 missing in original declaration">; def note_use_ifdef_guards : Note< "unguarded header; consider using #ifdef guards or #pragma once">; def note_deleted_dtor_no_operator_delete : Note< "virtual destructor requires an unambiguous, accessible 'operator delete'">; def note_deleted_special_member_class_subobject : Note< "%select{default constructor of|copy constructor of|move constructor of|" "copy assignment operator of|move assignment operator of|destructor of|" "constructor inherited by}0 " "%1 is implicitly deleted because " "%select{base class %3|%select{||||variant }4field %3}2 has " "%select{no|a deleted|multiple|an inaccessible|a non-trivial}4 " "%select{%select{default constructor|copy constructor|move constructor|copy " "assignment operator|move assignment operator|destructor|" "%select{default|corresponding|default|default|default}4 constructor}0|" "destructor}5" "%select{||s||}4">; def note_deleted_default_ctor_uninit_field : Note< "%select{default constructor of|constructor inherited by}0 " "%1 is implicitly deleted because field %2 of " "%select{reference|const-qualified}4 type %3 would not be initialized">; def note_deleted_default_ctor_all_const : Note< "%select{default constructor of|constructor inherited by}0 " "%1 is implicitly deleted because all " "%select{data members|data members of an anonymous union member}2" " are const-qualified">; def note_deleted_copy_ctor_rvalue_reference : Note< "copy constructor of %0 is implicitly deleted because field %1 is of " "rvalue reference type %2">; def note_deleted_copy_user_declared_move : Note< "copy %select{constructor|assignment operator}0 is implicitly deleted because" " %1 has a user-declared move %select{constructor|assignment operator}2">; def note_deleted_assign_field : Note< "%select{copy|move}0 assignment operator of %1 is implicitly deleted " "because field %2 is of %select{reference|const-qualified}4 type %3">; // These should be errors. def warn_undefined_internal : Warning< "%select{function|variable}0 %q1 has internal linkage but is not defined">, InGroup>; def err_undefined_internal_type : Error< "%select{function|variable}0 %q1 is used but not defined in this " "translation unit, and cannot be defined in any other translation unit " "because its type does not have linkage">; def ext_undefined_internal_type : Extension< "ISO C++ requires a definition in this translation unit for " "%select{function|variable}0 %q1 because its type does not have linkage">, InGroup>; def warn_undefined_inline : Warning<"inline function %q0 is not defined">, InGroup>; def err_undefined_inline_var : Error<"inline variable %q0 is not defined">; def note_used_here : Note<"used here">; def err_internal_linkage_redeclaration : Error< "'internal_linkage' attribute does not appear on the first declaration of %0">; def warn_internal_linkage_local_storage : Warning< "'internal_linkage' attribute on a non-static local variable is ignored">, InGroup; def ext_internal_in_extern_inline : ExtWarn< "static %select{function|variable}0 %1 is used in an inline function with " "external linkage">, InGroup; def ext_internal_in_extern_inline_quiet : Extension< "static %select{function|variable}0 %1 is used in an inline function with " "external linkage">, InGroup; def warn_static_local_in_extern_inline : Warning< "non-constant static local variable in inline function may be different " "in different files">, InGroup; def note_convert_inline_to_static : Note< "use 'static' to give inline function %0 internal linkage">; def ext_redefinition_of_typedef : ExtWarn< "redefinition of typedef %0 is a C11 feature">, InGroup >; def err_redefinition_variably_modified_typedef : Error< "redefinition of %select{typedef|type alias}0 for variably-modified type %1">; def err_inline_decl_follows_def : Error< "inline declaration of %0 follows non-inline definition">; def err_inline_declaration_block_scope : Error< "inline declaration of %0 not allowed in block scope">; def err_static_non_static : Error< "static declaration of %0 follows non-static declaration">; def err_different_language_linkage : Error< "declaration of %0 has a different language linkage">; def ext_retained_language_linkage : Extension< "friend function %0 retaining previous language linkage is an extension">, InGroup>; def err_extern_c_global_conflict : Error< "declaration of %1 %select{with C language linkage|in global scope}0 " "conflicts with declaration %select{in global scope|with C language linkage}0">; def note_extern_c_global_conflict : Note< "declared %select{in global scope|with C language linkage}0 here">; def note_extern_c_begins_here : Note< "extern \"C\" language linkage specification begins here">; def warn_weak_import : Warning < "an already-declared variable is made a weak_import declaration %0">; def ext_static_non_static : Extension< "redeclaring non-static %0 as static is a Microsoft extension">, InGroup; def err_non_static_static : Error< "non-static declaration of %0 follows static declaration">; def err_extern_non_extern : Error< "extern declaration of %0 follows non-extern declaration">; def err_non_extern_extern : Error< "non-extern declaration of %0 follows extern declaration">; def err_non_thread_thread : Error< "non-thread-local declaration of %0 follows thread-local declaration">; def err_thread_non_thread : Error< "thread-local declaration of %0 follows non-thread-local declaration">; def err_thread_thread_different_kind : Error< "thread-local declaration of %0 with %select{static|dynamic}1 initialization " "follows declaration with %select{dynamic|static}1 initialization">; def err_mismatched_owning_module : Error< "declaration of %0 in %select{the global module|module %2}1 follows " "declaration in %select{the global module|module %4}3">; def err_redefinition_different_type : Error< "redefinition of %0 with a different type%diff{: $ vs $|}1,2">; def err_redefinition_different_kind : Error< "redefinition of %0 as different kind of symbol">; def err_redefinition_different_namespace_alias : Error< "redefinition of %0 as an alias for a different namespace">; def note_previous_namespace_alias : Note< "previously defined as an alias for %0">; def warn_forward_class_redefinition : Warning< "redefinition of forward class %0 of a typedef name of an object type is ignored">, InGroup>; def err_redefinition_different_typedef : Error< "%select{typedef|type alias|type alias template}0 " "redefinition with different types%diff{ ($ vs $)|}1,2">; def err_tag_reference_non_tag : Error< "%select{non-struct type|non-class type|non-union type|non-enum " "type|typedef|type alias|template|type alias template|template " "template argument}1 %0 cannot be referenced with a " "%select{struct|interface|union|class|enum}2 specifier">; def err_tag_reference_conflict : Error< "implicit declaration introduced by elaborated type conflicts with a " "%select{non-struct type|non-class type|non-union type|non-enum " "type|typedef|type alias|template|type alias template|template " "template argument}0 of the same name">; def err_dependent_tag_decl : Error< "%select{declaration|definition}0 of " "%select{struct|interface|union|class|enum}1 in a dependent scope">; def err_tag_definition_of_typedef : Error< "definition of type %0 conflicts with %select{typedef|type alias}1 of the same name">; def err_conflicting_types : Error<"conflicting types for %0">; def err_different_pass_object_size_params : Error< "conflicting pass_object_size attributes on parameters">; def err_late_asm_label_name : Error< "cannot apply asm label to %select{variable|function}0 after its first use">; def err_different_asm_label : Error<"conflicting asm label">; def err_nested_redefinition : Error<"nested redefinition of %0">; def err_use_with_wrong_tag : Error< "use of %0 with tag type that does not match previous declaration">; def warn_struct_class_tag_mismatch : Warning< "%select{struct|interface|class}0%select{| template}1 %2 was previously " "declared as a %select{struct|interface|class}3%select{| template}1; " "this is valid, but may result in linker errors under the Microsoft C++ ABI">, InGroup, DefaultIgnore; def warn_struct_class_previous_tag_mismatch : Warning< "%2 defined as %select{a struct|an interface|a class}0%select{| template}1 " "here but previously declared as " "%select{a struct|an interface|a class}3%select{| template}1; " "this is valid, but may result in linker errors under the Microsoft C++ ABI">, InGroup, DefaultIgnore; def note_struct_class_suggestion : Note< "did you mean %select{struct|interface|class}0 here?">; def ext_forward_ref_enum : Extension< "ISO C forbids forward references to 'enum' types">; def err_forward_ref_enum : Error< "ISO C++ forbids forward references to 'enum' types">; def ext_ms_forward_ref_enum : ExtWarn< "forward references to 'enum' types are a Microsoft extension">, InGroup; def ext_forward_ref_enum_def : Extension< "redeclaration of already-defined enum %0 is a GNU extension">, InGroup; def err_redefinition_of_enumerator : Error<"redefinition of enumerator %0">; def err_duplicate_member : Error<"duplicate member %0">; def err_misplaced_ivar : Error< "instance variables may not be placed in %select{categories|class extension}0">; def warn_ivars_in_interface : Warning< "declaration of instance variables in the interface is deprecated">, InGroup>, DefaultIgnore; def ext_enum_value_not_int : Extension< "ISO C restricts enumerator values to range of 'int' (%0 is too " "%select{small|large}1)">; def ext_enum_too_large : ExtWarn< "enumeration values exceed range of largest integer">, InGroup; def ext_enumerator_increment_too_large : ExtWarn< "incremented enumerator value %0 is not representable in the " "largest integer type">, InGroup; def warn_flag_enum_constant_out_of_range : Warning< "enumeration value %0 is out of range of flags in enumeration type %1">, InGroup; def warn_illegal_constant_array_size : Extension< "size of static array must be an integer constant expression">; def err_vm_decl_in_file_scope : Error< "variably modified type declaration not allowed at file scope">; def err_vm_decl_has_extern_linkage : Error< "variably modified type declaration cannot have 'extern' linkage">; def err_typecheck_field_variable_size : Error< "fields must have a constant size: 'variable length array in structure' " "extension will never be supported">; def err_vm_func_decl : Error< "function declaration cannot have variably modified type">; def err_array_too_large : Error< "array is too large (%0 elements)">; def err_typecheck_negative_array_size : Error<"array size is negative">; def warn_typecheck_function_qualifiers_ignored : Warning< "'%0' qualifier on function type %1 has no effect">, InGroup; def warn_typecheck_function_qualifiers_unspecified : Warning< "'%0' qualifier on function type %1 has unspecified behavior">; def warn_typecheck_reference_qualifiers : Warning< "'%0' qualifier on reference type %1 has no effect">, InGroup; def err_typecheck_invalid_restrict_not_pointer : Error< "restrict requires a pointer or reference (%0 is invalid)">; def err_typecheck_invalid_restrict_not_pointer_noarg : Error< "restrict requires a pointer or reference">; def err_typecheck_invalid_restrict_invalid_pointee : Error< "pointer to function type %0 may not be 'restrict' qualified">; def ext_typecheck_zero_array_size : Extension< "zero size arrays are an extension">, InGroup; def err_typecheck_zero_array_size : Error< "zero-length arrays are not permitted in C++">; def warn_typecheck_zero_static_array_size : Warning< "'static' has no effect on zero-length arrays">, InGroup; def err_array_size_non_int : Error<"size of array has non-integer type %0">; def err_init_element_not_constant : Error< "initializer element is not a compile-time constant">; def ext_aggregate_init_not_constant : Extension< "initializer for aggregate is not a compile-time constant">, InGroup; def err_local_cant_init : Error< "'__local' variable cannot have an initializer">; def err_block_extern_cant_init : Error< "'extern' variable cannot have an initializer">; def warn_extern_init : Warning<"'extern' variable has an initializer">, InGroup>; def err_variable_object_no_init : Error< "variable-sized object may not be initialized">; def err_excess_initializers : Error< "excess elements in %select{array|vector|scalar|union|struct}0 initializer">; def ext_excess_initializers : ExtWarn< "excess elements in %select{array|vector|scalar|union|struct}0 initializer">; def err_excess_initializers_in_char_array_initializer : Error< "excess elements in char array initializer">; def ext_excess_initializers_in_char_array_initializer : ExtWarn< "excess elements in char array initializer">; def err_initializer_string_for_char_array_too_long : Error< "initializer-string for char array is too long">; def ext_initializer_string_for_char_array_too_long : ExtWarn< "initializer-string for char array is too long">; def warn_missing_field_initializers : Warning< "missing field %0 initializer">, InGroup, DefaultIgnore; def warn_braces_around_scalar_init : Warning< "braces around scalar initializer">, InGroup>; def ext_many_braces_around_scalar_init : ExtWarn< "too many braces around scalar initializer">, InGroup>, SFINAEFailure; def ext_complex_component_init : Extension< "complex initialization specifying real and imaginary components " "is an extension">, InGroup>; def err_empty_scalar_initializer : Error<"scalar initializer cannot be empty">; def warn_cxx98_compat_empty_scalar_initializer : Warning< "scalar initialized from empty initializer list is incompatible with C++98">, InGroup, DefaultIgnore; def warn_cxx98_compat_reference_list_init : Warning< "reference initialized from initializer list is incompatible with C++98">, InGroup, DefaultIgnore; def warn_cxx98_compat_initializer_list_init : Warning< "initialization of initializer_list object is incompatible with C++98">, InGroup, DefaultIgnore; def warn_cxx98_compat_ctor_list_init : Warning< "constructor call from initializer list is incompatible with C++98">, InGroup, DefaultIgnore; def err_illegal_initializer : Error< "illegal initializer (only variables can be initialized)">; def err_illegal_initializer_type : Error<"illegal initializer type %0">; def ext_init_list_type_narrowing : ExtWarn< "type %0 cannot be narrowed to %1 in initializer list">, InGroup, DefaultError, SFINAEFailure; def ext_init_list_variable_narrowing : ExtWarn< "non-constant-expression cannot be narrowed from type %0 to %1 in " "initializer list">, InGroup, DefaultError, SFINAEFailure; def ext_init_list_constant_narrowing : ExtWarn< "constant expression evaluates to %0 which cannot be narrowed to type %1">, InGroup, DefaultError, SFINAEFailure; def warn_init_list_type_narrowing : Warning< "type %0 cannot be narrowed to %1 in initializer list in C++11">, InGroup, DefaultIgnore; def warn_init_list_variable_narrowing : Warning< "non-constant-expression cannot be narrowed from type %0 to %1 in " "initializer list in C++11">, InGroup, DefaultIgnore; def warn_init_list_constant_narrowing : Warning< "constant expression evaluates to %0 which cannot be narrowed to type %1 in " "C++11">, InGroup, DefaultIgnore; def note_init_list_narrowing_silence : Note< "insert an explicit cast to silence this issue">; def err_init_objc_class : Error< "cannot initialize Objective-C class type %0">; def err_implicit_empty_initializer : Error< "initializer for aggregate with no elements requires explicit braces">; def err_bitfield_has_negative_width : Error< "bit-field %0 has negative width (%1)">; def err_anon_bitfield_has_negative_width : Error< "anonymous bit-field has negative width (%0)">; def err_bitfield_has_zero_width : Error<"named bit-field %0 has zero width">; def err_bitfield_width_exceeds_type_width : Error< "width of bit-field %0 (%1 bits) exceeds %select{width|size}2 " "of its type (%3 bit%s3)">; def err_anon_bitfield_width_exceeds_type_width : Error< "width of anonymous bit-field (%0 bits) exceeds %select{width|size}1 " "of its type (%2 bit%s2)">; def err_incorrect_number_of_vector_initializers : Error< "number of elements must be either one or match the size of the vector">; // Used by C++ which allows bit-fields that are wider than the type. def warn_bitfield_width_exceeds_type_width: Warning< "width of bit-field %0 (%1 bits) exceeds the width of its type; value will " "be truncated to %2 bit%s2">, InGroup; def warn_anon_bitfield_width_exceeds_type_width : Warning< "width of anonymous bit-field (%0 bits) exceeds width of its type; value " "will be truncated to %1 bit%s1">, InGroup; def warn_bitfield_too_small_for_enum : Warning< "bit-field %0 is not wide enough to store all enumerators of %1">, InGroup, DefaultIgnore; def note_widen_bitfield : Note< "widen this field to %0 bits to store all values of %1">; def warn_unsigned_bitfield_assigned_signed_enum : Warning< "assigning value of signed enum type %1 to unsigned bit-field %0; " "negative enumerators of enum %1 will be converted to positive values">, InGroup, DefaultIgnore; def warn_signed_bitfield_enum_conversion : Warning< "signed bit-field %0 needs an extra bit to represent the largest positive " "enumerators of %1">, InGroup, DefaultIgnore; def note_change_bitfield_sign : Note< "consider making the bitfield type %select{unsigned|signed}0">; def warn_missing_braces : Warning< "suggest braces around initialization of subobject">, InGroup, DefaultIgnore; def err_redefinition_of_label : Error<"redefinition of label %0">; def err_undeclared_label_use : Error<"use of undeclared label %0">; def err_goto_ms_asm_label : Error< "cannot jump from this goto statement to label %0 inside an inline assembly block">; def note_goto_ms_asm_label : Note< "inline assembly label %0 declared here">; def warn_unused_label : Warning<"unused label %0">, InGroup, DefaultIgnore; def err_goto_into_protected_scope : Error< "cannot jump from this goto statement to its label">; def ext_goto_into_protected_scope : ExtWarn< "jump from this goto statement to its label is a Microsoft extension">, InGroup; def warn_cxx98_compat_goto_into_protected_scope : Warning< "jump from this goto statement to its label is incompatible with C++98">, InGroup, DefaultIgnore; def err_switch_into_protected_scope : Error< "cannot jump from switch statement to this case label">; def warn_cxx98_compat_switch_into_protected_scope : Warning< "jump from switch statement to this case label is incompatible with C++98">, InGroup, DefaultIgnore; def err_indirect_goto_without_addrlabel : Error< "indirect goto in function with no address-of-label expressions">; def err_indirect_goto_in_protected_scope : Error< "cannot jump from this indirect goto statement to one of its possible targets">; def warn_cxx98_compat_indirect_goto_in_protected_scope : Warning< "jump from this indirect goto statement to one of its possible targets " "is incompatible with C++98">, InGroup, DefaultIgnore; def note_indirect_goto_target : Note< "possible target of indirect goto statement">; def note_protected_by_variable_init : Note< "jump bypasses variable initialization">; def note_protected_by_variable_nontriv_destructor : Note< "jump bypasses variable with a non-trivial destructor">; def note_protected_by_variable_non_pod : Note< "jump bypasses initialization of non-POD variable">; def note_protected_by_cleanup : Note< "jump bypasses initialization of variable with __attribute__((cleanup))">; def note_protected_by_vla_typedef : Note< "jump bypasses initialization of VLA typedef">; def note_protected_by_vla_type_alias : Note< "jump bypasses initialization of VLA type alias">; def note_protected_by_constexpr_if : Note< "jump enters controlled statement of constexpr if">; def note_protected_by_if_available : Note< "jump enters controlled statement of if available">; def note_protected_by_vla : Note< "jump bypasses initialization of variable length array">; def note_protected_by_objc_fast_enumeration : Note< "jump enters Objective-C fast enumeration loop">; def note_protected_by_objc_try : Note< "jump bypasses initialization of @try block">; def note_protected_by_objc_catch : Note< "jump bypasses initialization of @catch block">; def note_protected_by_objc_finally : Note< "jump bypasses initialization of @finally block">; def note_protected_by_objc_synchronized : Note< "jump bypasses initialization of @synchronized block">; def note_protected_by_objc_autoreleasepool : Note< "jump bypasses auto release push of @autoreleasepool block">; def note_protected_by_cxx_try : Note< "jump bypasses initialization of try block">; def note_protected_by_cxx_catch : Note< "jump bypasses initialization of catch block">; def note_protected_by_seh_try : Note< "jump bypasses initialization of __try block">; def note_protected_by_seh_except : Note< "jump bypasses initialization of __except block">; def note_protected_by_seh_finally : Note< "jump bypasses initialization of __finally block">; def note_protected_by___block : Note< "jump bypasses setup of __block variable">; def note_protected_by_objc_strong_init : Note< "jump bypasses initialization of __strong variable">; def note_protected_by_objc_weak_init : Note< "jump bypasses initialization of __weak variable">; def note_protected_by_non_trivial_c_struct_init : Note< "jump bypasses initialization of variable of non-trivial C struct type">; def note_enters_block_captures_cxx_obj : Note< "jump enters lifetime of block which captures a destructible C++ object">; def note_enters_block_captures_strong : Note< "jump enters lifetime of block which strongly captures a variable">; def note_enters_block_captures_weak : Note< "jump enters lifetime of block which weakly captures a variable">; def note_enters_block_captures_non_trivial_c_struct : Note< "jump enters lifetime of block which captures a C struct that is non-trivial " "to destroy">; def note_exits_cleanup : Note< "jump exits scope of variable with __attribute__((cleanup))">; def note_exits_dtor : Note< "jump exits scope of variable with non-trivial destructor">; def note_exits_temporary_dtor : Note< "jump exits scope of lifetime-extended temporary with non-trivial " "destructor">; def note_exits___block : Note< "jump exits scope of __block variable">; def note_exits_objc_try : Note< "jump exits @try block">; def note_exits_objc_catch : Note< "jump exits @catch block">; def note_exits_objc_finally : Note< "jump exits @finally block">; def note_exits_objc_synchronized : Note< "jump exits @synchronized block">; def note_exits_cxx_try : Note< "jump exits try block">; def note_exits_cxx_catch : Note< "jump exits catch block">; def note_exits_seh_try : Note< "jump exits __try block">; def note_exits_seh_except : Note< "jump exits __except block">; def note_exits_seh_finally : Note< "jump exits __finally block">; def note_exits_objc_autoreleasepool : Note< "jump exits autoreleasepool block">; def note_exits_objc_strong : Note< "jump exits scope of __strong variable">; def note_exits_objc_weak : Note< "jump exits scope of __weak variable">; def note_exits_block_captures_cxx_obj : Note< "jump exits lifetime of block which captures a destructible C++ object">; def note_exits_block_captures_strong : Note< "jump exits lifetime of block which strongly captures a variable">; def note_exits_block_captures_weak : Note< "jump exits lifetime of block which weakly captures a variable">; def note_exits_block_captures_non_trivial_c_struct : Note< "jump exits lifetime of block which captures a C struct that is non-trivial " "to destroy">; def err_func_returning_qualified_void : ExtWarn< "function cannot return qualified void type %0">, InGroup>; def err_func_returning_array_function : Error< "function cannot return %select{array|function}0 type %1">; def err_field_declared_as_function : Error<"field %0 declared as a function">; def err_field_incomplete : Error<"field has incomplete type %0">; def ext_variable_sized_type_in_struct : ExtWarn< "field %0 with variable sized type %1 not at the end of a struct or class is" " a GNU extension">, InGroup; def ext_c99_flexible_array_member : Extension< "flexible array members are a C99 feature">, InGroup; def err_flexible_array_virtual_base : Error< "flexible array member %0 not allowed in " "%select{struct|interface|union|class|enum}1 which has a virtual base class">; def err_flexible_array_empty_aggregate : Error< "flexible array member %0 not allowed in otherwise empty " "%select{struct|interface|union|class|enum}1">; def err_flexible_array_has_nontrivial_dtor : Error< "flexible array member %0 of type %1 with non-trivial destruction">; def ext_flexible_array_in_struct : Extension< "%0 may not be nested in a struct due to flexible array member">, InGroup; def ext_flexible_array_in_array : Extension< "%0 may not be used as an array element due to flexible array member">, InGroup; def err_flexible_array_init : Error< "initialization of flexible array member is not allowed">; def ext_flexible_array_empty_aggregate_ms : Extension< "flexible array member %0 in otherwise empty " "%select{struct|interface|union|class|enum}1 is a Microsoft extension">, InGroup; def err_flexible_array_union : Error< "flexible array member %0 in a union is not allowed">; def ext_flexible_array_union_ms : Extension< "flexible array member %0 in a union is a Microsoft extension">, InGroup; def ext_flexible_array_empty_aggregate_gnu : Extension< "flexible array member %0 in otherwise empty " "%select{struct|interface|union|class|enum}1 is a GNU extension">, InGroup; def ext_flexible_array_union_gnu : Extension< "flexible array member %0 in a union is a GNU extension">, InGroup; def err_flexible_array_not_at_end : Error< "flexible array member %0 with type %1 is not at the end of" " %select{struct|interface|union|class|enum}2">; def err_objc_variable_sized_type_not_at_end : Error< "field %0 with variable sized type %1 is not at the end of class">; def note_next_field_declaration : Note< "next field declaration is here">; def note_next_ivar_declaration : Note< "next %select{instance variable declaration|synthesized instance variable}0" " is here">; def err_synthesize_variable_sized_ivar : Error< "synthesized property with variable size type %0" " requires an existing instance variable">; def err_flexible_array_arc_retainable : Error< "ARC forbids flexible array members with retainable object type">; def warn_variable_sized_ivar_visibility : Warning< "field %0 with variable sized type %1 is not visible to subclasses and" " can conflict with their instance variables">, InGroup; def warn_superclass_variable_sized_type_not_at_end : Warning< "field %0 can overwrite instance variable %1 with variable sized type %2" " in superclass %3">, InGroup; let CategoryName = "ARC Semantic Issue" in { // ARC-mode diagnostics. let CategoryName = "ARC Weak References" in { def err_arc_weak_no_runtime : Error< "cannot create __weak reference because the current deployment target " "does not support weak references">; def err_arc_weak_disabled : Error< "cannot create __weak reference in file using manual reference counting">; def err_synthesizing_arc_weak_property_disabled : Error< "cannot synthesize weak property in file using manual reference counting">; def err_synthesizing_arc_weak_property_no_runtime : Error< "cannot synthesize weak property because the current deployment target " "does not support weak references">; def err_arc_unsupported_weak_class : Error< "class is incompatible with __weak references">; def err_arc_weak_unavailable_assign : Error< "assignment of a weak-unavailable object to a __weak object">; def err_arc_weak_unavailable_property : Error< "synthesizing __weak instance variable of type %0, which does not " "support weak references">; def note_implemented_by_class : Note< "when implemented by class %0">; def err_arc_convesion_of_weak_unavailable : Error< "%select{implicit conversion|cast}0 of weak-unavailable object of type %1 to" " a __weak object of type %2">; } // end "ARC Weak References" category let CategoryName = "ARC Restrictions" in { def err_unavailable_in_arc : Error< "%0 is unavailable in ARC">; def note_arc_forbidden_type : Note< "declaration uses type that is ill-formed in ARC">; def note_performs_forbidden_arc_conversion : Note< "inline function performs a conversion which is forbidden in ARC">; def note_arc_init_returns_unrelated : Note< "init method must return a type related to its receiver type">; def note_arc_weak_disabled : Note< "declaration uses __weak, but ARC is disabled">; def note_arc_weak_no_runtime : Note<"declaration uses __weak, which " "the current deployment target does not support">; def note_arc_field_with_ownership : Note< "field has non-trivial ownership qualification">; def err_arc_illegal_explicit_message : Error< "ARC forbids explicit message send of %0">; def err_arc_unused_init_message : Error< "the result of a delegate init call must be immediately returned " "or assigned to 'self'">; def err_arc_mismatched_cast : Error< "%select{implicit conversion|cast}0 of " "%select{%2|a non-Objective-C pointer type %2|a block pointer|" "an Objective-C pointer|an indirect pointer to an Objective-C pointer}1" " to %3 is disallowed with ARC">; def err_arc_nolifetime_behavior : Error< "explicit ownership qualifier on cast result has no effect">; def err_arc_objc_object_in_tag : Error< "ARC forbids %select{Objective-C objects|blocks}0 in " "%select{struct|interface|union|<>|enum}1">; def err_arc_objc_property_default_assign_on_object : Error< "ARC forbids synthesizing a property of an Objective-C object " "with unspecified ownership or storage attribute">; def err_arc_illegal_selector : Error< "ARC forbids use of %0 in a @selector">; def err_arc_illegal_method_def : Error< "ARC forbids %select{implementation|synthesis}0 of %1">; def warn_arc_strong_pointer_objc_pointer : Warning< "method parameter of type %0 with no explicit ownership">, InGroup>, DefaultIgnore; } // end "ARC Restrictions" category def err_arc_lost_method_convention : Error< "method was declared as %select{an 'alloc'|a 'copy'|an 'init'|a 'new'}0 " "method, but its implementation doesn't match because %select{" "its result type is not an object pointer|" "its result type is unrelated to its receiver type}1">; def note_arc_lost_method_convention : Note<"declaration in interface">; def err_arc_gained_method_convention : Error< "method implementation does not match its declaration">; def note_arc_gained_method_convention : Note< "declaration in interface is not in the '%select{alloc|copy|init|new}0' " "family because %select{its result type is not an object pointer|" "its result type is unrelated to its receiver type}1">; def err_typecheck_arc_assign_self : Error< "cannot assign to 'self' outside of a method in the init family">; def err_typecheck_arc_assign_self_class_method : Error< "cannot assign to 'self' in a class method">; def err_typecheck_arr_assign_enumeration : Error< "fast enumeration variables cannot be modified in ARC by default; " "declare the variable __strong to allow this">; def err_typecheck_arc_assign_externally_retained : Error< "variable declared with 'objc_externally_retained' " "cannot be modified in ARC">; def warn_arc_retained_assign : Warning< "assigning retained object to %select{weak|unsafe_unretained}0 " "%select{property|variable}1" "; object will be released after assignment">, InGroup; def warn_arc_retained_property_assign : Warning< "assigning retained object to unsafe property" "; object will be released after assignment">, InGroup; def warn_arc_literal_assign : Warning< "assigning %select{array literal|dictionary literal|numeric literal|boxed expression||block literal}0" " to a weak %select{property|variable}1" "; object will be released after assignment">, InGroup; def err_arc_new_array_without_ownership : Error< "'new' cannot allocate an array of %0 with no explicit ownership">; def err_arc_autoreleasing_var : Error< "%select{__block variables|global variables|fields|instance variables}0 cannot have " "__autoreleasing ownership">; def err_arc_autoreleasing_capture : Error< "cannot capture __autoreleasing variable in a " "%select{block|lambda by copy}0">; def err_arc_thread_ownership : Error< "thread-local variable has non-trivial ownership: type is %0">; def err_arc_indirect_no_ownership : Error< "%select{pointer|reference}1 to non-const type %0 with no explicit ownership">; def err_arc_array_param_no_ownership : Error< "must explicitly describe intended ownership of an object array parameter">; def err_arc_pseudo_dtor_inconstant_quals : Error< "pseudo-destructor destroys object of type %0 with inconsistently-qualified " "type %1">; def err_arc_init_method_unrelated_result_type : Error< "init methods must return a type related to the receiver type">; def err_arc_nonlocal_writeback : Error< "passing address of %select{non-local|non-scalar}0 object to " "__autoreleasing parameter for write-back">; def err_arc_method_not_found : Error< "no known %select{instance|class}1 method for selector %0">; def err_arc_receiver_forward_class : Error< "receiver %0 for class message is a forward declaration">; def err_arc_may_not_respond : Error< "no visible @interface for %0 declares the selector %1">; def err_arc_receiver_forward_instance : Error< "receiver type %0 for instance message is a forward declaration">; def warn_receiver_forward_instance : Warning< "receiver type %0 for instance message is a forward declaration">, InGroup, DefaultIgnore; def err_arc_collection_forward : Error< "collection expression type %0 is a forward declaration">; def err_arc_multiple_method_decl : Error< "multiple methods named %0 found with mismatched result, " "parameter type or attributes">; def warn_arc_lifetime_result_type : Warning< "ARC %select{unused|__unsafe_unretained|__strong|__weak|__autoreleasing}0 " "lifetime qualifier on return type is ignored">, InGroup; let CategoryName = "ARC Retain Cycle" in { def warn_arc_retain_cycle : Warning< "capturing %0 strongly in this block is likely to lead to a retain cycle">, InGroup; def note_arc_retain_cycle_owner : Note< "block will be retained by %select{the captured object|an object strongly " "retained by the captured object}0">; } // end "ARC Retain Cycle" category def warn_arc_object_memaccess : Warning< "%select{destination for|source of}0 this %1 call is a pointer to " "ownership-qualified type %2">, InGroup; let CategoryName = "ARC and @properties" in { def err_arc_strong_property_ownership : Error< "existing instance variable %1 for strong property %0 may not be " "%select{|__unsafe_unretained||__weak}2">; def err_arc_assign_property_ownership : Error< "existing instance variable %1 for property %0 with %select{unsafe_unretained|assign}2 " "attribute must be __unsafe_unretained">; def err_arc_inconsistent_property_ownership : Error< "%select{|unsafe_unretained|strong|weak}1 property %0 may not also be " "declared %select{|__unsafe_unretained|__strong|__weak|__autoreleasing}2">; } // end "ARC and @properties" category def warn_block_capture_autoreleasing : Warning< "block captures an autoreleasing out-parameter, which may result in " "use-after-free bugs">, InGroup; def note_declare_parameter_strong : Note< "declare the parameter __strong or capture a __block __strong variable to " "keep values alive across autorelease pools">; def err_arc_atomic_ownership : Error< "cannot perform atomic operation on a pointer to type %0: type has " "non-trivial ownership">; let CategoryName = "ARC Casting Rules" in { def err_arc_bridge_cast_incompatible : Error< "incompatible types casting %0 to %1 with a %select{__bridge|" "__bridge_transfer|__bridge_retained}2 cast">; def err_arc_bridge_cast_wrong_kind : Error< "cast of %select{Objective-C|block|C}0 pointer type %1 to " "%select{Objective-C|block|C}2 pointer type %3 cannot use %select{__bridge|" "__bridge_transfer|__bridge_retained}4">; def err_arc_cast_requires_bridge : Error< "%select{cast|implicit conversion}0 of %select{Objective-C|block|C}1 " "pointer type %2 to %select{Objective-C|block|C}3 pointer type %4 " "requires a bridged cast">; def note_arc_bridge : Note< "use __bridge to convert directly (no change in ownership)">; def note_arc_cstyle_bridge : Note< "use __bridge with C-style cast to convert directly (no change in ownership)">; def note_arc_bridge_transfer : Note< "use %select{__bridge_transfer|CFBridgingRelease call}1 to transfer " "ownership of a +1 %0 into ARC">; def note_arc_cstyle_bridge_transfer : Note< "use __bridge_transfer with C-style cast to transfer " "ownership of a +1 %0 into ARC">; def note_arc_bridge_retained : Note< "use %select{__bridge_retained|CFBridgingRetain call}1 to make an " "ARC object available as a +1 %0">; def note_arc_cstyle_bridge_retained : Note< "use __bridge_retained with C-style cast to make an " "ARC object available as a +1 %0">; } // ARC Casting category } // ARC category name def err_flexible_array_init_needs_braces : Error< "flexible array requires brace-enclosed initializer">; def err_illegal_decl_array_of_functions : Error< "'%0' declared as array of functions of type %1">; def err_illegal_decl_array_incomplete_type : Error< "array has incomplete element type %0">; def err_illegal_message_expr_incomplete_type : Error< "Objective-C message has incomplete result type %0">; def err_illegal_decl_array_of_references : Error< "'%0' declared as array of references of type %1">; def err_decl_negative_array_size : Error< "'%0' declared as an array with a negative size">; def err_array_static_outside_prototype : Error< "%0 used in array declarator outside of function prototype">; def err_array_static_not_outermost : Error< "%0 used in non-outermost array type derivation">; def err_array_star_outside_prototype : Error< "star modifier used outside of function prototype">; def err_illegal_decl_pointer_to_reference : Error< "'%0' declared as a pointer to a reference of type %1">; def err_illegal_decl_mempointer_to_reference : Error< "'%0' declared as a member pointer to a reference of type %1">; def err_illegal_decl_mempointer_to_void : Error< "'%0' declared as a member pointer to void">; def err_illegal_decl_mempointer_in_nonclass : Error< "'%0' does not point into a class">; def err_mempointer_in_nonclass_type : Error< "member pointer refers into non-class type %0">; def err_reference_to_void : Error<"cannot form a reference to 'void'">; def err_nonfunction_block_type : Error< "block pointer to non-function type is invalid">; def err_return_block_has_expr : Error<"void block should not return a value">; def err_block_return_missing_expr : Error< "non-void block should return a value">; def err_func_def_incomplete_result : Error< "incomplete result type %0 in function definition">; def err_atomic_specifier_bad_type : Error< "_Atomic cannot be applied to " "%select{incomplete |array |function |reference |atomic |qualified |}0type " "%1 %select{||||||which is not trivially copyable}0">; // Expressions. def select_unary_expr_or_type_trait_kind : TextSubstitution< "%select{sizeof|alignof|vec_step|__builtin_omp_required_simd_align|" "__alignof}0">; def ext_sizeof_alignof_function_type : Extension< "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " "to a function type">, InGroup; def ext_sizeof_alignof_void_type : Extension< "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " "to a void type">, InGroup; def err_opencl_sizeof_alignof_type : Error< "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " "to a void type">; def err_sizeof_alignof_incomplete_type : Error< "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " "to an incomplete type %1">; def err_sizeof_alignof_function_type : Error< "invalid application of '%sub{select_unary_expr_or_type_trait_kind}0' " "to a function type">; def err_openmp_default_simd_align_expr : Error< "invalid application of '__builtin_omp_required_simd_align' to an expression, only type is allowed">; def err_sizeof_alignof_typeof_bitfield : Error< "invalid application of '%select{sizeof|alignof|typeof}0' to bit-field">; def err_alignof_member_of_incomplete_type : Error< "invalid application of 'alignof' to a field of a class still being defined">; def err_vecstep_non_scalar_vector_type : Error< "'vec_step' requires built-in scalar or vector type, %0 invalid">; def err_offsetof_incomplete_type : Error< "offsetof of incomplete type %0">; def err_offsetof_record_type : Error< "offsetof requires struct, union, or class type, %0 invalid">; def err_offsetof_array_type : Error<"offsetof requires array type, %0 invalid">; def ext_offsetof_non_pod_type : ExtWarn<"offset of on non-POD type %0">, InGroup; def ext_offsetof_non_standardlayout_type : ExtWarn< "offset of on non-standard-layout type %0">, InGroup; def err_offsetof_bitfield : Error<"cannot compute offset of bit-field %0">; def err_offsetof_field_of_virtual_base : Error< "invalid application of 'offsetof' to a field of a virtual base">; def warn_sub_ptr_zero_size_types : Warning< "subtraction of pointers to type %0 of zero size has undefined behavior">, InGroup; def warn_pointer_arith_null_ptr : Warning< "performing pointer arithmetic on a null pointer has undefined behavior%select{| if the offset is nonzero}0">, InGroup, DefaultIgnore; def warn_gnu_null_ptr_arith : Warning< "arithmetic on a null pointer treated as a cast from integer to pointer is a GNU extension">, InGroup, DefaultIgnore; def warn_floatingpoint_eq : Warning< "comparing floating point with == or != is unsafe">, InGroup>, DefaultIgnore; def warn_remainder_division_by_zero : Warning< "%select{remainder|division}0 by zero is undefined">, InGroup; def warn_shift_lhs_negative : Warning<"shifting a negative signed value is undefined">, InGroup>; def warn_shift_negative : Warning<"shift count is negative">, InGroup>; def warn_shift_gt_typewidth : Warning<"shift count >= width of type">, InGroup>; def warn_shift_result_gt_typewidth : Warning< "signed shift result (%0) requires %1 bits to represent, but %2 only has " "%3 bits">, InGroup>; def warn_shift_result_sets_sign_bit : Warning< "signed shift result (%0) sets the sign bit of the shift expression's " "type (%1) and becomes negative">, InGroup>, DefaultIgnore; def warn_precedence_bitwise_rel : Warning< "%0 has lower precedence than %1; %1 will be evaluated first">, InGroup; def note_precedence_bitwise_first : Note< "place parentheses around the %0 expression to evaluate it first">; def note_precedence_silence : Note< "place parentheses around the '%0' expression to silence this warning">; def warn_precedence_conditional : Warning< "operator '?:' has lower precedence than '%0'; '%0' will be evaluated first">, InGroup; def note_precedence_conditional_first : Note< "place parentheses around the '?:' expression to evaluate it first">; def warn_logical_instead_of_bitwise : Warning< "use of logical '%0' with constant operand">, InGroup>; def note_logical_instead_of_bitwise_change_operator : Note< "use '%0' for a bitwise operation">; def note_logical_instead_of_bitwise_remove_constant : Note< "remove constant to silence this warning">; def warn_bitwise_op_in_bitwise_op : Warning< "'%0' within '%1'">, InGroup; def warn_logical_and_in_logical_or : Warning< "'&&' within '||'">, InGroup; def warn_overloaded_shift_in_comparison :Warning< "overloaded operator %select{>>|<<}0 has higher precedence than " "comparison operator">, InGroup; def note_evaluate_comparison_first :Note< "place parentheses around comparison expression to evaluate it first">; def warn_addition_in_bitshift : Warning< "operator '%0' has lower precedence than '%1'; " "'%1' will be evaluated first">, InGroup; def warn_self_assignment_builtin : Warning< "explicitly assigning value of variable of type %0 to itself">, InGroup, DefaultIgnore; def warn_self_assignment_overloaded : Warning< "explicitly assigning value of variable of type %0 to itself">, InGroup, DefaultIgnore; def warn_self_move : Warning< "explicitly moving variable of type %0 to itself">, InGroup, DefaultIgnore; def warn_redundant_move_on_return : Warning< "redundant move in return statement">, InGroup, DefaultIgnore; def warn_pessimizing_move_on_return : Warning< "moving a local object in a return statement prevents copy elision">, InGroup, DefaultIgnore; def warn_pessimizing_move_on_initialization : Warning< "moving a temporary object prevents copy elision">, InGroup, DefaultIgnore; def note_remove_move : Note<"remove std::move call here">; def warn_return_std_move : Warning< "local variable %0 will be copied despite being %select{returned|thrown}1 by name">, InGroup, DefaultIgnore; def note_add_std_move : Note< "call 'std::move' explicitly to avoid copying">; def warn_return_std_move_in_cxx11 : Warning< "prior to the resolution of a defect report against ISO C++11, " "local variable %0 would have been copied despite being returned by name, " "due to its not matching the function return type%diff{ ($ vs $)|}1,2">, InGroup, DefaultIgnore; def note_add_std_move_in_cxx11 : Note< "call 'std::move' explicitly to avoid copying on older compilers">; def warn_string_plus_int : Warning< "adding %0 to a string does not append to the string">, InGroup; def warn_string_plus_char : Warning< "adding %0 to a string pointer does not append to the string">, InGroup; def note_string_plus_scalar_silence : Note< "use array indexing to silence this warning">; def warn_sizeof_array_param : Warning< "sizeof on array function parameter will return size of %0 instead of %1">, InGroup; def warn_sizeof_array_decay : Warning< "sizeof on pointer operation will return size of %0 instead of %1">, InGroup; def err_sizeof_nonfragile_interface : Error< "application of '%select{alignof|sizeof}1' to interface %0 is " "not supported on this architecture and platform">; def err_atdef_nonfragile_interface : Error< "use of @defs is not supported on this architecture and platform">; def err_subscript_nonfragile_interface : Error< "subscript requires size of interface %0, which is not constant for " "this architecture and platform">; def err_arithmetic_nonfragile_interface : Error< "arithmetic on pointer to interface %0, which is not a constant size for " "this architecture and platform">; def ext_subscript_non_lvalue : Extension< "ISO C90 does not allow subscripting non-lvalue array">; def err_typecheck_subscript_value : Error< "subscripted value is not an array, pointer, or vector">; def err_typecheck_subscript_not_integer : Error< "array subscript is not an integer">; def err_subscript_function_type : Error< "subscript of pointer to function type %0">; def err_subscript_incomplete_type : Error< "subscript of pointer to incomplete type %0">; def err_dereference_incomplete_type : Error< "dereference of pointer to incomplete type %0">; def ext_gnu_subscript_void_type : Extension< "subscript of a pointer to void is a GNU extension">, InGroup; def err_typecheck_member_reference_struct_union : Error< "member reference base type %0 is not a structure or union">; def err_typecheck_member_reference_ivar : Error< "%0 does not have a member named %1">; def err_arc_weak_ivar_access : Error< "dereferencing a __weak pointer is not allowed due to possible " "null value caused by race condition, assign it to strong variable first">; def err_typecheck_member_reference_arrow : Error< "member reference type %0 is not a pointer">; def err_typecheck_member_reference_suggestion : Error< "member reference type %0 is %select{a|not a}1 pointer; did you mean to use '%select{->|.}1'?">; def note_typecheck_member_reference_suggestion : Note< "did you mean to use '.' instead?">; def note_member_reference_arrow_from_operator_arrow : Note< "'->' applied to return value of the operator->() declared here">; def err_typecheck_member_reference_type : Error< "cannot refer to type member %0 in %1 with '%select{.|->}2'">; def err_typecheck_member_reference_unknown : Error< "cannot refer to member %0 in %1 with '%select{.|->}2'">; def err_member_reference_needs_call : Error< "base of member reference is a function; perhaps you meant to call " "it%select{| with no arguments}0?">; def warn_subscript_is_char : Warning<"array subscript is of type 'char'">, InGroup, DefaultIgnore; def err_typecheck_incomplete_tag : Error<"incomplete definition of type %0">; def err_no_member : Error<"no member named %0 in %1">; def err_no_member_overloaded_arrow : Error< "no member named %0 in %1; did you mean to use '->' instead of '.'?">; def err_member_not_yet_instantiated : Error< "no member %0 in %1; it has not yet been instantiated">; def note_non_instantiated_member_here : Note< "not-yet-instantiated member is declared here">; def err_enumerator_does_not_exist : Error< "enumerator %0 does not exist in instantiation of %1">; def note_enum_specialized_here : Note< "enum %0 was explicitly specialized here">; def err_specialization_not_primary_template : Error< "cannot reference member of primary template because deduced class " "template specialization %0 is %select{instantiated from a partial|" "an explicit}1 specialization">; def err_member_redeclared : Error<"class member cannot be redeclared">; def ext_member_redeclared : ExtWarn<"class member cannot be redeclared">, InGroup; def err_member_redeclared_in_instantiation : Error< "multiple overloads of %0 instantiate to the same signature %1">; def err_member_name_of_class : Error<"member %0 has the same name as its class">; def err_member_def_undefined_record : Error< "out-of-line definition of %0 from class %1 without definition">; def err_member_decl_does_not_match : Error< "out-of-line %select{declaration|definition}2 of %0 " "does not match any declaration in %1">; def err_friend_decl_with_def_arg_must_be_def : Error< "friend declaration specifying a default argument must be a definition">; def err_friend_decl_with_def_arg_redeclared : Error< "friend declaration specifying a default argument must be the only declaration">; def err_friend_decl_does_not_match : Error< "friend declaration of %0 does not match any declaration in %1">; def err_member_decl_does_not_match_suggest : Error< "out-of-line %select{declaration|definition}2 of %0 " "does not match any declaration in %1; did you mean %3?">; def err_member_def_does_not_match_ret_type : Error< "return type of out-of-line definition of %q0 differs from " "that in the declaration">; def err_nonstatic_member_out_of_line : Error< "non-static data member defined out-of-line">; def err_qualified_typedef_declarator : Error< "typedef declarator cannot be qualified">; def err_qualified_param_declarator : Error< "parameter declarator cannot be qualified">; def ext_out_of_line_declaration : ExtWarn< "out-of-line declaration of a member must be a definition">, InGroup, DefaultError; def err_member_extra_qualification : Error< "extra qualification on member %0">; def warn_member_extra_qualification : Warning< err_member_extra_qualification.Text>, InGroup; def warn_namespace_member_extra_qualification : Warning< "extra qualification on member %0">, InGroup>; def err_member_qualification : Error< "non-friend class member %0 cannot have a qualified name">; def note_member_def_close_match : Note<"member declaration nearly matches">; def note_member_def_close_const_match : Note< "member declaration does not match because " "it %select{is|is not}0 const qualified">; def note_member_def_close_param_match : Note< "type of %ordinal0 parameter of member declaration does not match definition" "%diff{ ($ vs $)|}1,2">; def note_local_decl_close_match : Note<"local declaration nearly matches">; def note_local_decl_close_param_match : Note< "type of %ordinal0 parameter of local declaration does not match definition" "%diff{ ($ vs $)|}1,2">; def err_typecheck_ivar_variable_size : Error< "instance variables must have a constant size">; def err_ivar_reference_type : Error< "instance variables cannot be of reference type">; def err_typecheck_illegal_increment_decrement : Error< "cannot %select{decrement|increment}1 value of type %0">; def err_typecheck_expect_int : Error< "used type %0 where integer is required">; def err_typecheck_arithmetic_incomplete_type : Error< "arithmetic on a pointer to an incomplete type %0">; def err_typecheck_pointer_arith_function_type : Error< "arithmetic on%select{ a|}0 pointer%select{|s}0 to%select{ the|}2 " "function type%select{|s}2 %1%select{| and %3}2">; def err_typecheck_pointer_arith_void_type : Error< "arithmetic on%select{ a|}0 pointer%select{|s}0 to void">; def err_typecheck_decl_incomplete_type : Error< "variable has incomplete type %0">; def ext_typecheck_decl_incomplete_type : ExtWarn< "tentative definition of variable with internal linkage has incomplete non-array type %0">, InGroup>; def err_tentative_def_incomplete_type : Error< "tentative definition has type %0 that is never completed">; def warn_tentative_incomplete_array : Warning< "tentative array definition assumed to have one element">; def err_typecheck_incomplete_array_needs_initializer : Error< "definition of variable with array type needs an explicit size " "or an initializer">; def err_array_init_not_init_list : Error< "array initializer must be an initializer " "list%select{| or string literal| or wide string literal}0">; def err_array_init_narrow_string_into_wchar : Error< "initializing wide char array with non-wide string literal">; def err_array_init_wide_string_into_char : Error< "initializing char array with wide string literal">; def err_array_init_incompat_wide_string_into_wchar : Error< "initializing wide char array with incompatible wide string literal">; def err_array_init_plain_string_into_char8_t : Error< "initializing 'char8_t' array with plain string literal">; def note_array_init_plain_string_into_char8_t : Note< "add 'u8' prefix to form a 'char8_t' string literal">; def err_array_init_utf8_string_into_char : Error< "%select{|ISO C++20 does not permit }0initialization of char array with " "UTF-8 string literal%select{ is not permitted by '-fchar8_t'|}0">; def warn_cxx2a_compat_utf8_string : Warning< "type of UTF-8 string literal will change from array of const char to " "array of const char8_t in C++2a">, InGroup, DefaultIgnore; def note_cxx2a_compat_utf8_string_remove_u8 : Note< "remove 'u8' prefix to avoid a change of behavior; " "Clang encodes unprefixed narrow string literals as UTF-8">; def err_array_init_different_type : Error< "cannot initialize array %diff{of type $ with array of type $|" "with different type of array}0,1">; def err_array_init_non_constant_array : Error< "cannot initialize array %diff{of type $ with non-constant array of type $|" "with different type of array}0,1">; def ext_array_init_copy : Extension< "initialization of an array " "%diff{of type $ from a compound literal of type $|" "from a compound literal}0,1 is a GNU extension">, InGroup; // This is intentionally not disabled by -Wno-gnu. def ext_array_init_parens : ExtWarn< "parenthesized initialization of a member array is a GNU extension">, InGroup>, DefaultError; def warn_deprecated_string_literal_conversion : Warning< "conversion from string literal to %0 is deprecated">, InGroup; def ext_deprecated_string_literal_conversion : ExtWarn< "ISO C++11 does not allow conversion from string literal to %0">, InGroup, SFINAEFailure; def err_realimag_invalid_type : Error<"invalid type %0 to %1 operator">; def err_typecheck_sclass_fscope : Error< "illegal storage class on file-scoped variable">; def warn_standalone_specifier : Warning<"'%0' ignored on this declaration">, InGroup; def ext_standalone_specifier : ExtWarn<"'%0' is not permitted on a declaration " "of a type">, InGroup; def err_standalone_class_nested_name_specifier : Error< "forward declaration of %select{class|struct|interface|union|enum}0 cannot " "have a nested name specifier">; def err_typecheck_sclass_func : Error<"illegal storage class on function">; def err_static_block_func : Error< "function declared in block scope cannot have 'static' storage class">; def err_typecheck_address_of : Error<"address of %select{bit-field" "|vector element|property expression|register variable}0 requested">; def ext_typecheck_addrof_void : Extension< "ISO C forbids taking the address of an expression of type 'void'">; def err_unqualified_pointer_member_function : Error< "must explicitly qualify name of member function when taking its address">; def err_invalid_form_pointer_member_function : Error< "cannot create a non-constant pointer to member function">; def err_address_of_function_with_pass_object_size_params: Error< "cannot take address of function %0 because parameter %1 has " "pass_object_size attribute">; def err_parens_pointer_member_function : Error< "cannot parenthesize the name of a method when forming a member pointer">; def err_typecheck_invalid_lvalue_addrof_addrof_function : Error< "extra '&' taking address of overloaded function">; def err_typecheck_invalid_lvalue_addrof : Error< "cannot take the address of an rvalue of type %0">; def ext_typecheck_addrof_temporary : ExtWarn< "taking the address of a temporary object of type %0">, InGroup, DefaultError; def err_typecheck_addrof_temporary : Error< "taking the address of a temporary object of type %0">; def err_typecheck_addrof_dtor : Error< "taking the address of a destructor">; def err_typecheck_unary_expr : Error< "invalid argument type %0 to unary expression">; def err_typecheck_indirection_requires_pointer : Error< "indirection requires pointer operand (%0 invalid)">; def ext_typecheck_indirection_through_void_pointer : ExtWarn< "ISO C++ does not allow indirection on operand of type %0">, InGroup>; def warn_indirection_through_null : Warning< "indirection of non-volatile null pointer will be deleted, not trap">, InGroup; def warn_binding_null_to_reference : Warning< "binding dereferenced null pointer to reference has undefined behavior">, InGroup; def note_indirection_through_null : Note< "consider using __builtin_trap() or qualifying pointer with 'volatile'">; def warn_pointer_indirection_from_incompatible_type : Warning< "dereference of type %1 that was reinterpret_cast from type %0 has undefined " "behavior">, InGroup, DefaultIgnore; def warn_taking_address_of_packed_member : Warning< "taking address of packed member %0 of class or structure %q1 may result in an unaligned pointer value">, InGroup>; def err_objc_object_assignment : Error< "cannot assign to class object (%0 invalid)">; def err_typecheck_invalid_operands : Error< "invalid operands to binary expression (%0 and %1)">; def note_typecheck_invalid_operands_converted : Note< "%select{first|second}0 operand was implicitly converted to type %1">; def err_typecheck_logical_vector_expr_gnu_cpp_restrict : Error< "logical expression with vector %select{type %1 and non-vector type %2|types" " %1 and %2}0 is only supported in C++">; def err_typecheck_sub_ptr_compatible : Error< "%diff{$ and $ are not pointers to compatible types|" "pointers to incompatible types}0,1">; def ext_typecheck_ordered_comparison_of_pointer_integer : ExtWarn< "ordered comparison between pointer and integer (%0 and %1)">; def ext_typecheck_ordered_comparison_of_pointer_and_zero : Extension< "ordered comparison between pointer and zero (%0 and %1) is an extension">; def err_typecheck_ordered_comparison_of_pointer_and_zero : Error< "ordered comparison between pointer and zero (%0 and %1)">; def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn< "ordered comparison of function pointers (%0 and %1)">, InGroup>; def ext_typecheck_comparison_of_fptr_to_void : Extension< "equality comparison between function pointer and void pointer (%0 and %1)">; def err_typecheck_comparison_of_fptr_to_void : Error< "equality comparison between function pointer and void pointer (%0 and %1)">; def ext_typecheck_comparison_of_pointer_integer : ExtWarn< "comparison between pointer and integer (%0 and %1)">, InGroup>; def err_typecheck_comparison_of_pointer_integer : Error< "comparison between pointer and integer (%0 and %1)">; def ext_typecheck_comparison_of_distinct_pointers : ExtWarn< "comparison of distinct pointer types%diff{ ($ and $)|}0,1">, InGroup; def ext_typecheck_cond_incompatible_operands : ExtWarn< "incompatible operand types (%0 and %1)">; def err_cond_voidptr_arc : Error < "operands to conditional of types%diff{ $ and $|}0,1 are incompatible " "in ARC mode">; def err_typecheck_comparison_of_distinct_pointers : Error< "comparison of distinct pointer types%diff{ ($ and $)|}0,1">; def err_typecheck_op_on_nonoverlapping_address_space_pointers : Error< "%select{comparison between %diff{ ($ and $)|}0,1" "|arithmetic operation with operands of type %diff{ ($ and $)|}0,1" "|conditional operator with the second and third operands of type " "%diff{ ($ and $)|}0,1}2" " which are pointers to non-overlapping address spaces">; def err_typecheck_assign_const : Error< "%select{" "cannot assign to return value because function %1 returns a const value|" "cannot assign to variable %1 with const-qualified type %2|" "cannot assign to %select{non-|}1static data member %2 " "with const-qualified type %3|" "cannot assign to non-static data member within const member function %1|" "cannot assign to %select{variable %2|non-static data member %2|lvalue}1 " "with %select{|nested }3const-qualified data member %4|" "read-only variable is not assignable}0">; def note_typecheck_assign_const : Note< "%select{" "function %1 which returns const-qualified type %2 declared here|" "variable %1 declared const here|" "%select{non-|}1static data member %2 declared const here|" "member function %q1 is declared const here|" "%select{|nested }1data member %2 declared const here}0">; def warn_unsigned_always_true_comparison : Warning< "result of comparison of %select{%3|unsigned expression}0 %2 " "%select{unsigned expression|%3}0 is always %4">, InGroup, DefaultIgnore; def warn_unsigned_enum_always_true_comparison : Warning< "result of comparison of %select{%3|unsigned enum expression}0 %2 " "%select{unsigned enum expression|%3}0 is always %4">, InGroup, DefaultIgnore; def warn_tautological_constant_compare : Warning< "result of comparison %select{%3|%1}0 %2 " "%select{%1|%3}0 is always %4">, InGroup, DefaultIgnore; def warn_mixed_sign_comparison : Warning< "comparison of integers of different signs: %0 and %1">, InGroup, DefaultIgnore; def warn_out_of_range_compare : Warning< "result of comparison of %select{constant %0|true|false}1 with " "%select{expression of type %2|boolean expression}3 is always %4">, InGroup; def warn_tautological_bool_compare : Warning, InGroup; def warn_comparison_of_mixed_enum_types : Warning< "comparison of two values with different enumeration types" "%diff{ ($ and $)|}0,1">, InGroup; def warn_comparison_of_mixed_enum_types_switch : Warning< "comparison of two values with different enumeration types in switch statement" "%diff{ ($ and $)|}0,1">, InGroup; def warn_null_in_arithmetic_operation : Warning< "use of NULL in arithmetic operation">, InGroup; def warn_null_in_comparison_operation : Warning< "comparison between NULL and non-pointer " "%select{(%1 and NULL)|(NULL and %1)}0">, InGroup; def err_shift_rhs_only_vector : Error< "requested shift is a vector of type %0 but the first operand is not a " "vector (%1)">; def warn_logical_not_on_lhs_of_check : Warning< "logical not is only applied to the left hand side of this " "%select{comparison|bitwise operator}0">, InGroup; def note_logical_not_fix : Note< "add parentheses after the '!' to evaluate the " "%select{comparison|bitwise operator}0 first">; def note_logical_not_silence_with_parens : Note< "add parentheses around left hand side expression to silence this warning">; def err_invalid_this_use : Error< "invalid use of 'this' outside of a non-static member function">; def err_this_static_member_func : Error< "'this' cannot be%select{| implicitly}0 used in a static member function " "declaration">; def err_invalid_member_use_in_static_method : Error< "invalid use of member %0 in static member function">; def err_invalid_qualified_function_type : Error< "%select{non-member function|static member function|deduction guide}0 " "%select{of type %2 |}1cannot have '%3' qualifier">; def err_compound_qualified_function_type : Error< "%select{block pointer|pointer|reference}0 to function type %select{%2 |}1" "cannot have '%3' qualifier">; def err_ref_qualifier_overload : Error< "cannot overload a member function %select{without a ref-qualifier|with " "ref-qualifier '&'|with ref-qualifier '&&'}0 with a member function %select{" "without a ref-qualifier|with ref-qualifier '&'|with ref-qualifier '&&'}1">; def err_invalid_non_static_member_use : Error< "invalid use of non-static data member %0">; def err_nested_non_static_member_use : Error< "%select{call to non-static member function|use of non-static data member}0 " "%2 of %1 from nested type %3">; def warn_cxx98_compat_non_static_member_use : Warning< "use of non-static data member %0 in an unevaluated context is " "incompatible with C++98">, InGroup, DefaultIgnore; def err_invalid_incomplete_type_use : Error< "invalid use of incomplete type %0">; def err_builtin_func_cast_more_than_one_arg : Error< "function-style cast to a builtin type can only take one argument">; def err_value_init_for_array_type : Error< "array types cannot be value-initialized">; def err_init_for_function_type : Error< "cannot create object of function type %0">; def warn_format_nonliteral_noargs : Warning< "format string is not a string literal (potentially insecure)">, InGroup; def warn_format_nonliteral : Warning< "format string is not a string literal">, InGroup, DefaultIgnore; def err_unexpected_interface : Error< "unexpected interface name %0: expected expression">; def err_ref_non_value : Error<"%0 does not refer to a value">; def err_ref_vm_type : Error< "cannot refer to declaration with a variably modified type inside block">; def err_ref_flexarray_type : Error< "cannot refer to declaration of structure variable with flexible array member " "inside block">; def err_ref_array_type : Error< "cannot refer to declaration with an array type inside block">; def err_property_not_found : Error< "property %0 not found on object of type %1">; def err_invalid_property_name : Error< "%0 is not a valid property name (accessing an object of type %1)">; def err_getter_not_found : Error< "no getter method for read from property">; def err_objc_subscript_method_not_found : Error< "expected method to %select{read|write}1 %select{dictionary|array}2 element not " "found on object of type %0">; def err_objc_subscript_index_type : Error< "method index parameter type %0 is not integral type">; def err_objc_subscript_key_type : Error< "method key parameter type %0 is not object type">; def err_objc_subscript_dic_object_type : Error< "method object parameter type %0 is not object type">; def err_objc_subscript_object_type : Error< "cannot assign to this %select{dictionary|array}1 because assigning method's " "2nd parameter of type %0 is not an Objective-C pointer type">; def err_objc_subscript_base_type : Error< "%select{dictionary|array}1 subscript base type %0 is not an Objective-C object">; def err_objc_multiple_subscript_type_conversion : Error< "indexing expression is invalid because subscript type %0 has " "multiple type conversion functions">; def err_objc_subscript_type_conversion : Error< "indexing expression is invalid because subscript type %0 is not an integral" " or Objective-C pointer type">; def err_objc_subscript_pointer : Error< "indexing expression is invalid because subscript type %0 is not an" " Objective-C pointer">; def err_objc_indexing_method_result_type : Error< "method for accessing %select{dictionary|array}1 element must have Objective-C" " object return type instead of %0">; def err_objc_index_incomplete_class_type : Error< "Objective-C index expression has incomplete class type %0">; def err_illegal_container_subscripting_op : Error< "illegal operation on Objective-C container subscripting">; def err_property_not_found_forward_class : Error< "property %0 cannot be found in forward class object %1">; def err_property_not_as_forward_class : Error< "property %0 refers to an incomplete Objective-C class %1 " "(with no @interface available)">; def note_forward_class : Note< "forward declaration of class here">; def err_duplicate_property : Error< "property has a previous declaration">; def ext_gnu_void_ptr : Extension< "arithmetic on%select{ a|}0 pointer%select{|s}0 to void is a GNU extension">, InGroup; def ext_gnu_ptr_func_arith : Extension< "arithmetic on%select{ a|}0 pointer%select{|s}0 to%select{ the|}2 function " "type%select{|s}2 %1%select{| and %3}2 is a GNU extension">, InGroup; def err_readonly_message_assignment : Error< "assigning to 'readonly' return result of an Objective-C message not allowed">; def ext_integer_increment_complex : Extension< "ISO C does not support '++'/'--' on complex integer type %0">; def ext_integer_complement_complex : Extension< "ISO C does not support '~' for complex conjugation of %0">; def err_nosetter_property_assignment : Error< "%select{assignment to readonly property|" "no setter method %1 for assignment to property}0">; def err_nosetter_property_incdec : Error< "%select{%select{increment|decrement}1 of readonly property|" "no setter method %2 for %select{increment|decrement}1 of property}0">; def err_nogetter_property_compound_assignment : Error< "a getter method is needed to perform a compound assignment on a property">; def err_nogetter_property_incdec : Error< "no getter method %1 for %select{increment|decrement}0 of property">; def err_no_subobject_property_setting : Error< "expression is not assignable">; def err_qualified_objc_access : Error< "%select{property|instance variable}0 access cannot be qualified with '%1'">; def ext_freestanding_complex : Extension< "complex numbers are an extension in a freestanding C99 implementation">; // FIXME: Remove when we support imaginary. def err_imaginary_not_supported : Error<"imaginary types are not supported">; // Obj-c expressions def warn_root_inst_method_not_found : Warning< "instance method %0 is being used on 'Class' which is not in the root class">, InGroup; def warn_class_method_not_found : Warning< "class method %objcclass0 not found (return type defaults to 'id')">, InGroup; def warn_instance_method_on_class_found : Warning< "instance method %0 found instead of class method %1">, InGroup; def warn_inst_method_not_found : Warning< "instance method %objcinstance0 not found (return type defaults to 'id')">, InGroup; def warn_instance_method_not_found_with_typo : Warning< "instance method %objcinstance0 not found (return type defaults to 'id')" "; did you mean %objcinstance2?">, InGroup; def warn_class_method_not_found_with_typo : Warning< "class method %objcclass0 not found (return type defaults to 'id')" "; did you mean %objcclass2?">, InGroup; def err_method_not_found_with_typo : Error< "%select{instance|class}1 method %0 not found " "; did you mean %2?">; def err_no_super_class_message : Error< "no @interface declaration found in class messaging of %0">; def err_root_class_cannot_use_super : Error< "%0 cannot use 'super' because it is a root class">; def err_invalid_receiver_to_message_super : Error< "'super' is only valid in a method body">; def err_invalid_receiver_class_message : Error< "receiver type %0 is not an Objective-C class">; def err_missing_open_square_message_send : Error< "missing '[' at start of message send expression">; def warn_bad_receiver_type : Warning< "receiver type %0 is not 'id' or interface pointer, consider " "casting it to 'id'">,InGroup; def err_bad_receiver_type : Error<"bad receiver type %0">; def err_incomplete_receiver_type : Error<"incomplete receiver type %0">; def err_unknown_receiver_suggest : Error< "unknown receiver %0; did you mean %1?">; def err_objc_throw_expects_object : Error< "@throw requires an Objective-C object type (%0 invalid)">; def err_objc_synchronized_expects_object : Error< "@synchronized requires an Objective-C object type (%0 invalid)">; def err_rethrow_used_outside_catch : Error< "@throw (rethrow) used outside of a @catch block">; def err_attribute_multiple_objc_gc : Error< "multiple garbage collection attributes specified for type">; def err_catch_param_not_objc_type : Error< "@catch parameter is not a pointer to an interface type">; def err_illegal_qualifiers_on_catch_parm : Error< "illegal qualifiers on @catch parameter">; def err_storage_spec_on_catch_parm : Error< "@catch parameter cannot have storage specifier '%0'">; def warn_register_objc_catch_parm : Warning< "'register' storage specifier on @catch parameter will be ignored">; def err_qualified_objc_catch_parm : Error< "@catch parameter declarator cannot be qualified">; def warn_objc_pointer_cxx_catch_fragile : Warning< "cannot catch an exception thrown with @throw in C++ in the non-unified " "exception model">, InGroup; def err_objc_object_catch : Error< "cannot catch an Objective-C object by value">; def err_incomplete_type_objc_at_encode : Error< "'@encode' of incomplete type %0">; def warn_objc_circular_container : Warning< "adding %0 to %1 might cause circular dependency in container">, InGroup>; def note_objc_circular_container_declared_here : Note<"%0 declared here">; def warn_objc_unsafe_perform_selector : Warning< "%0 is incompatible with selectors that return a " "%select{struct|union|vector}1 type">, InGroup>; def note_objc_unsafe_perform_selector_method_declared_here : Note< "method %0 that returns %1 declared here">; def warn_setter_getter_impl_required : Warning< "property %0 requires method %1 to be defined - " "use @synthesize, @dynamic or provide a method implementation " "in this class implementation">, InGroup; def warn_setter_getter_impl_required_in_category : Warning< "property %0 requires method %1 to be defined - " "use @dynamic or provide a method implementation in this category">, InGroup; def note_parameter_named_here : Note< "passing argument to parameter %0 here">; def note_parameter_here : Note< "passing argument to parameter here">; def note_method_return_type_change : Note< "compiler has implicitly changed method %0 return type">; def warn_impl_required_for_class_property : Warning< "class property %0 requires method %1 to be defined - " "use @dynamic or provide a method implementation " "in this class implementation">, InGroup; def warn_impl_required_in_category_for_class_property : Warning< "class property %0 requires method %1 to be defined - " "use @dynamic or provide a method implementation in this category">, InGroup; // C++ casts // These messages adhere to the TryCast pattern: %0 is an int specifying the // cast type, %1 is the source type, %2 is the destination type. def err_bad_reinterpret_cast_overload : Error< "reinterpret_cast cannot resolve overloaded function %0 to type %1">; def warn_reinterpret_different_from_static : Warning< "'reinterpret_cast' %select{from|to}3 class %0 %select{to|from}3 its " "%select{virtual base|base at non-zero offset}2 %1 behaves differently from " "'static_cast'">, InGroup; def note_reinterpret_updowncast_use_static: Note< "use 'static_cast' to adjust the pointer correctly while " "%select{upcasting|downcasting}0">; def err_bad_static_cast_overload : Error< "address of overloaded function %0 cannot be static_cast to type %1">; def err_bad_cstyle_cast_overload : Error< "address of overloaded function %0 cannot be cast to type %1">; def err_bad_cxx_cast_generic : Error< "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from %1 to %2 is not allowed">; def err_bad_cxx_cast_unrelated_class : Error< "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from %1 to %2, which are not related by " "inheritance, is not allowed">; def note_type_incomplete : Note<"%0 is incomplete">; def err_bad_cxx_cast_rvalue : Error< "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from rvalue to reference type %2">; def err_bad_cxx_cast_bitfield : Error< "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from bit-field lvalue to reference type %2">; def err_bad_cxx_cast_qualifiers_away : Error< "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from %1 to %2 casts away qualifiers">; def ext_bad_cxx_cast_qualifiers_away_incoherent : ExtWarn< "ISO C++ does not allow " "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|" "functional-style cast}0 from %1 to %2 because it casts away qualifiers, " "even though the source and destination types are unrelated">, SFINAEFailure, InGroup>; def err_bad_const_cast_dest : Error< "%select{const_cast||||C-style cast|functional-style cast}0 to %2, " "which is not a reference, pointer-to-object, or pointer-to-data-member">; def ext_cast_fn_obj : Extension< "cast between pointer-to-function and pointer-to-object is an extension">; def ext_ms_cast_fn_obj : ExtWarn< "static_cast between pointer-to-function and pointer-to-object is a " "Microsoft extension">, InGroup; def warn_cxx98_compat_cast_fn_obj : Warning< "cast between pointer-to-function and pointer-to-object is incompatible with C++98">, InGroup, DefaultIgnore; def err_bad_reinterpret_cast_small_int : Error< "cast from pointer to smaller type %2 loses information">; def err_bad_cxx_cast_vector_to_scalar_different_size : Error< "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " "to scalar %2 of different size">; def err_bad_cxx_cast_scalar_to_vector_different_size : Error< "%select{||reinterpret_cast||C-style cast|}0 from scalar %1 " "to vector %2 of different size">; def err_bad_cxx_cast_vector_to_vector_different_size : Error< "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " "to vector %2 of different size">; def err_bad_lvalue_to_rvalue_cast : Error< "cannot cast from lvalue of type %1 to rvalue reference type %2; types are " "not compatible">; def err_bad_rvalue_to_rvalue_cast : Error< "cannot cast from rvalue of type %1 to rvalue reference type %2; types are " "not compatible">; def err_bad_static_cast_pointer_nonpointer : Error< "cannot cast from type %1 to pointer type %2">; def err_bad_static_cast_member_pointer_nonmp : Error< "cannot cast from type %1 to member pointer type %2">; def err_bad_cxx_cast_member_pointer_size : Error< "cannot %select{||reinterpret_cast||C-style cast|}0 from member pointer " "type %1 to member pointer type %2 of different size">; def err_bad_reinterpret_cast_reference : Error< "reinterpret_cast of a %0 to %1 needs its address, which is not allowed">; def warn_undefined_reinterpret_cast : Warning< "reinterpret_cast from %0 to %1 has undefined behavior">, InGroup, DefaultIgnore; // These messages don't adhere to the pattern. // FIXME: Display the path somehow better. def err_ambiguous_base_to_derived_cast : Error< "ambiguous cast from base %0 to derived %1:%2">; def err_static_downcast_via_virtual : Error< "cannot cast %0 to %1 via virtual base %2">; def err_downcast_from_inaccessible_base : Error< "cannot cast %select{private|protected}2 base class %1 to %0">; def err_upcast_to_inaccessible_base : Error< "cannot cast %0 to its %select{private|protected}2 base class %1">; def err_bad_dynamic_cast_not_ref_or_ptr : Error< "%0 is not a reference or pointer">; def err_bad_dynamic_cast_not_class : Error<"%0 is not a class">; def err_bad_dynamic_cast_incomplete : Error<"%0 is an incomplete type">; def err_bad_dynamic_cast_not_ptr : Error<"%0 is not a pointer">; def err_bad_dynamic_cast_not_polymorphic : Error<"%0 is not polymorphic">; // Other C++ expressions def err_need_header_before_typeid : Error< "you need to include before using the 'typeid' operator">; def err_need_header_before_ms_uuidof : Error< "you need to include before using the '__uuidof' operator">; def err_ms___leave_not_in___try : Error< "'__leave' statement not in __try block">; def err_uuidof_without_guid : Error< "cannot call operator __uuidof on a type with no GUID">; def err_uuidof_with_multiple_guids : Error< "cannot call operator __uuidof on a type with multiple GUIDs">; def err_incomplete_typeid : Error<"'typeid' of incomplete type %0">; def err_variably_modified_typeid : Error<"'typeid' of variably modified type %0">; def err_static_illegal_in_new : Error< "the 'static' modifier for the array size is not legal in new expressions">; def err_array_new_needs_size : Error< "array size must be specified in new expressions">; def err_bad_new_type : Error< "cannot allocate %select{function|reference}1 type %0 with new">; def err_new_incomplete_type : Error< "allocation of incomplete type %0">; def err_new_array_nonconst : Error< "only the first dimension of an allocated array may have dynamic size">; def err_new_array_init_args : Error< "array 'new' cannot have initialization arguments">; def ext_new_paren_array_nonconst : ExtWarn< "when type is in parentheses, array cannot have dynamic size">; def err_placement_new_non_placement_delete : Error< "'new' expression with placement arguments refers to non-placement " "'operator delete'">; def err_array_size_not_integral : Error< "array size expression must have integral or %select{|unscoped }0" "enumeration type, not %1">; def err_array_size_incomplete_type : Error< "array size expression has incomplete class type %0">; def err_array_size_explicit_conversion : Error< "array size expression of type %0 requires explicit conversion to type %1">; def note_array_size_conversion : Note< "conversion to %select{integral|enumeration}0 type %1 declared here">; def err_array_size_ambiguous_conversion : Error< "ambiguous conversion of array size expression of type %0 to an integral or " "enumeration type">; def ext_array_size_conversion : Extension< "implicit conversion from array size expression of type %0 to " "%select{integral|enumeration}1 type %2 is a C++11 extension">, InGroup; def warn_cxx98_compat_array_size_conversion : Warning< "implicit conversion from array size expression of type %0 to " "%select{integral|enumeration}1 type %2 is incompatible with C++98">, InGroup, DefaultIgnore; def err_address_space_qualified_new : Error< "'new' cannot allocate objects of type %0 in address space '%1'">; def err_address_space_qualified_delete : Error< "'delete' cannot delete objects of type %0 in address space '%1'">; def err_default_init_const : Error< "default initialization of an object of const type %0" "%select{| without a user-provided default constructor}1">; def ext_default_init_const : ExtWarn< "default initialization of an object of const type %0" "%select{| without a user-provided default constructor}1 " "is a Microsoft extension">, InGroup; def err_delete_operand : Error<"cannot delete expression of type %0">; def ext_delete_void_ptr_operand : ExtWarn< "cannot delete expression with pointer-to-'void' type %0">, InGroup; def err_ambiguous_delete_operand : Error< "ambiguous conversion of delete expression of type %0 to a pointer">; def warn_delete_incomplete : Warning< "deleting pointer to incomplete type %0 may cause undefined behavior">, InGroup; def err_delete_incomplete_class_type : Error< "deleting incomplete class type %0; no conversions to pointer type">; def err_delete_explicit_conversion : Error< "converting delete expression from type %0 to type %1 invokes an explicit " "conversion function">; def note_delete_conversion : Note<"conversion to pointer type %0">; def warn_delete_array_type : Warning< "'delete' applied to a pointer-to-array type %0 treated as 'delete[]'">; def warn_mismatched_delete_new : Warning< "'delete%select{|[]}0' applied to a pointer that was allocated with " "'new%select{[]|}0'; did you mean 'delete%select{[]|}0'?">, InGroup>; def note_allocated_here : Note<"allocated with 'new%select{[]|}0' here">; def err_no_suitable_delete_member_function_found : Error< "no suitable member %0 in %1">; def err_ambiguous_suitable_delete_member_function_found : Error< "multiple suitable %0 functions in %1">; def warn_ambiguous_suitable_delete_function_found : Warning< "multiple suitable %0 functions for %1; no 'operator delete' function " "will be invoked if initialization throws an exception">, InGroup>; def note_member_declared_here : Note< "member %0 declared here">; def note_member_first_declared_here : Note< "member %0 first declared here">; def err_decrement_bool : Error<"cannot decrement expression of type bool">; def warn_increment_bool : Warning< "incrementing expression of type bool is deprecated and " "incompatible with C++17">, InGroup; def ext_increment_bool : ExtWarn< "ISO C++17 does not allow incrementing expression of type bool">, DefaultError, InGroup; def err_increment_decrement_enum : Error< "cannot %select{decrement|increment}0 expression of enum type %1">; def err_catch_incomplete_ptr : Error< "cannot catch pointer to incomplete type %0">; def err_catch_incomplete_ref : Error< "cannot catch reference to incomplete type %0">; def err_catch_incomplete : Error<"cannot catch incomplete type %0">; def err_catch_rvalue_ref : Error<"cannot catch exceptions by rvalue reference">; def err_catch_variably_modified : Error< "cannot catch variably modified type %0">; def err_qualified_catch_declarator : Error< "exception declarator cannot be qualified">; def err_early_catch_all : Error<"catch-all handler must come last">; def err_bad_memptr_rhs : Error< "right hand operand to %0 has non-pointer-to-member type %1">; def err_bad_memptr_lhs : Error< "left hand operand to %0 must be a %select{|pointer to }1class " "compatible with the right hand operand, but is %2">; def err_memptr_incomplete : Error< "member pointer has incomplete base type %0">; def warn_exception_caught_by_earlier_handler : Warning< "exception of type %0 will be caught by earlier handler">, InGroup; def note_previous_exception_handler : Note<"for type %0">; def err_exceptions_disabled : Error< "cannot use '%0' with exceptions disabled">; def err_objc_exceptions_disabled : Error< "cannot use '%0' with Objective-C exceptions disabled">; def warn_throw_in_noexcept_func : Warning< "%0 has a non-throwing exception specification but can still throw">, InGroup; def note_throw_in_dtor : Note< "%select{destructor|deallocator}0 has a %select{non-throwing|implicit " "non-throwing}1 exception specification">; def note_throw_in_function : Note<"function declared non-throwing here">; def err_seh_try_outside_functions : Error< "cannot use SEH '__try' in blocks, captured regions, or Obj-C method decls">; def err_mixing_cxx_try_seh_try : Error< "cannot use C++ 'try' in the same function as SEH '__try'">; def err_seh_try_unsupported : Error< "SEH '__try' is not supported on this target">; def note_conflicting_try_here : Note< "conflicting %0 here">; def warn_jump_out_of_seh_finally : Warning< "jump out of __finally block has undefined behavior">, InGroup>; def warn_non_virtual_dtor : Warning< "%0 has virtual functions but non-virtual destructor">, InGroup, DefaultIgnore; def warn_delete_non_virtual_dtor : Warning< "%select{delete|destructor}0 called on non-final %1 that has " "virtual functions but non-virtual destructor">, InGroup, DefaultIgnore, ShowInSystemHeader; def note_delete_non_virtual : Note< "qualify call to silence this warning">; def warn_delete_abstract_non_virtual_dtor : Warning< "%select{delete|destructor}0 called on %1 that is abstract but has " "non-virtual destructor">, InGroup, ShowInSystemHeader; def warn_overloaded_virtual : Warning< "%q0 hides overloaded virtual %select{function|functions}1">, InGroup, DefaultIgnore; def note_hidden_overloaded_virtual_declared_here : Note< "hidden overloaded virtual function %q0 declared here" "%select{|: different classes%diff{ ($ vs $)|}2,3" "|: different number of parameters (%2 vs %3)" "|: type mismatch at %ordinal2 parameter%diff{ ($ vs $)|}3,4" "|: different return type%diff{ ($ vs $)|}2,3" "|: different qualifiers (%2 vs %3)" "|: different exception specifications}1">; def warn_using_directive_in_header : Warning< "using namespace directive in global context in header">, InGroup, DefaultIgnore; def warn_overaligned_type : Warning< "type %0 requires %1 bytes of alignment and the default allocator only " "guarantees %2 bytes">, InGroup, DefaultIgnore; def err_aligned_allocation_unavailable : Error< "aligned %select{allocation|deallocation}0 function of type '%1' is only " "available on %2 %3 or newer">; def note_silence_aligned_allocation_unavailable : Note< "if you supply your own aligned allocation functions, use " "-faligned-allocation to silence this diagnostic">; def err_conditional_void_nonvoid : Error< "%select{left|right}1 operand to ? is void, but %select{right|left}1 operand " "is of type %0">; def err_conditional_ambiguous : Error< "conditional expression is ambiguous; " "%diff{$ can be converted to $ and vice versa|" "types can be convert to each other}0,1">; def err_conditional_ambiguous_ovl : Error< "conditional expression is ambiguous; %diff{$ and $|types}0,1 " "can be converted to several common types">; def err_conditional_vector_size : Error< "vector condition type %0 and result type %1 do not have the same number " "of elements">; def err_conditional_vector_element_size : Error< "vector condition type %0 and result type %1 do not have elements of the " "same size">; def err_throw_incomplete : Error< "cannot throw object of incomplete type %0">; def err_throw_incomplete_ptr : Error< "cannot throw pointer to object of incomplete type %0">; def err_return_in_constructor_handler : Error< "return in the catch of a function try block of a constructor is illegal">; def warn_cdtor_function_try_handler_mem_expr : Warning< "cannot refer to a non-static member from the handler of a " "%select{constructor|destructor}0 function try block">, InGroup; let CategoryName = "Lambda Issue" in { def err_capture_more_than_once : Error< "%0 can appear only once in a capture list">; def err_reference_capture_with_reference_default : Error< "'&' cannot precede a capture when the capture default is '&'">; def err_copy_capture_with_copy_default : Error< "'&' must precede a capture when the capture default is '='">; def err_capture_does_not_name_variable : Error< "%0 in capture list does not name a variable">; def err_capture_non_automatic_variable : Error< "%0 cannot be captured because it does not have automatic storage " "duration">; def err_this_capture : Error< "'this' cannot be %select{implicitly |}0captured in this context">; def err_lambda_capture_anonymous_var : Error< "unnamed variable cannot be implicitly captured in a lambda expression">; def err_lambda_capture_flexarray_type : Error< "variable %0 with flexible array member cannot be captured in " "a lambda expression">; def err_lambda_impcap : Error< "variable %0 cannot be implicitly captured in a lambda with no " "capture-default specified">; def note_lambda_decl : Note<"lambda expression begins here">; def err_lambda_unevaluated_operand : Error< "lambda expression in an unevaluated operand">; def err_lambda_in_constant_expression : Error< "a lambda expression may not appear inside of a constant expression">; def err_lambda_in_invalid_context : Error< "a lambda expression cannot appear in this context">; def err_lambda_return_init_list : Error< "cannot deduce lambda return type from initializer list">; def err_lambda_capture_default_arg : Error< "lambda expression in default argument cannot capture any entity">; def err_lambda_incomplete_result : Error< "incomplete result type %0 in lambda expression">; def err_noreturn_lambda_has_return_expr : Error< "lambda declared 'noreturn' should not return">; def warn_maybe_falloff_nonvoid_lambda : Warning< "control may reach end of non-void lambda">, InGroup; def warn_falloff_nonvoid_lambda : Warning< "control reaches end of non-void lambda">, InGroup; def err_access_lambda_capture : Error< // The ERRORs represent other special members that aren't constructors, in // hopes that someone will bother noticing and reporting if they appear "capture of variable '%0' as type %1 calls %select{private|protected}3 " "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}2constructor">, AccessControl; def note_lambda_to_block_conv : Note< "implicit capture of lambda object due to conversion to block pointer " "here">; def note_var_explicitly_captured_here : Note<"variable %0 is" "%select{| explicitly}1 captured here">; // C++14 lambda init-captures. def warn_cxx11_compat_init_capture : Warning< "initialized lambda captures are incompatible with C++ standards " "before C++14">, InGroup, DefaultIgnore; def ext_init_capture : ExtWarn< "initialized lambda captures are a C++14 extension">, InGroup; def err_init_capture_no_expression : Error< "initializer missing for lambda capture %0">; def err_init_capture_multiple_expressions : Error< "initializer for lambda capture %0 contains multiple expressions">; def err_init_capture_paren_braces : Error< "cannot deduce type for lambda capture %1 from " "%select{parenthesized|nested}0 initializer list">; def err_init_capture_deduction_failure : Error< "cannot deduce type for lambda capture %0 from initializer of type %2">; def err_init_capture_deduction_failure_from_init_list : Error< "cannot deduce type for lambda capture %0 from initializer list">; // C++14 generic lambdas. def warn_cxx11_compat_generic_lambda : Warning< "generic lambdas are incompatible with C++11">, InGroup, DefaultIgnore; // C++17 '*this' captures. def warn_cxx14_compat_star_this_lambda_capture : Warning< "by value capture of '*this' is incompatible with C++ standards before C++17">, InGroup, DefaultIgnore; def ext_star_this_lambda_capture_cxx17 : ExtWarn< "capture of '*this' by copy is a C++17 extension">, InGroup; // C++17 parameter shadows capture def err_parameter_shadow_capture : Error< "a lambda parameter cannot shadow an explicitly captured entity">; // C++2a [=, this] captures. def warn_cxx17_compat_equals_this_lambda_capture : Warning< "explicit capture of 'this' with a capture default of '=' is incompatible " "with C++ standards before C++2a">, InGroup, DefaultIgnore; def ext_equals_this_lambda_capture_cxx2a : ExtWarn< "explicit capture of 'this' with a capture default of '=' " "is a C++2a extension">, InGroup; def warn_deprecated_this_capture : Warning< "implicit capture of 'this' with a capture default of '=' is deprecated">, InGroup, DefaultIgnore; def note_deprecated_this_capture : Note< "add an explicit capture of 'this' to capture '*this' by reference">; // C++2a default constructible / assignable lambdas. def warn_cxx17_compat_lambda_def_ctor_assign : Warning< "%select{default construction|assignment}0 of lambda is incompatible with " "C++ standards before C++2a">, InGroup, DefaultIgnore; } def err_return_in_captured_stmt : Error< "cannot return from %0">; def err_capture_block_variable : Error< "__block variable %0 cannot be captured in a " "%select{lambda expression|captured statement}1">; def err_operator_arrow_circular : Error< "circular pointer delegation detected">; def err_operator_arrow_depth_exceeded : Error< "use of 'operator->' on type %0 would invoke a sequence of more than %1 " "'operator->' calls">; def note_operator_arrow_here : Note< "'operator->' declared here produces an object of type %0">; def note_operator_arrows_suppressed : Note< "(skipping %0 'operator->'%s0 in backtrace)">; def note_operator_arrow_depth : Note< "use -foperator-arrow-depth=N to increase 'operator->' limit">; def err_pseudo_dtor_base_not_scalar : Error< "object expression of non-scalar type %0 cannot be used in a " "pseudo-destructor expression">; def ext_pseudo_dtor_on_void : ExtWarn< "pseudo-destructors on type void are a Microsoft extension">, InGroup; def err_pseudo_dtor_type_mismatch : Error< "the type of object expression " "%diff{($) does not match the type being destroyed ($)|" "does not match the type being destroyed}0,1 " "in pseudo-destructor expression">; def err_pseudo_dtor_call_with_args : Error< "call to pseudo-destructor cannot have any arguments">; def err_dtor_expr_without_call : Error< "reference to %select{destructor|pseudo-destructor}0 must be called" "%select{|; did you mean to call it with no arguments?}1">; def err_pseudo_dtor_destructor_non_type : Error< "%0 does not refer to a type name in pseudo-destructor expression; expected " "the name of type %1">; def err_invalid_use_of_function_type : Error< "a function type is not allowed here">; def err_invalid_use_of_array_type : Error<"an array type is not allowed here">; def err_typecheck_bool_condition : Error< "value of type %0 is not contextually convertible to 'bool'">; def err_typecheck_ambiguous_condition : Error< "conversion %diff{from $ to $|between types}0,1 is ambiguous">; def err_typecheck_nonviable_condition : Error< "no viable conversion%select{%diff{ from $ to $|}1,2|" "%diff{ from returned value of type $ to function return type $|}1,2}0">; def err_typecheck_nonviable_condition_incomplete : Error< "no viable conversion%diff{ from $ to incomplete type $|}0,1">; def err_typecheck_deleted_function : Error< "conversion function %diff{from $ to $|between types}0,1 " "invokes a deleted function">; def err_expected_class_or_namespace : Error<"%0 is not a class" "%select{ or namespace|, namespace, or enumeration}1">; def err_invalid_declarator_scope : Error<"cannot define or redeclare %0 here " "because namespace %1 does not enclose namespace %2">; def err_invalid_declarator_global_scope : Error< "definition or redeclaration of %0 cannot name the global scope">; def err_invalid_declarator_in_function : Error< "definition or redeclaration of %0 not allowed inside a function">; def err_invalid_declarator_in_block : Error< "definition or redeclaration of %0 not allowed inside a block">; def err_not_tag_in_scope : Error< "no %select{struct|interface|union|class|enum}0 named %1 in %2">; def err_no_typeid_with_fno_rtti : Error< "use of typeid requires -frtti">; def err_no_dynamic_cast_with_fno_rtti : Error< "use of dynamic_cast requires -frtti">; def err_cannot_form_pointer_to_member_of_reference_type : Error< "cannot form a pointer-to-member to member %0 of reference type %1">; def err_incomplete_object_call : Error< "incomplete type in call to object of type %0">; def warn_condition_is_assignment : Warning<"using the result of an " "assignment as a condition without parentheses">, InGroup; // Completely identical except off by default. def warn_condition_is_idiomatic_assignment : Warning<"using the result " "of an assignment as a condition without parentheses">, InGroup>, DefaultIgnore; def note_condition_assign_to_comparison : Note< "use '==' to turn this assignment into an equality comparison">; def note_condition_or_assign_to_comparison : Note< "use '!=' to turn this compound assignment into an inequality comparison">; def note_condition_assign_silence : Note< "place parentheses around the assignment to silence this warning">; def warn_equality_with_extra_parens : Warning<"equality comparison with " "extraneous parentheses">, InGroup; def note_equality_comparison_to_assign : Note< "use '=' to turn this equality comparison into an assignment">; def note_equality_comparison_silence : Note< "remove extraneous parentheses around the comparison to silence this warning">; // assignment related diagnostics (also for argument passing, returning, etc). // In most of these diagnostics the %2 is a value from the // Sema::AssignmentAction enumeration def err_typecheck_convert_incompatible : Error< "%select{%diff{assigning to $ from incompatible type $|" "assigning to type from incompatible type}0,1" "|%diff{passing $ to parameter of incompatible type $|" "passing type to parameter of incompatible type}0,1" "|%diff{returning $ from a function with incompatible result type $|" "returning type from a function with incompatible result type}0,1" "|%diff{converting $ to incompatible type $|" "converting type to incompatible type}0,1" "|%diff{initializing $ with an expression of incompatible type $|" "initializing type with an expression of incompatible type}0,1" "|%diff{sending $ to parameter of incompatible type $|" "sending type to parameter of incompatible type}0,1" "|%diff{casting $ to incompatible type $|" "casting type to incompatible type}0,1}2" "%select{|; dereference with *|" "; take the address with &|" "; remove *|" "; remove &}3" "%select{|: different classes%diff{ ($ vs $)|}5,6" "|: different number of parameters (%5 vs %6)" "|: type mismatch at %ordinal5 parameter%diff{ ($ vs $)|}6,7" "|: different return type%diff{ ($ vs $)|}5,6" "|: different qualifiers (%5 vs %6)" "|: different exception specifications}4">; def err_typecheck_missing_return_type_incompatible : Error< "%diff{return type $ must match previous return type $|" "return type must match previous return type}0,1 when %select{block " "literal|lambda expression}2 has unspecified explicit return type">; def note_incomplete_class_and_qualified_id : Note< "conformance of forward class %0 to protocol %1 can not be confirmed">; def warn_incompatible_qualified_id : Warning< "%select{%diff{assigning to $ from incompatible type $|" "assigning to type from incompatible type}0,1" "|%diff{passing $ to parameter of incompatible type $|" "passing type to parameter of incompatible type}0,1" "|%diff{returning $ from a function with incompatible result type $|" "returning type from a function with incompatible result type}0,1" "|%diff{converting $ to incompatible type $|" "converting type to incompatible type}0,1" "|%diff{initializing $ with an expression of incompatible type $|" "initializing type with an expression of incompatible type}0,1" "|%diff{sending $ to parameter of incompatible type $|" "sending type to parameter of incompatible type}0,1" "|%diff{casting $ to incompatible type $|" "casting type to incompatible type}0,1}2">; def ext_typecheck_convert_pointer_int : ExtWarn< "incompatible pointer to integer conversion " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" "%select{|; dereference with *|" "; take the address with &|" "; remove *|" "; remove &}3">, InGroup; def ext_typecheck_convert_int_pointer : ExtWarn< "incompatible integer to pointer conversion " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" "%select{|; dereference with *|" "; take the address with &|" "; remove *|" "; remove &}3">, InGroup; def ext_typecheck_convert_pointer_void_func : Extension< "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " converts between void pointer and function pointer">; def ext_typecheck_convert_incompatible_pointer_sign : ExtWarn< "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " converts between pointers to integer types with different sign">, InGroup>; def ext_typecheck_convert_incompatible_pointer : ExtWarn< "incompatible pointer types " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" "%select{|; dereference with *|" "; take the address with &|" "; remove *|" "; remove &}3">, InGroup; def ext_typecheck_convert_incompatible_function_pointer : ExtWarn< "incompatible function pointer types " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" "%select{|; dereference with *|" "; take the address with &|" "; remove *|" "; remove &}3">, InGroup; def ext_typecheck_convert_discards_qualifiers : ExtWarn< "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " discards qualifiers">, InGroup; def ext_nested_pointer_qualifier_mismatch : ExtWarn< "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " discards qualifiers in nested pointer types">, InGroup; def warn_incompatible_vectors : Warning< "incompatible vector types " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2">, InGroup, DefaultIgnore; def err_int_to_block_pointer : Error< "invalid block pointer conversion " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2">; def err_typecheck_convert_incompatible_block_pointer : Error< "incompatible block pointer types " "%select{%diff{assigning to $ from $|assigning to different types}0,1" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2">; def err_typecheck_incompatible_address_space : Error< "%select{%diff{assigning $ to $|assigning to different types}1,0" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " changes address space of pointer">; def err_typecheck_incompatible_ownership : Error< "%select{%diff{assigning $ to $|assigning to different types}1,0" "|%diff{passing $ to parameter of type $|" "passing to parameter of different type}0,1" "|%diff{returning $ from a function with result type $|" "returning from function with different return type}0,1" "|%diff{converting $ to type $|converting between types}0,1" "|%diff{initializing $ with an expression of type $|" "initializing with expression of different type}0,1" "|%diff{sending $ to parameter of type $|" "sending to parameter of different type}0,1" "|%diff{casting $ to type $|casting between types}0,1}2" " changes retain/release properties of pointer">; def err_typecheck_comparison_of_distinct_blocks : Error< "comparison of distinct block types%diff{ ($ and $)|}0,1">; def err_typecheck_array_not_modifiable_lvalue : Error< "array type %0 is not assignable">; def err_typecheck_non_object_not_modifiable_lvalue : Error< "non-object type %0 is not assignable">; def err_typecheck_expression_not_modifiable_lvalue : Error< "expression is not assignable">; def err_typecheck_incomplete_type_not_modifiable_lvalue : Error< "incomplete type %0 is not assignable">; def err_typecheck_lvalue_casts_not_supported : Error< "assignment to cast is illegal, lvalue casts are not supported">; def err_typecheck_duplicate_vector_components_not_mlvalue : Error< "vector is not assignable (contains duplicate components)">; def err_block_decl_ref_not_modifiable_lvalue : Error< "variable is not assignable (missing __block type specifier)">; def err_lambda_decl_ref_not_modifiable_lvalue : Error< "cannot assign to a variable captured by copy in a non-mutable lambda">; def err_typecheck_call_not_function : Error< "called object type %0 is not a function or function pointer">; def err_call_incomplete_return : Error< "calling function with incomplete return type %0">; def err_call_function_incomplete_return : Error< "calling %0 with incomplete return type %1">; def err_call_incomplete_argument : Error< "argument type %0 is incomplete">; def err_typecheck_call_too_few_args : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected %1, have %2">; def err_typecheck_call_too_few_args_one : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "single argument %1 was not specified">; def err_typecheck_call_too_few_args_at_least : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at least %1, have %2">; def err_typecheck_call_too_few_args_at_least_one : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "at least argument %1 must be specified">; def err_typecheck_call_too_few_args_suggest : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected %1, have %2; did you mean %3?">; def err_typecheck_call_too_few_args_at_least_suggest : Error< "too few %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at least %1, have %2; did you mean %3?">; def err_typecheck_call_too_many_args : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected %1, have %2">; def err_typecheck_call_too_many_args_one : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected single argument %1, have %2 arguments">; def err_typecheck_call_too_many_args_at_most : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at most %1, have %2">; def err_typecheck_call_too_many_args_at_most_one : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at most single argument %1, have %2 arguments">; def err_typecheck_call_too_many_args_suggest : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected %1, have %2; did you mean %3?">; def err_typecheck_call_too_many_args_at_most_suggest : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at most %1, have %2; did you mean %3?">; def err_arc_typecheck_convert_incompatible_pointer : Error< "incompatible pointer types passing retainable parameter of type %0" "to a CF function expecting %1 type">; def err_builtin_fn_use : Error<"builtin functions must be directly called">; def warn_call_wrong_number_of_arguments : Warning< "too %select{few|many}0 arguments in call to %1">; def err_atomic_builtin_must_be_pointer : Error< "address argument to atomic builtin must be a pointer (%0 invalid)">; def err_atomic_builtin_must_be_pointer_intptr : Error< "address argument to atomic builtin must be a pointer to integer or pointer" " (%0 invalid)">; def err_atomic_builtin_cannot_be_const : Error< "address argument to atomic builtin cannot be const-qualified (%0 invalid)">; def err_atomic_builtin_must_be_pointer_intfltptr : Error< "address argument to atomic builtin must be a pointer to integer," " floating-point or pointer (%0 invalid)">; def err_atomic_builtin_pointer_size : Error< "address argument to atomic builtin must be a pointer to 1,2,4,8 or 16 byte " "type (%0 invalid)">; def err_atomic_exclusive_builtin_pointer_size : Error< "address argument to load or store exclusive builtin must be a pointer to" " 1,2,4 or 8 byte type (%0 invalid)">; def err_atomic_op_needs_atomic : Error< "address argument to atomic operation must be a pointer to _Atomic " "type (%0 invalid)">; def err_atomic_op_needs_non_const_atomic : Error< "address argument to atomic operation must be a pointer to non-%select{const|constant}0 _Atomic " "type (%1 invalid)">; def err_atomic_op_needs_non_const_pointer : Error< "address argument to atomic operation must be a pointer to non-const " "type (%0 invalid)">; def err_atomic_op_needs_trivial_copy : Error< "address argument to atomic operation must be a pointer to a " "trivially-copyable type (%0 invalid)">; def err_atomic_op_needs_atomic_int_or_ptr : Error< "address argument to atomic operation must be a pointer to %select{|atomic }0" "integer or pointer (%1 invalid)">; def err_atomic_op_needs_int32_or_ptr : Error< "address argument to atomic operation must be a pointer to signed or unsigned 32-bit integer">; def err_atomic_op_bitwise_needs_atomic_int : Error< "address argument to bitwise atomic operation must be a pointer to " "%select{|atomic }0integer (%1 invalid)">; def warn_atomic_op_has_invalid_memory_order : Warning< "memory order argument to atomic operation is invalid">, InGroup>; def err_atomic_op_has_invalid_synch_scope : Error< "synchronization scope argument to atomic operation is invalid">; def warn_atomic_implicit_seq_cst : Warning< "implicit use of sequentially-consistent atomic may incur stronger memory barriers than necessary">, InGroup>, DefaultIgnore; def err_overflow_builtin_must_be_int : Error< "operand argument to overflow builtin must be an integer (%0 invalid)">; def err_overflow_builtin_must_be_ptr_int : Error< "result argument to overflow builtin must be a pointer " "to a non-const integer (%0 invalid)">; def err_atomic_load_store_uses_lib : Error< "atomic %select{load|store}0 requires runtime support that is not " "available for this target">; def err_nontemporal_builtin_must_be_pointer : Error< "address argument to nontemporal builtin must be a pointer (%0 invalid)">; def err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector : Error< "address argument to nontemporal builtin must be a pointer to integer, float, " "pointer, or a vector of such types (%0 invalid)">; def err_deleted_function_use : Error<"attempt to use a deleted function">; def err_deleted_inherited_ctor_use : Error< "constructor inherited by %0 from base class %1 is implicitly deleted">; def note_called_by : Note<"called by %0">; def err_kern_type_not_void_return : Error< "kernel function type %0 must have void return type">; def err_kern_is_nonstatic_method : Error< "kernel function %0 must be a free function or static member function">; def err_config_scalar_return : Error< "CUDA special function 'cudaConfigureCall' must have scalar return type">; def err_kern_call_not_global_function : Error< "kernel call to non-global function %0">; def err_global_call_not_config : Error< "call to global function %0 not configured">; def err_ref_bad_target : Error< "reference to %select{__device__|__global__|__host__|__host__ __device__}0 " "function %1 in %select{__device__|__global__|__host__|__host__ __device__}2 function">; def err_ref_bad_target_global_initializer : Error< "reference to %select{__device__|__global__|__host__|__host__ __device__}0 " "function %1 in global initializer">; def warn_kern_is_method : Extension< "kernel function %0 is a member function; this may not be accepted by nvcc">, InGroup; def warn_kern_is_inline : Warning< "ignored 'inline' attribute on kernel function %0">, InGroup; def err_variadic_device_fn : Error< "CUDA device code does not support variadic functions">; def err_va_arg_in_device : Error< "CUDA device code does not support va_arg">; def err_alias_not_supported_on_nvptx : Error<"CUDA does not support aliases">; def err_cuda_unattributed_constexpr_cannot_overload_device : Error< "constexpr function %0 without __host__ or __device__ attributes cannot " "overload __device__ function with same signature. Add a __host__ " "attribute, or build with -fno-cuda-host-device-constexpr.">; def note_cuda_conflicting_device_function_declared_here : Note< "conflicting __device__ function declared here">; def err_cuda_device_exceptions : Error< "cannot use '%0' in " "%select{__device__|__global__|__host__|__host__ __device__}1 function">; def err_dynamic_var_init : Error< "dynamic initialization is not supported for " "__device__, __constant__, and __shared__ variables.">; def err_shared_var_init : Error< "initialization is not supported for __shared__ variables.">; def err_device_static_local_var : Error< "within a %select{__device__|__global__|__host__|__host__ __device__}0 " "function, only __shared__ variables or const variables without device " "memory qualifier may be marked 'static'">; def err_cuda_vla : Error< "cannot use variable-length arrays in " "%select{__device__|__global__|__host__|__host__ __device__}0 functions">; def err_cuda_extern_shared : Error<"__shared__ variable %0 cannot be 'extern'">; def err_cuda_host_shared : Error< "__shared__ local variables not allowed in " "%select{__device__|__global__|__host__|__host__ __device__}0 functions">; def err_cuda_nonglobal_constant : Error<"__constant__ variables must be global">; def err_cuda_ovl_target : Error< "%select{__device__|__global__|__host__|__host__ __device__}0 function %1 " "cannot overload %select{__device__|__global__|__host__|__host__ __device__}2 function %3">; def note_cuda_ovl_candidate_target_mismatch : Note< "candidate template ignored: target attributes do not match">; def warn_non_pod_vararg_with_format_string : Warning< "cannot pass %select{non-POD|non-trivial}0 object of type %1 to variadic " "%select{function|block|method|constructor}2; expected type from format " "string was %3">, InGroup, DefaultError; // The arguments to this diagnostic should match the warning above. def err_cannot_pass_objc_interface_to_vararg_format : Error< "cannot pass object with interface type %1 by value to variadic " "%select{function|block|method|constructor}2; expected type from format " "string was %3">; def err_cannot_pass_non_trivial_c_struct_to_vararg : Error< "cannot pass non-trivial C object of type %0 by value to variadic " "%select{function|block|method|constructor}1">; def err_cannot_pass_objc_interface_to_vararg : Error< "cannot pass object with interface type %0 by value through variadic " "%select{function|block|method|constructor}1">; def warn_cannot_pass_non_pod_arg_to_vararg : Warning< "cannot pass object of %select{non-POD|non-trivial}0 type %1 through variadic" " %select{function|block|method|constructor}2; call will abort at runtime">, InGroup, DefaultError; def warn_cxx98_compat_pass_non_pod_arg_to_vararg : Warning< "passing object of trivial but non-POD type %0 through variadic" " %select{function|block|method|constructor}1 is incompatible with C++98">, InGroup, DefaultIgnore; def warn_pass_class_arg_to_vararg : Warning< "passing object of class type %0 through variadic " "%select{function|block|method|constructor}1" "%select{|; did you mean to call '%3'?}2">, InGroup, DefaultIgnore; def err_cannot_pass_to_vararg : Error< "cannot pass %select{expression of type %1|initializer list}0 to variadic " "%select{function|block|method|constructor}2">; def err_cannot_pass_to_vararg_format : Error< "cannot pass %select{expression of type %1|initializer list}0 to variadic " "%select{function|block|method|constructor}2; expected type from format " "string was %3">; def err_typecheck_call_invalid_ordered_compare : Error< "ordered compare requires two args of floating point type" "%diff{ ($ and $)|}0,1">; def err_typecheck_call_invalid_unary_fp : Error< "floating point classification requires argument of floating point type " "(passed in %0)">; def err_typecheck_cond_expect_int_float : Error< "used type %0 where integer or floating point type is required">; def err_typecheck_cond_expect_scalar : Error< "used type %0 where arithmetic or pointer type is required">; def err_typecheck_cond_expect_nonfloat : Error< "used type %0 where floating point type is not allowed">; def ext_typecheck_cond_one_void : Extension< "C99 forbids conditional expressions with only one void side">; def err_typecheck_cast_to_incomplete : Error< "cast to incomplete type %0">; def ext_typecheck_cast_nonscalar : Extension< "C99 forbids casting nonscalar type %0 to the same type">; def ext_typecheck_cast_to_union : Extension< "cast to union type is a GNU extension">, InGroup; def err_typecheck_cast_to_union_no_type : Error< "cast to union type from type %0 not present in union">; def err_cast_pointer_from_non_pointer_int : Error< "operand of type %0 cannot be cast to a pointer type">; def warn_cast_pointer_from_sel : Warning< "cast of type %0 to %1 is deprecated; use sel_getName instead">, InGroup; def warn_function_def_in_objc_container : Warning< "function definition inside an Objective-C container is deprecated">, InGroup; def warn_cast_calling_conv : Warning< "cast between incompatible calling conventions '%0' and '%1'; " "calls through this pointer may abort at runtime">, InGroup>; def note_change_calling_conv_fixit : Note< "consider defining %0 with the '%1' calling convention">; def warn_bad_function_cast : Warning< "cast from function call of type %0 to non-matching type %1">, InGroup, DefaultIgnore; def err_cast_pointer_to_non_pointer_int : Error< "pointer cannot be cast to type %0">; def err_typecheck_expect_scalar_operand : Error< "operand of type %0 where arithmetic or pointer type is required">; def err_typecheck_cond_incompatible_operands : Error< "incompatible operand types%diff{ ($ and $)|}0,1">; def err_cast_selector_expr : Error< "cannot type cast @selector expression">; def ext_typecheck_cond_incompatible_pointers : ExtWarn< "pointer type mismatch%diff{ ($ and $)|}0,1">, InGroup>; def ext_typecheck_cond_pointer_integer_mismatch : ExtWarn< "pointer/integer type mismatch in conditional expression" "%diff{ ($ and $)|}0,1">, InGroup>; def err_typecheck_choose_expr_requires_constant : Error< "'__builtin_choose_expr' requires a constant expression">; def warn_unused_expr : Warning<"expression result unused">, InGroup; def warn_unused_voidptr : Warning< "expression result unused; should this cast be to 'void'?">, InGroup; def warn_unused_property_expr : Warning< "property access result unused - getters should not be used for side effects">, InGroup; def warn_unused_container_subscript_expr : Warning< "container access result unused - container access should not be used for side effects">, InGroup; def warn_unused_call : Warning< "ignoring return value of function declared with %0 attribute">, InGroup; def warn_side_effects_unevaluated_context : Warning< "expression with side effects has no effect in an unevaluated context">, InGroup; def warn_side_effects_typeid : Warning< "expression with side effects will be evaluated despite being used as an " "operand to 'typeid'">, InGroup; def warn_unused_result : Warning< "ignoring return value of function declared with %0 attribute">, InGroup; def warn_unused_volatile : Warning< "expression result unused; assign into a variable to force a volatile load">, InGroup>; def ext_cxx14_attr : Extension< "use of the %0 attribute is a C++14 extension">, InGroup; def ext_cxx17_attr : Extension< "use of the %0 attribute is a C++17 extension">, InGroup; def warn_unused_comparison : Warning< "%select{equality|inequality|relational|three-way}0 comparison result unused">, InGroup; def note_inequality_comparison_to_or_assign : Note< "use '|=' to turn this inequality comparison into an or-assignment">; def err_incomplete_type_used_in_type_trait_expr : Error< "incomplete type %0 used in type trait expression">; def err_require_constant_init_failed : Error< "variable does not have a constant initializer">; def note_declared_required_constant_init_here : Note< "required by 'require_constant_initialization' attribute here">; def err_dimension_expr_not_constant_integer : Error< "dimension expression does not evaluate to a constant unsigned int">; def err_typecheck_cond_incompatible_operands_null : Error< "non-pointer operand type %0 incompatible with %select{NULL|nullptr}1">; def ext_empty_struct_union : Extension< "empty %select{struct|union}0 is a GNU extension">, InGroup; def ext_no_named_members_in_struct_union : Extension< "%select{struct|union}0 without named members is a GNU extension">, InGroup; def warn_zero_size_struct_union_compat : Warning<"%select{|empty }0" "%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++">, InGroup, DefaultIgnore; def warn_zero_size_struct_union_in_extern_c : Warning<"%select{|empty }0" "%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++">, InGroup; def warn_cast_qual : Warning<"cast from %0 to %1 drops %select{const and " "volatile qualifiers|const qualifier|volatile qualifier}2">, InGroup, DefaultIgnore; def warn_cast_qual2 : Warning<"cast from %0 to %1 must have all intermediate " "pointers const qualified to be safe">, InGroup, DefaultIgnore; def warn_redefine_extname_not_applied : Warning< "#pragma redefine_extname is applicable to external C declarations only; " "not applied to %select{function|variable}0 %1">, InGroup; } // End of general sema category. // inline asm. let CategoryName = "Inline Assembly Issue" in { def err_asm_invalid_lvalue_in_output : Error<"invalid lvalue in asm output">; def err_asm_invalid_output_constraint : Error< "invalid output constraint '%0' in asm">; def err_asm_invalid_lvalue_in_input : Error< "invalid lvalue in asm input for constraint '%0'">; def err_asm_invalid_input_constraint : Error< "invalid input constraint '%0' in asm">; def err_asm_immediate_expected : Error<"constraint '%0' expects " "an integer constant expression">; def err_asm_tying_incompatible_types : Error< "unsupported inline asm: input with type " "%diff{$ matching output with type $|}0,1">; def err_asm_unexpected_constraint_alternatives : Error< "asm constraint has an unexpected number of alternatives: %0 vs %1">; def err_asm_incomplete_type : Error<"asm operand has incomplete type %0">; def err_asm_unknown_register_name : Error<"unknown register name '%0' in asm">; def err_asm_invalid_global_var_reg : Error<"register '%0' unsuitable for " "global register variables on this target">; def err_asm_register_size_mismatch : Error<"size of register '%0' does not " "match variable size">; def err_asm_bad_register_type : Error<"bad type for named register variable">; def err_asm_invalid_input_size : Error< "invalid input size for constraint '%0'">; def err_asm_invalid_output_size : Error< "invalid output size for constraint '%0'">; def err_invalid_asm_cast_lvalue : Error< "invalid use of a cast in a inline asm context requiring an l-value: " "remove the cast or build with -fheinous-gnu-extensions">; def err_invalid_asm_value_for_constraint : Error <"value '%0' out of range for constraint '%1'">; def err_asm_non_addr_value_in_memory_constraint : Error < "reference to a %select{bit-field|vector element|global register variable}0" " in asm %select{input|output}1 with a memory constraint '%2'">; def err_asm_input_duplicate_match : Error< "more than one input constraint matches the same output '%0'">; def warn_asm_label_on_auto_decl : Warning< "ignored asm label '%0' on automatic variable">; def warn_invalid_asm_cast_lvalue : Warning< "invalid use of a cast in an inline asm context requiring an l-value: " "accepted due to -fheinous-gnu-extensions, but clang may remove support " "for this in the future">; def warn_asm_mismatched_size_modifier : Warning< "value size does not match register size specified by the constraint " "and modifier">, InGroup; def note_asm_missing_constraint_modifier : Note< "use constraint modifier \"%0\"">; def note_asm_input_duplicate_first : Note< "constraint '%0' is already present here">; } def error_inoutput_conflict_with_clobber : Error< "asm-specifier for input or output variable conflicts with asm" " clobber list">; let CategoryName = "Semantic Issue" in { def err_invalid_conversion_between_vectors : Error< "invalid conversion between vector type%diff{ $ and $|}0,1 of different " "size">; def err_invalid_conversion_between_vector_and_integer : Error< "invalid conversion between vector type %0 and integer type %1 " "of different size">; def err_opencl_function_pointer : Error< "pointers to functions are not allowed">; def err_opencl_taking_address_capture : Error< "taking address of a capture is not allowed">; def err_invalid_conversion_between_vector_and_scalar : Error< "invalid conversion between vector type %0 and scalar type %1">; // C++ member initializers. def err_only_constructors_take_base_inits : Error< "only constructors take base initializers">; def err_multiple_mem_initialization : Error < "multiple initializations given for non-static member %0">; def err_multiple_mem_union_initialization : Error < "initializing multiple members of union">; def err_multiple_base_initialization : Error < "multiple initializations given for base %0">; def err_mem_init_not_member_or_class : Error< "member initializer %0 does not name a non-static data member or base " "class">; def warn_initializer_out_of_order : Warning< "%select{field|base class}0 %1 will be initialized after " "%select{field|base}2 %3">, InGroup, DefaultIgnore; def warn_abstract_vbase_init_ignored : Warning< "initializer for virtual base class %0 of abstract class %1 " "will never be used">, InGroup>, DefaultIgnore; def err_base_init_does_not_name_class : Error< "constructor initializer %0 does not name a class">; def err_base_init_direct_and_virtual : Error< "base class initializer %0 names both a direct base class and an " "inherited virtual base class">; def err_not_direct_base_or_virtual : Error< "type %0 is not a direct or virtual base of %1">; def err_in_class_initializer_non_const : Error< "non-const static data member must be initialized out of line">; def err_in_class_initializer_volatile : Error< "static const volatile data member must be initialized out of line">; def err_in_class_initializer_bad_type : Error< "static data member of type %0 must be initialized out of line">; def ext_in_class_initializer_float_type : ExtWarn< "in-class initializer for static data member of type %0 is a GNU extension">, InGroup; def ext_in_class_initializer_float_type_cxx11 : ExtWarn< "in-class initializer for static data member of type %0 requires " "'constexpr' specifier">, InGroup, DefaultError; def note_in_class_initializer_float_type_cxx11 : Note<"add 'constexpr'">; def err_in_class_initializer_literal_type : Error< "in-class initializer for static data member of type %0 requires " "'constexpr' specifier">; def err_in_class_initializer_non_constant : Error< "in-class initializer for static data member is not a constant expression">; def err_in_class_initializer_not_yet_parsed : Error< "default member initializer for %1 needed within definition of enclosing " "class %0 outside of member functions">; def note_in_class_initializer_not_yet_parsed : Note< "default member initializer declared here">; def err_in_class_initializer_cycle : Error<"default member initializer for %0 uses itself">; def ext_in_class_initializer_non_constant : Extension< "in-class initializer for static data member is not a constant expression; " "folding it to a constant is a GNU extension">, InGroup; def err_thread_dynamic_init : Error< "initializer for thread-local variable must be a constant expression">; def err_thread_nontrivial_dtor : Error< "type of thread-local variable has non-trivial destruction">; def note_use_thread_local : Note< "use 'thread_local' to allow this">; // C++ anonymous unions and GNU anonymous structs/unions def ext_anonymous_union : Extension< "anonymous unions are a C11 extension">, InGroup; def ext_gnu_anonymous_struct : Extension< "anonymous structs are a GNU extension">, InGroup; def ext_c11_anonymous_struct : Extension< "anonymous structs are a C11 extension">, InGroup; def err_anonymous_union_not_static : Error< "anonymous unions at namespace or global scope must be declared 'static'">; def err_anonymous_union_with_storage_spec : Error< "anonymous union at class scope must not have a storage specifier">; def err_anonymous_struct_not_member : Error< "anonymous %select{structs|structs and classes}0 must be " "%select{struct or union|class}0 members">; def err_anonymous_record_member_redecl : Error< "member of anonymous %select{struct|union}0 redeclares %1">; def err_anonymous_record_with_type : Error< "types cannot be declared in an anonymous %select{struct|union}0">; def ext_anonymous_record_with_type : Extension< "types declared in an anonymous %select{struct|union}0 are a Microsoft " "extension">, InGroup; def ext_anonymous_record_with_anonymous_type : Extension< "anonymous types declared in an anonymous %select{struct|union}0 " "are an extension">, InGroup>; def err_anonymous_record_with_function : Error< "functions cannot be declared in an anonymous %select{struct|union}0">; def err_anonymous_record_with_static : Error< "static members cannot be declared in an anonymous %select{struct|union}0">; def err_anonymous_record_bad_member : Error< "anonymous %select{struct|union}0 can only contain non-static data members">; def err_anonymous_record_nonpublic_member : Error< "anonymous %select{struct|union}0 cannot contain a " "%select{private|protected}1 data member">; def ext_ms_anonymous_record : ExtWarn< "anonymous %select{structs|unions}0 are a Microsoft extension">, InGroup; // C++ local classes def err_reference_to_local_in_enclosing_context : Error< "reference to local %select{variable|binding}1 %0 declared in enclosing " "%select{%3|block literal|lambda expression|context}2">; def err_static_data_member_not_allowed_in_local_class : Error< "static data member %0 not allowed in local class %1">; // C++ derived classes def err_base_clause_on_union : Error<"unions cannot have base classes">; def err_base_must_be_class : Error<"base specifier must name a class">; def err_union_as_base_class : Error<"unions cannot be base classes">; def err_circular_inheritance : Error< "circular inheritance between %0 and %1">; def err_base_class_has_flexible_array_member : Error< "base class %0 has a flexible array member">; def err_incomplete_base_class : Error<"base class has incomplete type">; def err_duplicate_base_class : Error< "base class %0 specified more than once as a direct base class">; def warn_inaccessible_base_class : Warning< "direct base %0 is inaccessible due to ambiguity:%1">, InGroup>; // FIXME: better way to display derivation? Pass entire thing into diagclient? def err_ambiguous_derived_to_base_conv : Error< "ambiguous conversion from derived class %0 to base class %1:%2">; def err_ambiguous_memptr_conv : Error< "ambiguous conversion from pointer to member of %select{base|derived}0 " "class %1 to pointer to member of %select{derived|base}0 class %2:%3">; def ext_ms_ambiguous_direct_base : ExtWarn< "accessing inaccessible direct base %0 of %1 is a Microsoft extension">, InGroup; def err_memptr_conv_via_virtual : Error< "conversion from pointer to member of class %0 to pointer to member " "of class %1 via virtual base %2 is not allowed">; // C++ member name lookup def err_ambiguous_member_multiple_subobjects : Error< "non-static member %0 found in multiple base-class subobjects of type %1:%2">; def err_ambiguous_member_multiple_subobject_types : Error< "member %0 found in multiple base classes of different types">; def note_ambiguous_member_found : Note<"member found by ambiguous name lookup">; def err_ambiguous_reference : Error<"reference to %0 is ambiguous">; def note_ambiguous_candidate : Note<"candidate found by name lookup is %q0">; def err_ambiguous_tag_hiding : Error<"a type named %0 is hidden by a " "declaration in a different namespace">; def note_hidden_tag : Note<"type declaration hidden">; def note_hiding_object : Note<"declaration hides type">; // C++ operator overloading def err_operator_overload_needs_class_or_enum : Error< "overloaded %0 must have at least one parameter of class " "or enumeration type">; def err_operator_overload_variadic : Error<"overloaded %0 cannot be variadic">; def err_operator_overload_static : Error< "overloaded %0 cannot be a static member function">; def err_operator_overload_default_arg : Error< "parameter of overloaded %0 cannot have a default argument">; def err_operator_overload_must_be : Error< "overloaded %0 must be a %select{unary|binary|unary or binary}2 operator " "(has %1 parameter%s1)">; def err_operator_overload_must_be_member : Error< "overloaded %0 must be a non-static member function">; def err_operator_overload_post_incdec_must_be_int : Error< "parameter of overloaded post-%select{increment|decrement}1 operator must " "have type 'int' (not %0)">; // C++ allocation and deallocation functions. def err_operator_new_delete_declared_in_namespace : Error< "%0 cannot be declared inside a namespace">; def err_operator_new_delete_declared_static : Error< "%0 cannot be declared static in global scope">; def ext_operator_new_delete_declared_inline : ExtWarn< "replacement function %0 cannot be declared 'inline'">, InGroup>; def err_operator_new_delete_invalid_result_type : Error< "%0 must return type %1">; def err_operator_new_delete_dependent_result_type : Error< "%0 cannot have a dependent return type; use %1 instead">; def err_operator_new_delete_too_few_parameters : Error< "%0 must have at least one parameter">; def err_operator_new_delete_template_too_few_parameters : Error< "%0 template must have at least two parameters">; def warn_operator_new_returns_null : Warning< "%0 should not return a null pointer unless it is declared 'throw()'" "%select{| or 'noexcept'}1">, InGroup; def err_operator_new_dependent_param_type : Error< "%0 cannot take a dependent type as first parameter; " "use size_t (%1) instead">; def err_operator_new_param_type : Error< "%0 takes type size_t (%1) as first parameter">; def err_operator_new_default_arg: Error< "parameter of %0 cannot have a default argument">; def err_operator_delete_dependent_param_type : Error< "%0 cannot take a dependent type as first parameter; use %1 instead">; def err_operator_delete_param_type : Error< "first parameter of %0 must have type %1">; def err_destroying_operator_delete_not_usual : Error< "destroying operator delete can have only an optional size and optional " "alignment parameter">; def note_implicit_delete_this_in_destructor_here : Note< "while checking implicit 'delete this' for virtual destructor">; def err_builtin_operator_new_delete_not_usual : Error< "call to '%select{__builtin_operator_new|__builtin_operator_delete}0' " "selects non-usual %select{allocation|deallocation}0 function">; def note_non_usual_function_declared_here : Note< "non-usual %0 declared here">; // C++ literal operators def err_literal_operator_outside_namespace : Error< "literal operator %0 must be in a namespace or global scope">; def err_literal_operator_id_outside_namespace : Error< "non-namespace scope '%0' cannot have a literal operator member">; def err_literal_operator_default_argument : Error< "literal operator cannot have a default argument">; def err_literal_operator_bad_param_count : Error< "non-template literal operator must have one or two parameters">; def err_literal_operator_invalid_param : Error< "parameter of literal operator must have type 'unsigned long long', 'long double', 'char', 'wchar_t', 'char16_t', 'char32_t', or 'const char *'">; def err_literal_operator_param : Error< "invalid literal operator parameter type %0, did you mean %1?">; def err_literal_operator_template_with_params : Error< "literal operator template cannot have any parameters">; def err_literal_operator_template : Error< "template parameter list for literal operator must be either 'char...' or 'typename T, T...'">; def err_literal_operator_extern_c : Error< "literal operator must have C++ linkage">; def ext_string_literal_operator_template : ExtWarn< "string literal operator templates are a GNU extension">, InGroup; def warn_user_literal_reserved : Warning< "user-defined literal suffixes not starting with '_' are reserved" "%select{; no literal will invoke this operator|}0">, InGroup; // C++ conversion functions def err_conv_function_not_member : Error< "conversion function must be a non-static member function">; def err_conv_function_return_type : Error< "conversion function cannot have a return type">; def err_conv_function_with_params : Error< "conversion function cannot have any parameters">; def err_conv_function_variadic : Error< "conversion function cannot be variadic">; def err_conv_function_to_array : Error< "conversion function cannot convert to an array type">; def err_conv_function_to_function : Error< "conversion function cannot convert to a function type">; def err_conv_function_with_complex_decl : Error< "cannot specify any part of a return type in the " "declaration of a conversion function" "%select{" "; put the complete type after 'operator'|" "; use a typedef to declare a conversion to %1|" "; use an alias template to declare a conversion to %1|" "}0">; def err_conv_function_redeclared : Error< "conversion function cannot be redeclared">; def warn_conv_to_self_not_used : Warning< "conversion function converting %0 to itself will never be used">; def warn_conv_to_base_not_used : Warning< "conversion function converting %0 to its base class %1 will never be used">; def warn_conv_to_void_not_used : Warning< "conversion function converting %0 to %1 will never be used">; def warn_not_compound_assign : Warning< "use of unary operator that may be intended as compound assignment (%0=)">; // C++11 explicit conversion operators def ext_explicit_conversion_functions : ExtWarn< "explicit conversion functions are a C++11 extension">, InGroup; def warn_cxx98_compat_explicit_conversion_functions : Warning< "explicit conversion functions are incompatible with C++98">, InGroup, DefaultIgnore; // C++11 defaulted functions def err_defaulted_special_member_params : Error< "an explicitly-defaulted %select{|copy |move }0constructor cannot " "have default arguments">; def err_defaulted_special_member_variadic : Error< "an explicitly-defaulted %select{|copy |move }0constructor cannot " "be variadic">; def err_defaulted_special_member_return_type : Error< "explicitly-defaulted %select{copy|move}0 assignment operator must " "return %1">; def err_defaulted_special_member_quals : Error< "an explicitly-defaulted %select{copy|move}0 assignment operator may not " "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">; def err_defaulted_special_member_volatile_param : Error< "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 " "may not be volatile">; def err_defaulted_special_member_move_const_param : Error< "the parameter for an explicitly-defaulted move " "%select{constructor|assignment operator}0 may not be const">; def err_defaulted_special_member_copy_const_param : Error< "the parameter for this explicitly-defaulted copy " "%select{constructor|assignment operator}0 is const, but a member or base " "requires it to be non-const">; def err_defaulted_copy_assign_not_ref : Error< "the parameter for an explicitly-defaulted copy assignment operator must be an " "lvalue reference type">; def err_incorrect_defaulted_exception_spec : Error< "exception specification of explicitly defaulted " "%sub{select_special_member_kind}0 does not match the calculated one">; def err_incorrect_defaulted_constexpr : Error< "defaulted definition of %sub{select_special_member_kind}0 " "is not constexpr">; def warn_defaulted_method_deleted : Warning< "explicitly defaulted %sub{select_special_member_kind}0 is implicitly " "deleted">, InGroup>; def err_out_of_line_default_deletes : Error< "defaulting this %sub{select_special_member_kind}0 " "would delete it after its first declaration">; def note_deleted_type_mismatch : Note< "function is implicitly deleted because its declared type does not match " "the type of an implicit %sub{select_special_member_kind}0">; def warn_cxx17_compat_defaulted_method_type_mismatch : Warning< "explicitly defaulting this %sub{select_special_member_kind}0 with a type " "different from the implicit type is incompatible with C++ standards before " "C++2a">, InGroup, DefaultIgnore; def warn_vbase_moved_multiple_times : Warning< "defaulted move assignment operator of %0 will move assign virtual base " "class %1 multiple times">, InGroup>; def note_vbase_moved_here : Note< "%select{%1 is a virtual base class of base class %2 declared here|" "virtual base class %1 declared here}0">; def ext_implicit_exception_spec_mismatch : ExtWarn< "function previously declared with an %select{explicit|implicit}0 exception " "specification redeclared with an %select{implicit|explicit}0 exception " "specification">, InGroup>; def warn_ptr_arith_precedes_bounds : Warning< "the pointer decremented by %0 refers before the beginning of the array">, InGroup, DefaultIgnore; def warn_ptr_arith_exceeds_bounds : Warning< "the pointer incremented by %0 refers past the end of the array (that " "contains %1 element%s2)">, InGroup, DefaultIgnore; def warn_array_index_precedes_bounds : Warning< "array index %0 is before the beginning of the array">, InGroup; def warn_array_index_exceeds_bounds : Warning< "array index %0 is past the end of the array (which contains %1 " "element%s2)">, InGroup; def note_array_index_out_of_bounds : Note< "array %0 declared here">; def warn_printf_insufficient_data_args : Warning< "more '%%' conversions than data arguments">, InGroup; def warn_printf_data_arg_not_used : Warning< "data argument not used by format string">, InGroup; def warn_format_invalid_conversion : Warning< "invalid conversion specifier '%0'">, InGroup; def warn_printf_incomplete_specifier : Warning< "incomplete format specifier">, InGroup; def warn_missing_format_string : Warning< "format string missing">, InGroup; def warn_scanf_nonzero_width : Warning< "zero field width in scanf format string is unused">, InGroup; def warn_format_conversion_argument_type_mismatch : Warning< "format specifies type %0 but the argument has " "%select{type|underlying type}2 %1">, InGroup; def warn_format_conversion_argument_type_mismatch_pedantic : Extension< "format specifies type %0 but the argument has " "%select{type|underlying type}2 %1">, InGroup; def warn_format_argument_needs_cast : Warning< "%select{values of type|enum values with underlying type}2 '%0' should not " "be used as format arguments; add an explicit cast to %1 instead">, InGroup; def warn_format_argument_needs_cast_pedantic : Warning< "%select{values of type|enum values with underlying type}2 '%0' should not " "be used as format arguments; add an explicit cast to %1 instead">, InGroup, DefaultIgnore; def warn_printf_positional_arg_exceeds_data_args : Warning < "data argument position '%0' exceeds the number of data arguments (%1)">, InGroup; def warn_format_zero_positional_specifier : Warning< "position arguments in format strings start counting at 1 (not 0)">, InGroup; def warn_format_invalid_positional_specifier : Warning< "invalid position specified for %select{field width|field precision}0">, InGroup; def warn_format_mix_positional_nonpositional_args : Warning< "cannot mix positional and non-positional arguments in format string">, InGroup; def warn_static_array_too_small : Warning< "array argument is too small; contains %0 elements, callee requires at least %1">, InGroup; def note_callee_static_array : Note< "callee declares array parameter as static here">; def warn_empty_format_string : Warning< "format string is empty">, InGroup; def warn_format_string_is_wide_literal : Warning< "format string should not be a wide string">, InGroup; def warn_printf_format_string_contains_null_char : Warning< "format string contains '\\0' within the string body">, InGroup; def warn_printf_format_string_not_null_terminated : Warning< "format string is not null-terminated">, InGroup; def warn_printf_asterisk_missing_arg : Warning< "'%select{*|.*}0' specified field %select{width|precision}0 is missing a matching 'int' argument">, InGroup; def warn_printf_asterisk_wrong_type : Warning< "field %select{width|precision}0 should have type %1, but argument has type %2">, InGroup; def warn_printf_nonsensical_optional_amount: Warning< "%select{field width|precision}0 used with '%1' conversion specifier, resulting in undefined behavior">, InGroup; def warn_printf_nonsensical_flag: Warning< "flag '%0' results in undefined behavior with '%1' conversion specifier">, InGroup; def warn_format_nonsensical_length: Warning< "length modifier '%0' results in undefined behavior or no effect with '%1' conversion specifier">, InGroup; def warn_format_non_standard_positional_arg: Warning< "positional arguments are not supported by ISO C">, InGroup, DefaultIgnore; def warn_format_non_standard: Warning< "'%0' %select{length modifier|conversion specifier}1 is not supported by ISO C">, InGroup, DefaultIgnore; def warn_format_non_standard_conversion_spec: Warning< "using length modifier '%0' with conversion specifier '%1' is not supported by ISO C">, InGroup, DefaultIgnore; def err_invalid_mask_type_size : Error< "mask type size must be between 1-byte and 8-bytes">; def warn_format_invalid_annotation : Warning< "using '%0' format specifier annotation outside of os_log()/os_trace()">, InGroup; def warn_format_P_no_precision : Warning< "using '%%P' format specifier without precision">, InGroup; def warn_printf_ignored_flag: Warning< "flag '%0' is ignored when flag '%1' is present">, InGroup; def warn_printf_empty_objc_flag: Warning< "missing object format flag">, InGroup; def warn_printf_ObjCflags_without_ObjCConversion: Warning< "object format flags cannot be used with '%0' conversion specifier">, InGroup; def warn_printf_invalid_objc_flag: Warning< "'%0' is not a valid object format flag">, InGroup; def warn_scanf_scanlist_incomplete : Warning< "no closing ']' for '%%[' in scanf format string">, InGroup; def note_format_string_defined : Note<"format string is defined here">; def note_format_fix_specifier : Note<"did you mean to use '%0'?">; def note_printf_c_str: Note<"did you mean to call the %0 method?">; def note_format_security_fixit: Note< "treat the string as an argument to avoid this">; def warn_null_arg : Warning< "null passed to a callee that requires a non-null argument">, InGroup; def warn_null_ret : Warning< "null returned from %select{function|method}0 that requires a non-null return value">, InGroup; def err_lifetimebound_no_object_param : Error< "'lifetimebound' attribute cannot be applied; %select{static |non-}0member " "function has no implicit object parameter">; def err_lifetimebound_ctor_dtor : Error< "'lifetimebound' attribute cannot be applied to a " "%select{constructor|destructor}0">; // CHECK: returning address/reference of stack memory def warn_ret_stack_addr_ref : Warning< "%select{address of|reference to}0 stack memory associated with " "%select{local variable|parameter}2 %1 returned">, InGroup; def warn_ret_local_temp_addr_ref : Warning< "returning %select{address of|reference to}0 local temporary object">, InGroup; def warn_ret_addr_label : Warning< "returning address of label, which is local">, InGroup; def err_ret_local_block : Error< "returning block that lives on the local stack">; def note_local_var_initializer : Note< "%select{via initialization of|binding reference}0 variable " "%select{%2 |}1here">; def note_init_with_default_member_initalizer : Note< "initializing field %0 with default member initializer">; // Check for initializing a member variable with the address or a reference to // a constructor parameter. def warn_bind_ref_member_to_parameter : Warning< "binding reference member %0 to stack allocated " "%select{variable|parameter}2 %1">, InGroup; def warn_init_ptr_member_to_parameter_addr : Warning< "initializing pointer member %0 with the stack address of " "%select{variable|parameter}2 %1">, InGroup; def note_ref_or_ptr_member_declared_here : Note< "%select{reference|pointer}0 member declared here">; def err_dangling_member : Error< "%select{reference|backing array for 'std::initializer_list'}2 " "%select{|subobject of }1member %0 " "%select{binds to|is}2 a temporary object " "whose lifetime would be shorter than the lifetime of " "the constructed object">; def warn_dangling_member : Warning< "%select{reference|backing array for 'std::initializer_list'}2 " "%select{|subobject of }1member %0 " "%select{binds to|is}2 a temporary object " "whose lifetime is shorter than the lifetime of the constructed object">, InGroup; def note_lifetime_extending_member_declared_here : Note< "%select{%select{reference|'std::initializer_list'}0 member|" "member with %select{reference|'std::initializer_list'}0 subobject}1 " "declared here">; def warn_dangling_variable : Warning< "%select{temporary %select{whose address is used as value of|" "%select{|implicitly }2bound to}4 " "%select{%select{|reference }4member of local variable|" "local %select{variable|reference}4}1|" "array backing " "%select{initializer list subobject of local variable|" "local initializer list}1}0 " "%select{%3 |}2will be destroyed at the end of the full-expression">, InGroup; def warn_new_dangling_reference : Warning< "temporary bound to reference member of allocated object " "will be destroyed at the end of the full-expression">, InGroup; def warn_new_dangling_initializer_list : Warning< "array backing " "%select{initializer list subobject of the allocated object|" "the allocated initializer list}0 " "will be destroyed at the end of the full-expression">, InGroup; def warn_unsupported_lifetime_extension : Warning< "sorry, lifetime extension of " "%select{temporary|backing array of initializer list}0 created " "by aggregate initialization using default member initializer " "is not supported; lifetime of %select{temporary|backing array}0 " "will end at the end of the full-expression">, InGroup; // For non-floating point, expressions of the form x == x or x != x // should result in a warning, since these always evaluate to a constant. // Array comparisons have similar warnings def warn_comparison_always : Warning< "%select{self-|array }0comparison always evaluates to %select{a constant|%2}1">, InGroup; def warn_comparison_bitwise_always : Warning< "bitwise comparison always evaluates to %select{false|true}0">, InGroup; def warn_tautological_overlap_comparison : Warning< "overlapping comparisons always evaluate to %select{false|true}0">, InGroup, DefaultIgnore; def warn_stringcompare : Warning< "result of comparison against %select{a string literal|@encode}0 is " "unspecified (use strncmp instead)">, InGroup; def warn_identity_field_assign : Warning< "assigning %select{field|instance variable}0 to itself">, InGroup; // Type safety attributes def err_type_tag_for_datatype_not_ice : Error< "'type_tag_for_datatype' attribute requires the initializer to be " "an %select{integer|integral}0 constant expression">; def err_type_tag_for_datatype_too_large : Error< "'type_tag_for_datatype' attribute requires the initializer to be " "an %select{integer|integral}0 constant expression " "that can be represented by a 64 bit integer">; def err_tag_index_out_of_range : Error< "%select{type tag|argument}0 index %1 is greater than the number of arguments specified">; def warn_type_tag_for_datatype_wrong_kind : Warning< "this type tag was not designed to be used with this function">, InGroup; def warn_type_safety_type_mismatch : Warning< "argument type %0 doesn't match specified %1 type tag " "%select{that requires %3|}2">, InGroup; def warn_type_safety_null_pointer_required : Warning< "specified %0 type tag requires a null pointer">, InGroup; // Generic selections. def err_assoc_type_incomplete : Error< "type %0 in generic association incomplete">; def err_assoc_type_nonobject : Error< "type %0 in generic association not an object type">; def err_assoc_type_variably_modified : Error< "type %0 in generic association is a variably modified type">; def err_assoc_compatible_types : Error< "type %0 in generic association compatible with previously specified type %1">; def note_compat_assoc : Note< "compatible type %0 specified here">; def err_generic_sel_no_match : Error< "controlling expression type %0 not compatible with any generic association type">; def err_generic_sel_multi_match : Error< "controlling expression type %0 compatible with %1 generic association types">; // Blocks def err_blocks_disable : Error<"blocks support disabled - compile with -fblocks" " or %select{pick a deployment target that supports them|for OpenCL 2.0}0">; def err_block_returning_array_function : Error< "block cannot return %select{array|function}0 type %1">; // Builtin annotation def err_builtin_annotation_first_arg : Error< "first argument to __builtin_annotation must be an integer">; def err_builtin_annotation_second_arg : Error< "second argument to __builtin_annotation must be a non-wide string constant">; def err_msvc_annotation_wide_str : Error< "arguments to __annotation must be wide string constants">; // CFString checking def err_cfstring_literal_not_string_constant : Error< "CFString literal is not a string constant">; def warn_cfstring_truncated : Warning< "input conversion stopped due to an input byte that does not " "belong to the input codeset UTF-8">, InGroup>; // os_log checking // TODO: separate diagnostic for os_trace() def err_os_log_format_not_string_constant : Error< "os_log() format argument is not a string constant">; def err_os_log_argument_too_big : Error< "os_log() argument %0 is too big (%1 bytes, max %2)">; def warn_os_log_format_narg : Error< "os_log() '%%n' format specifier is not allowed">, DefaultError; // Statements. def err_continue_not_in_loop : Error< "'continue' statement not in loop statement">; def err_break_not_in_loop_or_switch : Error< "'break' statement not in loop or switch statement">; def warn_loop_ctrl_binds_to_inner : Warning< "'%0' is bound to current loop, GCC binds it to the enclosing loop">, InGroup; def warn_break_binds_to_switch : Warning< "'break' is bound to loop, GCC binds it to switch">, InGroup; def err_default_not_in_switch : Error< "'default' statement not in switch statement">; def err_case_not_in_switch : Error<"'case' statement not in switch statement">; def warn_bool_switch_condition : Warning< "switch condition has boolean value">, InGroup; def warn_case_value_overflow : Warning< "overflow converting case value to switch condition type (%0 to %1)">, InGroup; def err_duplicate_case : Error<"duplicate case value '%0'">; def err_duplicate_case_differing_expr : Error< "duplicate case value: '%0' and '%1' both equal '%2'">; def warn_case_empty_range : Warning<"empty case range specified">; def warn_missing_case_for_condition : Warning<"no case matching constant switch condition '%0'">; def warn_def_missing_case : Warning<"%plural{" "1:enumeration value %1 not explicitly handled in switch|" "2:enumeration values %1 and %2 not explicitly handled in switch|" "3:enumeration values %1, %2, and %3 not explicitly handled in switch|" ":%0 enumeration values not explicitly handled in switch: %1, %2, %3...}0">, InGroup, DefaultIgnore; def warn_missing_case : Warning<"%plural{" "1:enumeration value %1 not handled in switch|" "2:enumeration values %1 and %2 not handled in switch|" "3:enumeration values %1, %2, and %3 not handled in switch|" ":%0 enumeration values not handled in switch: %1, %2, %3...}0">, InGroup; def warn_unannotated_fallthrough : Warning< "unannotated fall-through between switch labels">, InGroup, DefaultIgnore; def warn_unannotated_fallthrough_per_function : Warning< "unannotated fall-through between switch labels in partly-annotated " "function">, InGroup, DefaultIgnore; def note_insert_fallthrough_fixit : Note< "insert '%0;' to silence this warning">; def note_insert_break_fixit : Note< "insert 'break;' to avoid fall-through">; def err_fallthrough_attr_wrong_target : Error< "%0 attribute is only allowed on empty statements">; def note_fallthrough_insert_semi_fixit : Note<"did you forget ';'?">; def err_fallthrough_attr_outside_switch : Error< "fallthrough annotation is outside switch statement">; def err_fallthrough_attr_invalid_placement : Error< "fallthrough annotation does not directly precede switch label">; def warn_fallthrough_attr_unreachable : Warning< "fallthrough annotation in unreachable code">, InGroup, DefaultIgnore; def warn_unreachable_default : Warning< "default label in switch which covers all enumeration values">, InGroup, DefaultIgnore; def warn_not_in_enum : Warning<"case value not in enumerated type %0">, InGroup; def warn_not_in_enum_assignment : Warning<"integer constant not in range " "of enumerated type %0">, InGroup>, DefaultIgnore; def err_typecheck_statement_requires_scalar : Error< "statement requires expression of scalar type (%0 invalid)">; def err_typecheck_statement_requires_integer : Error< "statement requires expression of integer type (%0 invalid)">; def err_multiple_default_labels_defined : Error< "multiple default labels in one switch">; def err_switch_multiple_conversions : Error< "multiple conversions from switch condition type %0 to an integral or " "enumeration type">; def note_switch_conversion : Note< "conversion to %select{integral|enumeration}0 type %1">; def err_switch_explicit_conversion : Error< "switch condition type %0 requires explicit conversion to %1">; def err_switch_incomplete_class_type : Error< "switch condition has incomplete class type %0">; def warn_empty_if_body : Warning< "if statement has empty body">, InGroup; def warn_empty_for_body : Warning< "for loop has empty body">, InGroup; def warn_empty_range_based_for_body : Warning< "range-based for loop has empty body">, InGroup; def warn_empty_while_body : Warning< "while loop has empty body">, InGroup; def warn_empty_switch_body : Warning< "switch statement has empty body">, InGroup; def note_empty_body_on_separate_line : Note< "put the semicolon on a separate line to silence this warning">; def err_va_start_captured_stmt : Error< "'va_start' cannot be used in a captured statement">; def err_va_start_outside_function : Error< "'va_start' cannot be used outside a function">; def err_va_start_fixed_function : Error< "'va_start' used in function with fixed args">; def err_va_start_used_in_wrong_abi_function : Error< "'va_start' used in %select{System V|Win64}0 ABI function">; def err_ms_va_start_used_in_sysv_function : Error< "'__builtin_ms_va_start' used in System V ABI function">; def warn_second_arg_of_va_start_not_last_named_param : Warning< "second argument to 'va_start' is not the last named parameter">, InGroup; def warn_va_start_type_is_undefined : Warning< "passing %select{an object that undergoes default argument promotion|" "an object of reference type|a parameter declared with the 'register' " "keyword}0 to 'va_start' has undefined behavior">, InGroup; def err_first_argument_to_va_arg_not_of_type_va_list : Error< "first argument to 'va_arg' is of type %0 and not 'va_list'">; def err_second_parameter_to_va_arg_incomplete: Error< "second argument to 'va_arg' is of incomplete type %0">; def err_second_parameter_to_va_arg_abstract: Error< "second argument to 'va_arg' is of abstract type %0">; def warn_second_parameter_to_va_arg_not_pod : Warning< "second argument to 'va_arg' is of non-POD type %0">, InGroup, DefaultError; def warn_second_parameter_to_va_arg_ownership_qualified : Warning< "second argument to 'va_arg' is of ARC ownership-qualified type %0">, InGroup, DefaultError; def warn_second_parameter_to_va_arg_never_compatible : Warning< "second argument to 'va_arg' is of promotable type %0; this va_arg has " "undefined behavior because arguments will be promoted to %1">, InGroup; def warn_return_missing_expr : Warning< "non-void %select{function|method}1 %0 should return a value">, DefaultError, InGroup; def ext_return_missing_expr : ExtWarn< "non-void %select{function|method}1 %0 should return a value">, DefaultError, InGroup; def ext_return_has_expr : ExtWarn< "%select{void function|void method|constructor|destructor}1 %0 " "should not return a value">, DefaultError, InGroup; def ext_return_has_void_expr : Extension< "void %select{function|method|block}1 %0 should not return void expression">; def err_return_init_list : Error< "%select{void function|void method|constructor|destructor}1 %0 " "must not return a value">; def err_ctor_dtor_returns_void : Error< "%select{constructor|destructor}1 %0 must not return void expression">; def warn_noreturn_function_has_return_expr : Warning< "function %0 declared 'noreturn' should not return">, InGroup; def warn_falloff_noreturn_function : Warning< "function declared 'noreturn' should not return">, InGroup; def err_noreturn_block_has_return_expr : Error< "block declared 'noreturn' should not return">; def err_noreturn_missing_on_first_decl : Error< "function declared '[[noreturn]]' after its first declaration">; def note_noreturn_missing_first_decl : Note< "declaration missing '[[noreturn]]' attribute is here">; def err_carries_dependency_missing_on_first_decl : Error< "%select{function|parameter}0 declared '[[carries_dependency]]' " "after its first declaration">; def note_carries_dependency_missing_first_decl : Note< "declaration missing '[[carries_dependency]]' attribute is here">; def err_carries_dependency_param_not_function_decl : Error< "'[[carries_dependency]]' attribute only allowed on parameter in a function " "declaration or lambda">; def err_block_on_nonlocal : Error< "__block attribute not allowed, only allowed on local variables">; def err_block_on_vm : Error< "__block attribute not allowed on declaration with a variably modified type">; def err_vec_builtin_non_vector : Error< "first two arguments to %0 must be vectors">; def err_vec_builtin_incompatible_vector : Error< "first two arguments to %0 must have the same type">; def err_vsx_builtin_nonconstant_argument : Error< "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">; def err_shufflevector_nonconstant_argument : Error< "index for __builtin_shufflevector must be a constant integer">; def err_shufflevector_argument_too_large : Error< "index for __builtin_shufflevector must be less than the total number " "of vector elements">; def err_convertvector_non_vector : Error< "first argument to __builtin_convertvector must be a vector">; def err_convertvector_non_vector_type : Error< "second argument to __builtin_convertvector must be a vector type">; def err_convertvector_incompatible_vector : Error< "first two arguments to __builtin_convertvector must have the same number of elements">; def err_first_argument_to_cwsc_not_call : Error< "first argument to __builtin_call_with_static_chain must be a non-member call expression">; def err_first_argument_to_cwsc_block_call : Error< "first argument to __builtin_call_with_static_chain must not be a block call">; def err_first_argument_to_cwsc_builtin_call : Error< "first argument to __builtin_call_with_static_chain must not be a builtin call">; def err_first_argument_to_cwsc_pdtor_call : Error< "first argument to __builtin_call_with_static_chain must not be a pseudo-destructor call">; def err_second_argument_to_cwsc_not_pointer : Error< "second argument to __builtin_call_with_static_chain must be of pointer type">; def err_vector_incorrect_num_initializers : Error< "%select{too many|too few}0 elements in vector initialization (expected %1 elements, have %2)">; def err_altivec_empty_initializer : Error<"expected initializer">; def err_invalid_neon_type_code : Error< "incompatible constant for this __builtin_neon function">; def err_argument_invalid_range : Error< "argument value %0 is outside the valid range [%1, %2]">; def warn_argument_invalid_range : Warning< "argument value %0 is outside the valid range [%1, %2]">, DefaultError, InGroup>; def err_argument_not_multiple : Error< "argument should be a multiple of %0">; def warn_neon_vector_initializer_non_portable : Warning< "vector initializers are not compatible with NEON intrinsics in big endian " "mode">, InGroup>; def note_neon_vector_initializer_non_portable : Note< "consider using vld1_%0%1() to initialize a vector from memory, or " "vcreate_%0%1() to initialize from an integer constant">; def note_neon_vector_initializer_non_portable_q : Note< "consider using vld1q_%0%1() to initialize a vector from memory, or " "vcombine_%0%1(vcreate_%0%1(), vcreate_%0%1()) to initialize from integer " "constants">; def err_systemz_invalid_tabort_code : Error< "invalid transaction abort code">; def err_64_bit_builtin_32_bit_tgt : Error< "this builtin is only available on 64-bit targets">; def err_32_bit_builtin_64_bit_tgt : Error< "this builtin is only available on 32-bit targets">; def err_builtin_x64_aarch64_only : Error< "this builtin is only available on x86-64 and aarch64 targets">; def err_ppc_builtin_only_on_pwr7 : Error< "this builtin is only valid on POWER7 or later CPUs">; def err_x86_builtin_invalid_rounding : Error< "invalid rounding argument">; def err_x86_builtin_invalid_scale : Error< "scale argument must be 1, 2, 4, or 8">; def err_hexagon_builtin_unsupported_cpu : Error< "builtin is not supported on this CPU">; def err_hexagon_builtin_requires_hvx : Error< "builtin requires HVX">; def err_hexagon_builtin_unsupported_hvx : Error< "builtin is not supported on this version of HVX">; def err_builtin_target_unsupported : Error< "builtin is not supported on this target">; def err_builtin_longjmp_unsupported : Error< "__builtin_longjmp is not supported for the current target">; def err_builtin_setjmp_unsupported : Error< "__builtin_setjmp is not supported for the current target">; def err_builtin_longjmp_invalid_val : Error< "argument to __builtin_longjmp must be a constant 1">; def err_builtin_requires_language : Error<"'%0' is only available in %1">; def err_constant_integer_arg_type : Error< "argument to %0 must be a constant integer">; def ext_mixed_decls_code : Extension< "ISO C90 forbids mixing declarations and code">, InGroup>; def err_non_local_variable_decl_in_for : Error< "declaration of non-local variable in 'for' loop">; def err_non_variable_decl_in_for : Error< "non-variable declaration in 'for' loop">; def err_toomany_element_decls : Error< "only one element declaration is allowed">; def err_selector_element_not_lvalue : Error< "selector element is not a valid lvalue">; def err_selector_element_type : Error< "selector element type %0 is not a valid object">; def err_selector_element_const_type : Error< "selector element of type %0 cannot be a constant l-value expression">; def err_collection_expr_type : Error< "the type %0 is not a pointer to a fast-enumerable object">; def warn_collection_expr_type : Warning< "collection expression type %0 may not respond to %1">; def err_invalid_conversion_between_ext_vectors : Error< "invalid conversion between ext-vector type %0 and %1">; def warn_duplicate_attribute_exact : Warning< "attribute %0 is already applied">, InGroup; def warn_duplicate_attribute : Warning< "attribute %0 is already applied with different parameters">, InGroup; def warn_sync_fetch_and_nand_semantics_change : Warning< "the semantics of this intrinsic changed with GCC " "version 4.4 - the newer semantics are provided here">, InGroup>; // Type def ext_invalid_sign_spec : Extension<"'%0' cannot be signed or unsigned">; def warn_receiver_forward_class : Warning< "receiver %0 is a forward class and corresponding @interface may not exist">, InGroup; def note_method_sent_forward_class : Note<"method %0 is used for the forward class">; def ext_missing_declspec : ExtWarn< "declaration specifier missing, defaulting to 'int'">; def ext_missing_type_specifier : ExtWarn< "type specifier missing, defaults to 'int'">, InGroup; def err_decimal_unsupported : Error< "GNU decimal type extension not supported">; def err_missing_type_specifier : Error< "C++ requires a type specifier for all declarations">; def err_objc_array_of_interfaces : Error< "array of interface %0 is invalid (probably should be an array of pointers)">; def ext_c99_array_usage : Extension< "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 " "feature">, InGroup; def err_c99_array_usage_cxx : Error< "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 " "feature, not permitted in C++">; def err_type_unsupported : Error< "%0 is not supported on this target">; def err_nsconsumed_attribute_mismatch : Error< "overriding method has mismatched ns_consumed attribute on its" " parameter">; def err_nsreturns_retained_attribute_mismatch : Error< "overriding method has mismatched ns_returns_%select{not_retained|retained}0" " attributes">; def warn_nsconsumed_attribute_mismatch : Warning< err_nsconsumed_attribute_mismatch.Text>, InGroup; def warn_nsreturns_retained_attribute_mismatch : Warning< err_nsreturns_retained_attribute_mismatch.Text>, InGroup; def note_getter_unavailable : Note< "or because setter is declared here, but no getter method %0 is found">; def err_invalid_protocol_qualifiers : Error< "invalid protocol qualifiers on non-ObjC type">; def warn_ivar_use_hidden : Warning< "local declaration of %0 hides instance variable">, InGroup; def warn_direct_initialize_call : Warning< "explicit call to +initialize results in duplicate call to +initialize">, InGroup; def warn_direct_super_initialize_call : Warning< "explicit call to [super initialize] should only be in implementation " "of +initialize">, InGroup; def err_ivar_use_in_class_method : Error< "instance variable %0 accessed in class method">; def err_private_ivar_access : Error<"instance variable %0 is private">, AccessControl; def err_protected_ivar_access : Error<"instance variable %0 is protected">, AccessControl; def warn_maynot_respond : Warning<"%0 may not respond to %1">; def ext_typecheck_base_super : Warning< "method parameter type " "%diff{$ does not match super class method parameter type $|" "does not match super class method parameter type}0,1">, InGroup, DefaultIgnore; def warn_missing_method_return_type : Warning< "method has no return type specified; defaults to 'id'">, InGroup, DefaultIgnore; def warn_direct_ivar_access : Warning<"instance variable %0 is being " "directly accessed">, InGroup>, DefaultIgnore; // Spell-checking diagnostics def err_unknown_typename : Error< "unknown type name %0">; def err_unknown_type_or_class_name_suggest : Error< "unknown %select{type|class}1 name %0; did you mean %2?">; def err_unknown_typename_suggest : Error< "unknown type name %0; did you mean %1?">; def err_unknown_nested_typename_suggest : Error< "no type named %0 in %1; did you mean %select{|simply }2%3?">; def err_no_member_suggest : Error<"no member named %0 in %1; did you mean %select{|simply }2%3?">; def err_undeclared_use_suggest : Error< "use of undeclared %0; did you mean %1?">; def err_undeclared_var_use_suggest : Error< "use of undeclared identifier %0; did you mean %1?">; def err_no_template : Error<"no template named %0">; def err_no_template_suggest : Error<"no template named %0; did you mean %1?">; def err_no_member_template : Error<"no template named %0 in %1">; def err_no_member_template_suggest : Error< "no template named %0 in %1; did you mean %select{|simply }2%3?">; def err_non_template_in_template_id : Error< "%0 does not name a template but is followed by template arguments">; def err_non_template_in_template_id_suggest : Error< "%0 does not name a template but is followed by template arguments; " "did you mean %1?">; def err_non_template_in_member_template_id_suggest : Error< "member %0 of %1 is not a template; did you mean %select{|simply }2%3?">; def note_non_template_in_template_id_found : Note< "non-template declaration found by name lookup">; def err_mem_init_not_member_or_class_suggest : Error< "initializer %0 does not name a non-static data member or base " "class; did you mean the %select{base class|member}1 %2?">; def err_field_designator_unknown_suggest : Error< "field designator %0 does not refer to any field in type %1; did you mean " "%2?">; def err_typecheck_member_reference_ivar_suggest : Error< "%0 does not have a member named %1; did you mean %2?">; def err_property_not_found_suggest : Error< "property %0 not found on object of type %1; did you mean %2?">; def err_class_property_found : Error< "property %0 is a class property; did you mean to access it with class '%1'?">; def err_ivar_access_using_property_syntax_suggest : Error< "property %0 not found on object of type %1; did you mean to access instance variable %2?">; def warn_property_access_suggest : Warning< "property %0 not found on object of type %1; did you mean to access property %2?">, InGroup; def err_property_found_suggest : Error< "property %0 found on object of type %1; did you mean to access " "it with the \".\" operator?">; def err_undef_interface_suggest : Error< "cannot find interface declaration for %0; did you mean %1?">; def warn_undef_interface_suggest : Warning< "cannot find interface declaration for %0; did you mean %1?">; def err_undef_superclass_suggest : Error< "cannot find interface declaration for %0, superclass of %1; did you mean " "%2?">; def err_undeclared_protocol_suggest : Error< "cannot find protocol declaration for %0; did you mean %1?">; def note_base_class_specified_here : Note< "base class %0 specified here">; def err_using_directive_suggest : Error< "no namespace named %0; did you mean %1?">; def err_using_directive_member_suggest : Error< "no namespace named %0 in %1; did you mean %select{|simply }2%3?">; def note_namespace_defined_here : Note<"namespace %0 defined here">; def err_sizeof_pack_no_pack_name_suggest : Error< "%0 does not refer to the name of a parameter pack; did you mean %1?">; def note_parameter_pack_here : Note<"parameter pack %0 declared here">; def err_uncasted_use_of_unknown_any : Error< "%0 has unknown type; cast it to its declared type to use it">; def err_uncasted_call_of_unknown_any : Error< "%0 has unknown return type; cast the call to its declared return type">; def err_uncasted_send_to_unknown_any_method : Error< "no known method %select{%objcinstance1|%objcclass1}0; cast the " "message send to the method's return type">; def err_unsupported_unknown_any_decl : Error< "%0 has unknown type, which is not supported for this kind of declaration">; def err_unsupported_unknown_any_expr : Error< "unsupported expression with unknown type">; def err_unsupported_unknown_any_call : Error< "call to unsupported expression with unknown type">; def err_unknown_any_addrof : Error< "the address of a declaration with unknown type " "can only be cast to a pointer type">; def err_unknown_any_addrof_call : Error< "address-of operator cannot be applied to a call to a function with " "unknown return type">; def err_unknown_any_var_function_type : Error< "variable %0 with unknown type cannot be given a function type">; def err_unknown_any_function : Error< "function %0 with unknown type must be given a function type">; def err_filter_expression_integral : Error< "filter expression type should be an integral value not %0">; def err_non_asm_stmt_in_naked_function : Error< "non-ASM statement in naked function is not supported">; def err_asm_naked_this_ref : Error< "'this' pointer references not allowed in naked functions">; def err_asm_naked_parm_ref : Error< "parameter references not allowed in naked functions">; // OpenCL warnings and errors. def err_invalid_astype_of_different_size : Error< "invalid reinterpretation: sizes of %0 and %1 must match">; def err_static_kernel : Error< "kernel functions cannot be declared static">; def err_opencl_ptrptr_kernel_param : Error< "kernel parameter cannot be declared as a pointer to a pointer">; def err_kernel_arg_address_space : Error< "pointer arguments to kernel functions must reside in '__global', " "'__constant' or '__local' address space">; def err_opencl_ext_vector_component_invalid_length : Error< "vector component access has invalid length %0. Supported: 1,2,3,4,8,16.">; def err_opencl_function_variable : Error< "%select{non-kernel function|function scope}0 variable cannot be declared in %1 address space">; def err_opencl_addrspace_scope : Error< "variables in the %0 address space can only be declared in the outermost " "scope of a kernel function">; def err_static_function_scope : Error< "variables in function scope cannot be declared static">; def err_opencl_bitfields : Error< "bit-fields are not supported in OpenCL">; def err_opencl_vla : Error< "variable length arrays are not supported in OpenCL">; def err_opencl_scalar_type_rank_greater_than_vector_type : Error< "scalar operand type has greater rank than the type of the vector " "element. (%0 and %1)">; def err_bad_kernel_param_type : Error< "%0 cannot be used as the type of a kernel parameter">; def err_opencl_implicit_function_decl : Error< "implicit declaration of function %0 is invalid in OpenCL">; def err_record_with_pointers_kernel_param : Error< "%select{struct|union}0 kernel parameters may not contain pointers">; def note_within_field_of_type : Note< "within field of type %0 declared here">; def note_illegal_field_declared_here : Note< "field of illegal %select{type|pointer type}0 %1 declared here">; def err_opencl_type_struct_or_union_field : Error< "the %0 type cannot be used to declare a structure or union field">; def err_event_t_addr_space_qual : Error< "the event_t type can only be used with __private address space qualifier">; def err_expected_kernel_void_return_type : Error< "kernel must have void return type">; def err_sampler_initializer_not_integer : Error< "sampler_t initialization requires 32-bit integer, not %0">; def warn_sampler_initializer_invalid_bits : Warning< "sampler initializer has invalid %0 bits">, InGroup, DefaultIgnore; def err_sampler_argument_required : Error< "sampler_t variable required - got %0">; def err_wrong_sampler_addressspace: Error< "sampler type cannot be used with the __local and __global address space qualifiers">; def err_opencl_nonconst_global_sampler : Error< "global sampler requires a const or constant address space qualifier">; def err_opencl_cast_non_zero_to_event_t : Error< "cannot cast non-zero value '%0' to 'event_t'">; def err_opencl_global_invalid_addr_space : Error< "%select{program scope|static local|extern}0 variable must reside in %1 address space">; def err_missing_actual_pipe_type : Error< "missing actual type specifier for pipe">; def err_reference_pipe_type : Error < "pipes packet types cannot be of reference type">; def err_opencl_no_main : Error<"%select{function|kernel}0 cannot be called 'main'">; def err_opencl_kernel_attr : Error<"attribute %0 can only be applied to an OpenCL kernel function">; def err_opencl_return_value_with_address_space : Error< "return value cannot be qualified with address space">; def err_opencl_constant_no_init : Error< "variable in constant address space must be initialized">; def err_opencl_atomic_init: Error< "atomic variable can be %select{assigned|initialized}0 to a variable only " "in global address space">; def err_opencl_implicit_vector_conversion : Error< "implicit conversions between vector types (%0 and %1) are not permitted">; def err_opencl_invalid_type_array : Error< "array of %0 type is invalid in OpenCL">; def err_opencl_ternary_with_block : Error< "block type cannot be used as expression in ternary expression in OpenCL">; def err_opencl_pointer_to_type : Error< "pointer to type %0 is invalid in OpenCL">; def err_opencl_type_can_only_be_used_as_function_parameter : Error < "type %0 can only be used as a function parameter in OpenCL">; def warn_opencl_attr_deprecated_ignored : Warning < "%0 attribute is deprecated and ignored in OpenCL version %1">, InGroup; def err_opencl_variadic_function : Error< "invalid prototype, variadic arguments are not allowed in OpenCL">; def err_opencl_requires_extension : Error< "use of %select{type|declaration}0 %1 requires %2 extension to be enabled">; def warn_opencl_generic_address_space_arg : Warning< "passing non-generic address space pointer to %0" " may cause dynamic conversion affecting performance">, InGroup, DefaultIgnore; // OpenCL v2.0 s6.13.6 -- Builtin Pipe Functions def err_opencl_builtin_pipe_first_arg : Error< "first argument to %0 must be a pipe type">; def err_opencl_builtin_pipe_arg_num : Error< "invalid number of arguments to function: %0">; def err_opencl_builtin_pipe_invalid_arg : Error< "invalid argument type to function %0 (expecting %1 having %2)">; def err_opencl_builtin_pipe_invalid_access_modifier : Error< "invalid pipe access modifier (expecting %0)">; // OpenCL access qualifier def err_opencl_invalid_access_qualifier : Error< "access qualifier can only be used for pipe and image type">; def err_opencl_invalid_read_write : Error< "access qualifier %0 can not be used for %1 %select{|prior to OpenCL version 2.0}2">; def err_opencl_multiple_access_qualifiers : Error< "multiple access qualifiers">; def note_opencl_typedef_access_qualifier : Note< "previously declared '%0' here">; // OpenCL v2.0 s6.12.5 Blocks restrictions def err_opencl_block_storage_type : Error< "the __block storage type is not permitted">; def err_opencl_invalid_block_declaration : Error< "invalid block variable declaration - must be %select{const qualified|initialized}0">; def err_opencl_extern_block_declaration : Error< "invalid block variable declaration - using 'extern' storage class is disallowed">; def err_opencl_block_ref_block : Error< "cannot refer to a block inside block">; // OpenCL v2.0 s6.13.9 - Address space qualifier functions. def err_opencl_builtin_to_addr_arg_num : Error< "invalid number of arguments to function: %0">; def err_opencl_builtin_to_addr_invalid_arg : Error< "invalid argument %0 to function: %1, expecting a generic pointer argument">; // OpenCL v2.0 s6.13.17 Enqueue kernel restrictions. def err_opencl_enqueue_kernel_incorrect_args : Error< "illegal call to enqueue_kernel, incorrect argument types">; def err_opencl_enqueue_kernel_local_size_args : Error< "mismatch in number of block parameters and local size arguments passed">; def err_opencl_enqueue_kernel_invalid_local_size_type : Error< "illegal call to enqueue_kernel, parameter needs to be specified as integer type">; def err_opencl_enqueue_kernel_blocks_non_local_void_args : Error< "blocks used in enqueue_kernel call are expected to have parameters of type 'local void*'">; def err_opencl_enqueue_kernel_blocks_no_args : Error< "blocks with parameters are not accepted in this prototype of enqueue_kernel call">; def err_opencl_builtin_expected_type : Error< "illegal call to %0, expected %1 argument type">; // OpenCL v2.2 s2.1.2.3 - Vector Component Access def ext_opencl_ext_vector_type_rgba_selector: ExtWarn< "vector component name '%0' is an OpenCL version 2.2 feature">, InGroup; } // end of sema category let CategoryName = "OpenMP Issue" in { // OpenMP support. def err_omp_expected_var_arg : Error< "%0 is not a global variable, static local variable or static data member">; def err_omp_expected_var_arg_suggest : Error< "%0 is not a global variable, static local variable or static data member; " "did you mean %1">; def err_omp_global_var_arg : Error< "arguments of '#pragma omp %0' must have %select{global storage|static storage duration}1">; def err_omp_ref_type_arg : Error< "arguments of '#pragma omp %0' cannot be of reference type %1">; def err_omp_region_not_file_context : Error< "directive must be at file or namespace scope">; def err_omp_var_scope : Error< "'#pragma omp %0' must appear in the scope of the %q1 variable declaration">; def err_omp_var_used : Error< "'#pragma omp %0' must precede all references to variable %q1">; def err_omp_var_thread_local : Error< "variable %0 cannot be threadprivate because it is %select{thread-local|a global named register variable}1">; def err_omp_private_incomplete_type : Error< "a private variable with incomplete type %0">; def err_omp_firstprivate_incomplete_type : Error< "a firstprivate variable with incomplete type %0">; def err_omp_lastprivate_incomplete_type : Error< "a lastprivate variable with incomplete type %0">; def err_omp_reduction_incomplete_type : Error< "a reduction list item with incomplete type %0">; def err_omp_unexpected_clause_value : Error< "expected %0 in OpenMP clause '%1'">; def err_omp_expected_var_name_member_expr : Error< "expected variable name%select{| or data member of current class}0">; def err_omp_expected_var_name_member_expr_or_array_item : Error< "expected variable name%select{|, data member of current class}0, array element or array section">; def err_omp_expected_addressable_lvalue_or_array_item : Error< "expected addressable lvalue expression, array element or array section">; def err_omp_expected_named_var_member_or_array_expression: Error< "expected expression containing only member accesses and/or array sections based on named variables">; def err_omp_bit_fields_forbidden_in_clause : Error< "bit fields cannot be used to specify storage in a '%0' clause">; def err_array_section_does_not_specify_contiguous_storage : Error< "array section does not specify contiguous storage">; def err_omp_union_type_not_allowed : Error< "mapping of union members is not allowed">; def err_omp_expected_access_to_data_field : Error< "expected access to data field">; def err_omp_multiple_array_items_in_map_clause : Error< "multiple array elements associated with the same variable are not allowed in map clauses of the same construct">; def err_omp_duplicate_map_type_modifier : Error< "same map type modifier has been specified more than once">; def err_omp_pointer_mapped_along_with_derived_section : Error< "pointer cannot be mapped along with a section derived from itself">; def err_omp_original_storage_is_shared_and_does_not_contain : Error< "original storage of expression in data environment is shared but data environment do not fully contain mapped expression storage">; def err_omp_same_pointer_dereferenced : Error< "same pointer dereferenced in multiple different ways in map clause expressions">; def note_omp_task_predetermined_firstprivate_here : Note< "predetermined as a firstprivate in a task construct here">; def err_omp_threadprivate_incomplete_type : Error< "threadprivate variable with incomplete type %0">; def err_omp_no_dsa_for_variable : Error< "variable %0 must have explicitly specified data sharing attributes">; def err_omp_wrong_dsa : Error< "%0 variable cannot be %1">; def err_omp_variably_modified_type_not_supported : Error< "arguments of OpenMP clause '%0' in '#pragma omp %2' directive cannot be of variably-modified type %1">; def note_omp_explicit_dsa : Note< "defined as %0">; def note_omp_predetermined_dsa : Note< "%select{static data member is predetermined as shared|" "variable with static storage duration is predetermined as shared|" "loop iteration variable is predetermined as private|" "loop iteration variable is predetermined as linear|" "loop iteration variable is predetermined as lastprivate|" "constant variable is predetermined as shared|" "global variable is predetermined as shared|" "non-shared variable in a task construct is predetermined as firstprivate|" "variable with automatic storage duration is predetermined as private}0" "%select{|; perhaps you forget to enclose 'omp %2' directive into a parallel or another task region?}1">; def note_omp_implicit_dsa : Note< "implicitly determined as %0">; def err_omp_loop_var_dsa : Error< "loop iteration variable in the associated loop of 'omp %1' directive may not be %0, predetermined as %2">; def err_omp_not_for : Error< "%select{statement after '#pragma omp %1' must be a for loop|" "expected %2 for loops after '#pragma omp %1'%select{|, but found only %4}3}0">; def note_omp_collapse_ordered_expr : Note< "as specified in %select{'collapse'|'ordered'|'collapse' and 'ordered'}0 clause%select{||s}0">; def err_omp_negative_expression_in_clause : Error< "argument to '%0' clause must be a %select{non-negative|strictly positive}1 integer value">; def err_omp_not_integral : Error< "expression must have integral or unscoped enumeration " "type, not %0">; def err_omp_threadprivate_in_target : Error< "threadprivate variables cannot be used in target constructs">; def err_omp_incomplete_type : Error< "expression has incomplete class type %0">; def err_omp_explicit_conversion : Error< "expression requires explicit conversion from %0 to %1">; def note_omp_conversion_here : Note< "conversion to %select{integral|enumeration}0 type %1 declared here">; def err_omp_ambiguous_conversion : Error< "ambiguous conversion from type %0 to an integral or unscoped " "enumeration type">; def err_omp_required_access : Error< "%0 variable must be %1">; def err_omp_const_variable : Error< "const-qualified variable cannot be %0">; def err_omp_const_not_mutable_variable : Error< "const-qualified variable without mutable fields cannot be %0">; def err_omp_const_list_item : Error< "const-qualified list item cannot be %0">; def err_omp_linear_incomplete_type : Error< "a linear variable with incomplete type %0">; def err_omp_linear_expected_int_or_ptr : Error< "argument of a linear clause should be of integral or pointer " "type, not %0">; def warn_omp_linear_step_zero : Warning< "zero linear step (%0 %select{|and other variables in clause }1should probably be const)">, InGroup; def warn_omp_alignment_not_power_of_two : Warning< "aligned clause will be ignored because the requested alignment is not a power of 2">, InGroup; def err_omp_invalid_target_decl : Error< "%0 used in declare target directive is not a variable or a function name">; def err_omp_declare_target_multiple : Error< "%0 appears multiple times in clauses on the same declare target directive">; def err_omp_declare_target_to_and_link : Error< "%0 must not appear in both clauses 'to' and 'link'">; def warn_omp_not_in_target_context : Warning< "declaration is not declared in any declare target region">, InGroup; def err_omp_function_in_link_clause : Error< "function name is not allowed in 'link' clause">; def err_omp_aligned_expected_array_or_ptr : Error< "argument of aligned clause should be array" "%select{ or pointer|, pointer, reference to array or reference to pointer}1" ", not %0">; def err_omp_aligned_twice : Error< "%select{a variable|a parameter|'this'}0 cannot appear in more than one aligned clause">; def err_omp_local_var_in_threadprivate_init : Error< "variable with local storage in initial value of threadprivate variable">; def err_omp_loop_not_canonical_init : Error< "initialization clause of OpenMP for loop is not in canonical form " "('var = init' or 'T var = init')">; def ext_omp_loop_not_canonical_init : ExtWarn< "initialization clause of OpenMP for loop is not in canonical form " "('var = init' or 'T var = init')">, InGroup; def err_omp_loop_not_canonical_cond : Error< "condition of OpenMP for loop must be a relational comparison " "('<', '<=', '>', or '>=') of loop variable %0">; def err_omp_loop_not_canonical_incr : Error< "increment clause of OpenMP for loop must perform simple addition " "or subtraction on loop variable %0">; def err_omp_loop_variable_type : Error< "variable must be of integer or %select{pointer|random access iterator}0 type">; def err_omp_loop_incr_not_compatible : Error< "increment expression must cause %0 to %select{decrease|increase}1 " "on each iteration of OpenMP for loop">; def note_omp_loop_cond_requres_compatible_incr : Note< "loop step is expected to be %select{negative|positive}0 due to this condition">; def err_omp_loop_diff_cxx : Error< "could not calculate number of iterations calling 'operator-' with " "upper and lower loop bounds">; def err_omp_loop_cannot_use_stmt : Error< "'%0' statement cannot be used in OpenMP for loop">; def err_omp_simd_region_cannot_use_stmt : Error< "'%0' statement cannot be used in OpenMP simd region">; def warn_omp_loop_64_bit_var : Warning< "OpenMP loop iteration variable cannot have more than 64 bits size and will be narrowed">, InGroup; def err_omp_unknown_reduction_identifier : Error< "incorrect reduction identifier, expected one of '+', '-', '*', '&', '|', '^', " "'&&', '||', 'min' or 'max' or declare reduction for type %0">; def err_omp_not_resolved_reduction_identifier : Error< "unable to resolve declare reduction construct for type %0">; def err_omp_reduction_ref_type_arg : Error< "argument of OpenMP clause '%0' must reference the same object in all threads">; def err_omp_clause_not_arithmetic_type_arg : Error< "arguments of OpenMP clause '%0' for 'min' or 'max' must be of %select{scalar|arithmetic}1 type">; def err_omp_clause_floating_type_arg : Error< "arguments of OpenMP clause '%0' with bitwise operators cannot be of floating type">; def err_omp_once_referenced : Error< "variable can appear only once in OpenMP '%0' clause">; def err_omp_once_referenced_in_target_update : Error< "variable can appear only once in OpenMP 'target update' construct">; def note_omp_referenced : Note< "previously referenced here">; def err_omp_reduction_in_task : Error< "reduction variables may not be accessed in an explicit task">; def err_omp_reduction_id_not_compatible : Error< "list item of type %0 is not valid for specified reduction operation: unable to provide default initialization value">; def err_omp_in_reduction_not_task_reduction : Error< "in_reduction variable must appear in a task_reduction clause">; def err_omp_reduction_identifier_mismatch : Error< "in_reduction variable must have the same reduction operation as in a task_reduction clause">; def note_omp_previous_reduction_identifier : Note< "previously marked as task_reduction with different reduction operation">; def err_omp_prohibited_region : Error< "region cannot be%select{| closely}0 nested inside '%1' region" "%select{|; perhaps you forget to enclose 'omp %3' directive into a parallel region?|" "; perhaps you forget to enclose 'omp %3' directive into a for or a parallel for region with 'ordered' clause?|" "; perhaps you forget to enclose 'omp %3' directive into a target region?|" "; perhaps you forget to enclose 'omp %3' directive into a teams region?}2">; def err_omp_prohibited_region_simd : Error< "OpenMP constructs may not be nested inside a simd region">; def err_omp_prohibited_region_atomic : Error< "OpenMP constructs may not be nested inside an atomic region">; def err_omp_prohibited_region_critical_same_name : Error< "cannot nest 'critical' regions having the same name %0">; def note_omp_previous_critical_region : Note< "previous 'critical' region starts here">; def err_omp_sections_not_compound_stmt : Error< "the statement for '#pragma omp sections' must be a compound statement">; def err_omp_parallel_sections_not_compound_stmt : Error< "the statement for '#pragma omp parallel sections' must be a compound statement">; def err_omp_orphaned_section_directive : Error< "%select{orphaned 'omp section' directives are prohibited, it|'omp section' directive}0" " must be closely nested to a sections region%select{|, not a %1 region}0">; def err_omp_sections_substmt_not_section : Error< "statement in 'omp sections' directive must be enclosed into a section region">; def err_omp_parallel_sections_substmt_not_section : Error< "statement in 'omp parallel sections' directive must be enclosed into a section region">; def err_omp_parallel_reduction_in_task_firstprivate : Error< "argument of a reduction clause of a %0 construct must not appear in a firstprivate clause on a task construct">; def err_omp_atomic_read_not_expression_statement : Error< "the statement for 'atomic read' must be an expression statement of form 'v = x;'," " where v and x are both lvalue expressions with scalar type">; def note_omp_atomic_read_write: Note< "%select{expected an expression statement|expected built-in assignment operator|expected expression of scalar type|expected lvalue expression}0">; def err_omp_atomic_write_not_expression_statement : Error< "the statement for 'atomic write' must be an expression statement of form 'x = expr;'," " where x is a lvalue expression with scalar type">; def err_omp_atomic_update_not_expression_statement : Error< "the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x'," " where x is an l-value expression with scalar type">; def err_omp_atomic_not_expression_statement : Error< "the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x'," " where x is an l-value expression with scalar type">; def note_omp_atomic_update: Note< "%select{expected an expression statement|expected built-in binary or unary operator|expected unary decrement/increment operation|" "expected expression of scalar type|expected assignment expression|expected built-in binary operator|" "expected one of '+', '*', '-', '/', '&', '^', '%|', '<<', or '>>' built-in operations|expected in right hand side of expression}0">; def err_omp_atomic_capture_not_expression_statement : Error< "the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x'," " where x and v are both l-value expressions with scalar type">; def err_omp_atomic_capture_not_compound_statement : Error< "the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}'," " '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}'," " '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}'" " where x is an l-value expression with scalar type">; def note_omp_atomic_capture: Note< "%select{expected assignment expression|expected compound statement|expected exactly two expression statements|expected in right hand side of the first expression}0">; def err_omp_atomic_several_clauses : Error< "directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause">; def note_omp_atomic_previous_clause : Note< "'%0' clause used here">; def err_omp_target_contains_not_only_teams : Error< "target construct with nested teams region contains statements outside of the teams construct">; def note_omp_nested_teams_construct_here : Note< "nested teams construct here">; def note_omp_nested_statement_here : Note< "%select{statement|directive}0 outside teams construct here">; def err_omp_single_copyprivate_with_nowait : Error< "the 'copyprivate' clause must not be used with the 'nowait' clause">; def note_omp_nowait_clause_here : Note< "'nowait' clause is here">; def err_omp_single_decl_in_declare_simd : Error< "single declaration is expected after 'declare simd' directive">; def err_omp_function_expected : Error< "'#pragma omp declare simd' can only be applied to functions">; def err_omp_wrong_cancel_region : Error< "one of 'for', 'parallel', 'sections' or 'taskgroup' is expected">; def err_omp_parent_cancel_region_nowait : Error< "parent region for 'omp %select{cancellation point|cancel}0' construct cannot be nowait">; def err_omp_parent_cancel_region_ordered : Error< "parent region for 'omp %select{cancellation point|cancel}0' construct cannot be ordered">; def err_omp_reduction_wrong_type : Error<"reduction type cannot be %select{qualified with 'const', 'volatile' or 'restrict'|a function|a reference|an array}0 type">; def err_omp_wrong_var_in_declare_reduction : Error<"only %select{'omp_priv' or 'omp_orig'|'omp_in' or 'omp_out'}0 variables are allowed in %select{initializer|combiner}0 expression">; def err_omp_declare_reduction_redefinition : Error<"redefinition of user-defined reduction for type %0">; def err_omp_array_section_use : Error<"OpenMP array section is not allowed here">; def err_omp_typecheck_section_value : Error< "subscripted value is not an array or pointer">; def err_omp_typecheck_section_not_integer : Error< "array section %select{lower bound|length}0 is not an integer">; def err_omp_section_function_type : Error< "section of pointer to function type %0">; def warn_omp_section_is_char : Warning<"array section %select{lower bound|length}0 is of type 'char'">, InGroup, DefaultIgnore; def err_omp_section_incomplete_type : Error< "section of pointer to incomplete type %0">; def err_omp_section_not_subset_of_array : Error< "array section must be a subset of the original array">; def err_omp_section_length_negative : Error< "section length is evaluated to a negative value %0">; def err_omp_section_length_undefined : Error< "section length is unspecified and cannot be inferred because subscripted value is %select{not an array|an array of unknown bound}0">; def err_omp_wrong_linear_modifier : Error< "expected %select{'val' modifier|one of 'ref', val' or 'uval' modifiers}0">; def err_omp_wrong_linear_modifier_non_reference : Error< "variable of non-reference type %0 can be used only with 'val' modifier, but used with '%1'">; def err_omp_wrong_simdlen_safelen_values : Error< "the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter">; def err_omp_wrong_if_directive_name_modifier : Error< "directive name modifier '%0' is not allowed for '#pragma omp %1'">; def err_omp_no_more_if_clause : Error< "no more 'if' clause is allowed">; def err_omp_unnamed_if_clause : Error< "expected %select{|one of}0 %1 directive name modifier%select{|s}0">; def note_omp_previous_named_if_clause : Note< "previous clause with directive name modifier specified here">; def err_omp_ordered_directive_with_param : Error< "'ordered' directive %select{without any clauses|with 'threads' clause}0 cannot be closely nested inside ordered region with specified parameter">; def err_omp_ordered_directive_without_param : Error< "'ordered' directive with 'depend' clause cannot be closely nested inside ordered region without specified parameter">; def note_omp_ordered_param : Note< "'ordered' clause with specified parameter">; def err_omp_expected_base_var_name : Error< "expected variable name as a base of the array %select{subscript|section}0">; def err_omp_map_shared_storage : Error< "variable already marked as mapped in current construct">; def err_omp_invalid_map_type_for_directive : Error< "%select{map type '%1' is not allowed|map type must be specified}0 for '#pragma omp %2'">; def err_omp_no_clause_for_directive : Error< "expected at least one %0 clause for '#pragma omp %1'">; def err_omp_threadprivate_in_clause : Error< "threadprivate variables are not allowed in '%0' clause">; def err_omp_wrong_ordered_loop_count : Error< "the parameter of the 'ordered' clause must be greater than or equal to the parameter of the 'collapse' clause">; def note_collapse_loop_count : Note< "parameter of the 'collapse' clause">; def err_omp_grainsize_num_tasks_mutually_exclusive : Error< "'%0' and '%1' clause are mutually exclusive and may not appear on the same directive">; def note_omp_previous_grainsize_num_tasks : Note< "'%0' clause is specified here">; def err_omp_hint_clause_no_name : Error< "the name of the construct must be specified in presence of 'hint' clause">; def err_omp_critical_with_hint : Error< "constructs with the same name must have a 'hint' clause with the same value">; def note_omp_critical_hint_here : Note< "%select{|previous }0'hint' clause with value '%1'">; def note_omp_critical_no_hint : Note< "%select{|previous }0directive with no 'hint' clause specified">; def err_omp_depend_clause_thread_simd : Error< "'depend' clauses cannot be mixed with '%0' clause">; def err_omp_depend_sink_expected_loop_iteration : Error< "expected%select{| %1}0 loop iteration variable">; def err_omp_depend_sink_unexpected_expr : Error< "unexpected expression: number of expressions is larger than the number of associated loops">; def err_omp_depend_sink_expected_plus_minus : Error< "expected '+' or '-' operation">; def err_omp_depend_sink_source_not_allowed : Error< "'depend(%select{source|sink:vec}0)' clause%select{|s}0 cannot be mixed with 'depend(%select{sink:vec|source}0)' clause%select{s|}0">; def err_omp_linear_ordered : Error< "'linear' clause cannot be specified along with 'ordered' clause with a parameter">; def err_omp_unexpected_schedule_modifier : Error< "modifier '%0' cannot be used along with modifier '%1'">; def err_omp_schedule_nonmonotonic_static : Error< "'nonmonotonic' modifier can only be specified with 'dynamic' or 'guided' schedule kind">; def err_omp_schedule_nonmonotonic_ordered : Error< "'schedule' clause with 'nonmonotonic' modifier cannot be specified if an 'ordered' clause is specified">; def err_omp_ordered_simd : Error< "'ordered' clause with a parameter can not be specified in '#pragma omp %0' directive">; def err_omp_variable_in_given_clause_and_dsa : Error< "%0 variable cannot be in a %1 clause in '#pragma omp %2' directive">; def err_omp_param_or_this_in_clause : Error< "expected reference to one of the parameters of function %0%select{| or 'this'}1">; def err_omp_expected_uniform_param : Error< "expected a reference to a parameter specified in a 'uniform' clause">; def err_omp_expected_int_param : Error< "expected a reference to an integer-typed parameter">; def err_omp_at_least_one_motion_clause_required : Error< "expected at least one 'to' clause or 'from' clause specified to '#pragma omp target update'">; def err_omp_usedeviceptr_not_a_pointer : Error< "expected pointer or reference to pointer in 'use_device_ptr' clause">; def err_omp_argument_type_isdeviceptr : Error < "expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'">; def warn_omp_nesting_simd : Warning< "OpenMP only allows an ordered construct with the simd clause nested in a simd construct">, InGroup; def err_omp_orphaned_device_directive : Error< "orphaned 'omp %0' directives are prohibited" "; perhaps you forget to enclose the directive into a %select{|||target |teams }1region?">; def err_omp_reduction_non_addressable_expression : Error< "expected addressable reduction item for the task-based directives">; def err_omp_reduction_with_nogroup : Error< "'reduction' clause cannot be used with 'nogroup' clause">; def err_omp_reduction_vla_unsupported : Error< "cannot generate code for reduction on %select{|array section, which requires a }0variable length array">; def err_omp_linear_distribute_var_non_loop_iteration : Error< "only loop iteration variables are allowed in 'linear' clause in distribute directives">; def warn_omp_non_trivial_type_mapped : Warning< "Non-trivial type %0 is mapped, only trivial types are guaranteed to be mapped correctly">, InGroup; def err_omp_requires_clause_redeclaration : Error < "Only one %0 clause can appear on a requires directive in a single translation unit">; def note_omp_requires_previous_clause : Note < "%0 clause previously used here">; def err_omp_invalid_scope : Error < "'#pragma omp %0' directive must appear only in file scope">; def note_omp_invalid_length_on_this_ptr_mapping : Note < "expected length on mapping of 'this' array section expression to be '1'">; def note_omp_invalid_lower_bound_on_this_ptr_mapping : Note < "expected lower bound on mapping of 'this' array section expression to be '0' or not specified">; def note_omp_invalid_subscript_on_this_ptr_map : Note < "expected 'this' subscript expression on map clause to be 'this[0]'">; def err_omp_invalid_map_this_expr : Error < "invalid 'this' expression on 'map' clause">; } // end of OpenMP category let CategoryName = "Related Result Type Issue" in { // Objective-C related result type compatibility def warn_related_result_type_compatibility_class : Warning< "method is expected to return an instance of its class type " "%diff{$, but is declared to return $|" ", but is declared to return different type}0,1">; def warn_related_result_type_compatibility_protocol : Warning< "protocol method is expected to return an instance of the implementing " "class, but is declared to return %0">; def note_related_result_type_family : Note< "%select{overridden|current}0 method is part of the '%select{|alloc|copy|init|" "mutableCopy|new|autorelease|dealloc|finalize|release|retain|retainCount|" "self}1' method family%select{| and is expected to return an instance of its " "class type}0">; def note_related_result_type_overridden : Note< "overridden method returns an instance of its class type">; def note_related_result_type_inferred : Note< "%select{class|instance}0 method %1 is assumed to return an instance of " "its receiver type (%2)">; def note_related_result_type_explicit : Note< "%select{overridden|current}0 method is explicitly declared 'instancetype'" "%select{| and is expected to return an instance of its class type}0">; def err_invalid_type_for_program_scope_var : Error< "the %0 type cannot be used to declare a program scope variable">; } let CategoryName = "Modules Issue" in { def err_module_decl_in_module_map_module : Error< "'module' declaration found while building module from module map">; def err_module_decl_in_header_module : Error< "'module' declaration found while building header module">; def err_module_interface_implementation_mismatch : Error< "missing 'export' specifier in module declaration while " "building module interface">; def err_current_module_name_mismatch : Error< "module name '%0' specified on command line does not match name of module">; def err_module_redefinition : Error< "redefinition of module '%0'">; def note_prev_module_definition : Note<"previously defined here">; def note_prev_module_definition_from_ast_file : Note<"module loaded from '%0'">; def err_module_not_defined : Error< "definition of module '%0' is not available; use -fmodule-file= to specify " "path to precompiled module interface">; def err_module_redeclaration : Error< "translation unit contains multiple module declarations">; def note_prev_module_declaration : Note<"previous module declaration is here">; def err_module_declaration_missing : Error< "missing 'export module' declaration in module interface unit">; def err_module_private_specialization : Error< "%select{template|partial|member}0 specialization cannot be " "declared __module_private__">; def err_module_private_local : Error< "%select{local variable|parameter|typedef}0 %1 cannot be declared " "__module_private__">; def err_module_private_local_class : Error< "local %select{struct|interface|union|class|enum}0 cannot be declared " "__module_private__">; def err_module_unimported_use : Error< "%select{declaration|definition|default argument|" "explicit specialization|partial specialization}0 of %1 must be imported " "from module '%2' before it is required">; def err_module_unimported_use_header : Error< "missing '#include %3'; " "%select{declaration|definition|default argument|" "explicit specialization|partial specialization}0 of %1 must be imported " "from module '%2' before it is required">; def err_module_unimported_use_multiple : Error< "%select{declaration|definition|default argument|" "explicit specialization|partial specialization}0 of %1 must be imported " "from one of the following modules before it is required:%2">; def ext_module_import_in_extern_c : ExtWarn< "import of C++ module '%0' appears within extern \"C\" language linkage " "specification">, DefaultError, InGroup>; def err_module_import_not_at_top_level_fatal : Error< "import of module '%0' appears within %1">, DefaultFatal; def ext_module_import_not_at_top_level_noop : ExtWarn< "redundant #include of module '%0' appears within %1">, DefaultError, InGroup>; def note_module_import_not_at_top_level : Note<"%0 begins here">; def err_module_self_import : Error< "import of module '%0' appears within same top-level module '%1'">; def err_module_import_in_implementation : Error< "@import of module '%0' in implementation of '%1'; use #import">; // C++ Modules TS def err_export_within_export : Error< "export declaration appears within another export declaration">; def err_export_not_in_module_interface : Error< "export declaration can only be used within a module interface unit after " "the module declaration">; def ext_equivalent_internal_linkage_decl_in_modules : ExtWarn< "ambiguous use of internal linkage declaration %0 defined in multiple modules">, InGroup>; def note_equivalent_internal_linkage_decl : Note< "declared here%select{ in module '%1'|}0">; def note_redefinition_modules_same_file : Note< "'%0' included multiple times, additional include site in header from module '%1'">; def note_redefinition_include_same_file : Note< "'%0' included multiple times, additional include site here">; } let CategoryName = "Coroutines Issue" in { def err_return_in_coroutine : Error< "return statement not allowed in coroutine; did you mean 'co_return'?">; def note_declared_coroutine_here : Note< "function is a coroutine due to use of '%0' here">; def err_coroutine_objc_method : Error< "Objective-C methods as coroutines are not yet supported">; def err_coroutine_unevaluated_context : Error< "'%0' cannot be used in an unevaluated context">; def err_coroutine_outside_function : Error< "'%0' cannot be used outside a function">; def err_coroutine_invalid_func_context : Error< "'%1' cannot be used in %select{a constructor|a destructor" "|a copy assignment operator|a move assignment operator|the 'main' function" "|a constexpr function|a function with a deduced return type" "|a varargs function}0">; def err_implied_coroutine_type_not_found : Error< "%0 type was not found; include before defining " "a coroutine">; def err_implicit_coroutine_std_nothrow_type_not_found : Error< "std::nothrow was not found; include before defining a coroutine which " "uses get_return_object_on_allocation_failure()">; def err_malformed_std_nothrow : Error< "std::nothrow must be a valid variable declaration">; def err_malformed_std_coroutine_handle : Error< "std::experimental::coroutine_handle must be a class template">; def err_coroutine_handle_missing_member : Error< "std::experimental::coroutine_handle missing a member named '%0'">; def err_malformed_std_coroutine_traits : Error< "'std::experimental::coroutine_traits' must be a class template">; def err_implied_std_coroutine_traits_promise_type_not_found : Error< "this function cannot be a coroutine: %q0 has no member named 'promise_type'">; def err_implied_std_coroutine_traits_promise_type_not_class : Error< "this function cannot be a coroutine: %0 is not a class">; def err_coroutine_promise_type_incomplete : Error< "this function cannot be a coroutine: %0 is an incomplete type">; def err_coroutine_type_missing_specialization : Error< "this function cannot be a coroutine: missing definition of " "specialization %0">; def err_coroutine_promise_incompatible_return_functions : Error< "the coroutine promise type %0 declares both 'return_value' and 'return_void'">; def err_coroutine_promise_requires_return_function : Error< "the coroutine promise type %0 must declare either 'return_value' or 'return_void'">; def note_coroutine_promise_implicit_await_transform_required_here : Note< "call to 'await_transform' implicitly required by 'co_await' here">; def note_coroutine_promise_suspend_implicitly_required : Note< "call to '%select{initial_suspend|final_suspend}0' implicitly " "required by the %select{initial suspend point|final suspend point}0">; def err_coroutine_promise_unhandled_exception_required : Error< "%0 is required to declare the member 'unhandled_exception()'">; def warn_coroutine_promise_unhandled_exception_required_with_exceptions : Warning< "%0 is required to declare the member 'unhandled_exception()' when exceptions are enabled">, InGroup; def err_coroutine_promise_get_return_object_on_allocation_failure : Error< "%0: 'get_return_object_on_allocation_failure()' must be a static member function">; def err_seh_in_a_coroutine_with_cxx_exceptions : Error< "cannot use SEH '__try' in a coroutine when C++ exceptions are enabled">; def err_coroutine_promise_new_requires_nothrow : Error< "%0 is required to have a non-throwing noexcept specification when the promise " "type declares 'get_return_object_on_allocation_failure()'">; def note_coroutine_promise_call_implicitly_required : Note< "call to %0 implicitly required by coroutine function here">; def err_await_suspend_invalid_return_type : Error< "return type of 'await_suspend' is required to be 'void' or 'bool' (have %0)" >; def note_await_ready_no_bool_conversion : Note< "return type of 'await_ready' is required to be contextually convertible to 'bool'" >; } let CategoryName = "Documentation Issue" in { def warn_not_a_doxygen_trailing_member_comment : Warning< "not a Doxygen trailing comment">, InGroup, DefaultIgnore; } // end of documentation issue category let CategoryName = "Nullability Issue" in { def warn_mismatched_nullability_attr : Warning< "nullability specifier %0 conflicts with existing specifier %1">, InGroup; def warn_nullability_declspec : Warning< "nullability specifier %0 cannot be applied " "to non-pointer type %1; did you mean to apply the specifier to the " "%select{pointer|block pointer|member pointer|function pointer|" "member function pointer}2?">, InGroup, DefaultError; def note_nullability_here : Note<"%0 specified here">; def err_nullability_nonpointer : Error< "nullability specifier %0 cannot be applied to non-pointer type %1">; def warn_nullability_lost : Warning< "implicit conversion from nullable pointer %0 to non-nullable pointer " "type %1">, InGroup, DefaultIgnore; def warn_zero_as_null_pointer_constant : Warning< "zero as null pointer constant">, InGroup>, DefaultIgnore; def err_nullability_cs_multilevel : Error< "nullability keyword %0 cannot be applied to multi-level pointer type %1">; def note_nullability_type_specifier : Note< "use nullability type specifier %0 to affect the innermost " "pointer type of %1">; def warn_null_resettable_setter : Warning< "synthesized setter %0 for null_resettable property %1 does not handle nil">, InGroup; def warn_nullability_missing : Warning< "%select{pointer|block pointer|member pointer}0 is missing a nullability " "type specifier (_Nonnull, _Nullable, or _Null_unspecified)">, InGroup; def warn_nullability_missing_array : Warning< "array parameter is missing a nullability type specifier (_Nonnull, " "_Nullable, or _Null_unspecified)">, InGroup; def note_nullability_fix_it : Note< "insert '%select{_Nonnull|_Nullable|_Null_unspecified}0' if the " "%select{pointer|block pointer|member pointer|array parameter}1 " "%select{should never be null|may be null|should not declare nullability}0">; def warn_nullability_inferred_on_nested_type : Warning< "inferring '_Nonnull' for pointer type within %select{array|reference}0 is " "deprecated">, InGroup; def err_objc_type_arg_explicit_nullability : Error< "type argument %0 cannot explicitly specify nullability">; def err_objc_type_param_bound_explicit_nullability : Error< "type parameter %0 bound %1 cannot explicitly specify nullability">; } let CategoryName = "Generics Issue" in { def err_objc_type_param_bound_nonobject : Error< "type bound %0 for type parameter %1 is not an Objective-C pointer type">; def err_objc_type_param_bound_missing_pointer : Error< "missing '*' in type bound %0 for type parameter %1">; def err_objc_type_param_bound_qualified : Error< "type bound %1 for type parameter %0 cannot be qualified with '%2'">; def err_objc_type_param_redecl : Error< "redeclaration of type parameter %0">; def err_objc_type_param_arity_mismatch : Error< "%select{forward class declaration|class definition|category|extension}0 has " "too %select{few|many}1 type parameters (expected %2, have %3)">; def err_objc_type_param_bound_conflict : Error< "type bound %0 for type parameter %1 conflicts with " "%select{implicit|previous}2 bound %3%select{for type parameter %5|}4">; def err_objc_type_param_variance_conflict : Error< "%select{in|co|contra}0variant type parameter %1 conflicts with previous " "%select{in|co|contra}2variant type parameter %3">; def note_objc_type_param_here : Note<"type parameter %0 declared here">; def err_objc_type_param_bound_missing : Error< "missing type bound %0 for type parameter %1 in %select{@interface|@class}2">; def err_objc_parameterized_category_nonclass : Error< "%select{extension|category}0 of non-parameterized class %1 cannot have type " "parameters">; def err_objc_parameterized_forward_class : Error< "forward declaration of non-parameterized class %0 cannot have type " "parameters">; def err_objc_parameterized_forward_class_first : Error< "class %0 previously declared with type parameters">; def err_objc_type_arg_missing_star : Error< "type argument %0 must be a pointer (requires a '*')">; def err_objc_type_arg_qualified : Error< "type argument %0 cannot be qualified with '%1'">; def err_objc_type_arg_missing : Error< "no type or protocol named %0">; def err_objc_type_args_and_protocols : Error< "angle brackets contain both a %select{type|protocol}0 (%1) and a " "%select{protocol|type}0 (%2)">; def err_objc_type_args_non_class : Error< "type arguments cannot be applied to non-class type %0">; def err_objc_type_args_non_parameterized_class : Error< "type arguments cannot be applied to non-parameterized class %0">; def err_objc_type_args_specialized_class : Error< "type arguments cannot be applied to already-specialized class type %0">; def err_objc_type_args_wrong_arity : Error< "too %select{many|few}0 type arguments for class %1 (have %2, expected %3)">; } def err_objc_type_arg_not_id_compatible : Error< "type argument %0 is neither an Objective-C object nor a block type">; def err_objc_type_arg_does_not_match_bound : Error< "type argument %0 does not satisfy the bound (%1) of type parameter %2">; def warn_objc_redundant_qualified_class_type : Warning< "parameterized class %0 already conforms to the protocols listed; did you " "forget a '*'?">, InGroup; def warn_block_literal_attributes_on_omitted_return_type : Warning< "attribute %0 ignored, because it cannot be applied to omitted return type">, InGroup; def warn_block_literal_qualifiers_on_omitted_return_type : Warning< "'%0' qualifier on omitted return type %1 has no effect">, InGroup; def warn_shadow_field : Warning< "%select{parameter|non-static data member}3 %0 %select{|of %1 }3shadows " "member inherited from type %2">, InGroup, DefaultIgnore; def note_shadow_field : Note<"declared here">; def err_multiversion_required_in_redecl : Error< "function declaration is missing %select{'target'|'cpu_specific' or " "'cpu_dispatch'}0 attribute in a multiversioned function">; def note_multiversioning_caused_here : Note< "function multiversioning caused by this declaration">; def err_multiversion_after_used : Error< "function declaration cannot become a multiversioned function after first " "usage">; def err_bad_multiversion_option : Error< "function multiversioning doesn't support %select{feature|architecture}0 " "'%1'">; def err_multiversion_duplicate : Error< "multiversioned function redeclarations require identical target attributes">; def err_multiversion_noproto : Error< "multiversioned function must have a prototype">; def err_multiversion_no_other_attrs : Error< "attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioning cannot be combined" " with other attributes">; def err_multiversion_diff : Error< "multiversioned function declaration has a different %select{calling convention" "|return type|constexpr specification|inline specification|storage class|" "linkage}0">; def err_multiversion_doesnt_support : Error< "attribute '%select{target|cpu_specific|cpu_dispatch}0' multiversioned functions do not " "yet support %select{function templates|virtual functions|" "deduced return types|constructors|destructors|deleted functions|" "defaulted functions|constexpr functions}1">; def err_multiversion_not_allowed_on_main : Error< "'main' cannot be a multiversioned function">; def err_multiversion_not_supported : Error< "function multiversioning is not supported on the current target">; def err_multiversion_types_mixed : Error< "multiversioning attributes cannot be combined">; def err_cpu_dispatch_mismatch : Error< "'cpu_dispatch' function redeclared with different CPUs">; def err_cpu_specific_multiple_defs : Error< "multiple 'cpu_specific' functions cannot specify the same CPU: %0">; def warn_multiversion_duplicate_entries : Warning< "CPU list contains duplicate entries; attribute ignored">, InGroup; def warn_dispatch_body_ignored : Warning< "body of cpu_dispatch function will be ignored">, InGroup; // three-way comparison operator diagnostics def err_implied_comparison_category_type_not_found : Error< "cannot deduce return type of 'operator<=>' because type '%0' was not found; " "include ">; def err_spaceship_argument_narrowing : Error< "argument to 'operator<=>' " "%select{cannot be narrowed from type %1 to %2|" "evaluates to %1, which cannot be narrowed to type %2}0">; def err_std_compare_type_not_supported : Error< "standard library implementation of %0 is not supported; " "%select{member '%2' does not have expected form|" "member '%2' is missing|" "the type is not trivially copyable|" "the type does not have the expected form}1">; def warn_dereference_of_noderef_type : Warning< "dereferencing %0; was declared with a 'noderef' type">, InGroup; def warn_dereference_of_noderef_type_no_decl : Warning< "dereferencing expression marked as 'noderef'">, InGroup; def warn_noderef_on_non_pointer_or_array : Warning< "'noderef' can only be used on an array or pointer type">, InGroup; def warn_noderef_to_dereferenceable_pointer : Warning< "casting to dereferenceable pointer removes 'noderef' attribute">, InGroup; def err_builtin_launder_invalid_arg : Error< "%select{non-pointer|function pointer|void pointer}0 argument to " "'__builtin_launder' is not allowed">; } // end of sema component. Index: vendor/clang/dist-release_80/lib/Basic/Version.cpp =================================================================== --- vendor/clang/dist-release_80/lib/Basic/Version.cpp (revision 343192) +++ vendor/clang/dist-release_80/lib/Basic/Version.cpp (revision 343193) @@ -1,151 +1,151 @@ //===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several version-related utility functions for Clang. // //===----------------------------------------------------------------------===// #include "clang/Basic/Version.h" #include "clang/Basic/LLVM.h" #include "clang/Config/config.h" #include "llvm/Support/raw_ostream.h" #include #include #ifdef HAVE_SVN_VERSION_INC # include "SVNVersion.inc" #endif namespace clang { std::string getClangRepositoryPath() { #if defined(CLANG_REPOSITORY_STRING) return CLANG_REPOSITORY_STRING; #else #ifdef SVN_REPOSITORY StringRef URL(SVN_REPOSITORY); #else StringRef URL(""); #endif // If the SVN_REPOSITORY is empty, try to use the SVN keyword. This helps us // pick up a tag in an SVN export, for example. - StringRef SVNRepository("$URL: https://llvm.org/svn/llvm-project/cfe/trunk/lib/Basic/Version.cpp $"); + StringRef SVNRepository("$URL: https://llvm.org/svn/llvm-project/cfe/branches/release_80/lib/Basic/Version.cpp $"); if (URL.empty()) { URL = SVNRepository.slice(SVNRepository.find(':'), SVNRepository.find("/lib/Basic")); } // Strip off version from a build from an integration branch. URL = URL.slice(0, URL.find("/src/tools/clang")); // Trim path prefix off, assuming path came from standard cfe path. size_t Start = URL.find("cfe/"); if (Start != StringRef::npos) URL = URL.substr(Start + 4); return URL; #endif } std::string getLLVMRepositoryPath() { #ifdef LLVM_REPOSITORY StringRef URL(LLVM_REPOSITORY); #else StringRef URL(""); #endif // Trim path prefix off, assuming path came from standard llvm path. // Leave "llvm/" prefix to distinguish the following llvm revision from the // clang revision. size_t Start = URL.find("llvm/"); if (Start != StringRef::npos) URL = URL.substr(Start); return URL; } std::string getClangRevision() { #ifdef SVN_REVISION return SVN_REVISION; #else return ""; #endif } std::string getLLVMRevision() { #ifdef LLVM_REVISION return LLVM_REVISION; #else return ""; #endif } std::string getClangFullRepositoryVersion() { std::string buf; llvm::raw_string_ostream OS(buf); std::string Path = getClangRepositoryPath(); std::string Revision = getClangRevision(); if (!Path.empty() || !Revision.empty()) { OS << '('; if (!Path.empty()) OS << Path; if (!Revision.empty()) { if (!Path.empty()) OS << ' '; OS << Revision; } OS << ')'; } // Support LLVM in a separate repository. std::string LLVMRev = getLLVMRevision(); if (!LLVMRev.empty() && LLVMRev != Revision) { OS << " ("; std::string LLVMRepo = getLLVMRepositoryPath(); if (!LLVMRepo.empty()) OS << LLVMRepo << ' '; OS << LLVMRev << ')'; } return OS.str(); } std::string getClangFullVersion() { return getClangToolFullVersion("clang"); } std::string getClangToolFullVersion(StringRef ToolName) { std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << ToolName << " version " CLANG_VERSION_STRING " " << getClangFullRepositoryVersion(); // If vendor supplied, include the base LLVM version as well. #ifdef CLANG_VENDOR OS << " (based on " << BACKEND_PACKAGE_STRING << ")"; #endif return OS.str(); } std::string getClangFullCPPVersion() { // The version string we report in __VERSION__ is just a compacted version of // the one we report on the command line. std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << "Clang " CLANG_VERSION_STRING " " << getClangFullRepositoryVersion(); return OS.str(); } } // end namespace clang Index: vendor/clang/dist-release_80/lib/CodeGen/ItaniumCXXABI.cpp =================================================================== --- vendor/clang/dist-release_80/lib/CodeGen/ItaniumCXXABI.cpp (revision 343192) +++ vendor/clang/dist-release_80/lib/CodeGen/ItaniumCXXABI.cpp (revision 343193) @@ -1,4279 +1,4281 @@ //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides C++ code generation targeting the Itanium C++ ABI. The class // in this file generates structures that follow the Itanium C++ ABI, which is // documented at: // http://www.codesourcery.com/public/cxx-abi/abi.html // http://www.codesourcery.com/public/cxx-abi/abi-eh.html // // It also supports the closely-related ARM ABI, documented at: // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf // //===----------------------------------------------------------------------===// #include "CGCXXABI.h" #include "CGCleanup.h" #include "CGRecordLayout.h" #include "CGVTables.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "TargetInfo.h" #include "clang/CodeGen/ConstantInitBuilder.h" #include "clang/AST/Mangle.h" #include "clang/AST/Type.h" #include "clang/AST/StmtCXX.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Value.h" #include "llvm/Support/ScopedPrinter.h" using namespace clang; using namespace CodeGen; namespace { class ItaniumCXXABI : public CodeGen::CGCXXABI { /// VTables - All the vtables which have been defined. llvm::DenseMap VTables; protected: bool UseARMMethodPtrABI; bool UseARMGuardVarABI; bool Use32BitVTableOffsetABI; ItaniumMangleContext &getMangleContext() { return cast(CodeGen::CGCXXABI::getMangleContext()); } public: ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool UseARMMethodPtrABI = false, bool UseARMGuardVarABI = false) : CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), UseARMGuardVarABI(UseARMGuardVarABI), Use32BitVTableOffsetABI(false) { } bool classifyReturnType(CGFunctionInfo &FI) const override; bool passClassIndirect(const CXXRecordDecl *RD) const { return !canCopyArgument(RD); } RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override { // If C++ prohibits us from making a copy, pass by address. if (passClassIndirect(RD)) return RAA_Indirect; return RAA_Default; } bool isThisCompleteObject(GlobalDecl GD) const override { // The Itanium ABI has separate complete-object vs. base-object // variants of both constructors and destructors. if (isa(GD.getDecl())) { switch (GD.getDtorType()) { case Dtor_Complete: case Dtor_Deleting: return true; case Dtor_Base: return false; case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?"); } llvm_unreachable("bad dtor kind"); } if (isa(GD.getDecl())) { switch (GD.getCtorType()) { case Ctor_Complete: return true; case Ctor_Base: return false; case Ctor_CopyingClosure: case Ctor_DefaultClosure: llvm_unreachable("closure ctors in Itanium ABI?"); case Ctor_Comdat: llvm_unreachable("emitting ctor comdat as function?"); } llvm_unreachable("bad dtor kind"); } // No other kinds. return false; } bool isZeroInitializable(const MemberPointerType *MPT) override; llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; CGCallee EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, Address This, llvm::Value *&ThisPtrForCall, llvm::Value *MemFnPtr, const MemberPointerType *MPT) override; llvm::Value * EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, const MemberPointerType *MPT) override; llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src) override; llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, llvm::Constant *Src) override; llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override; llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset) override; llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, CharUnits ThisAdjustment); llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality) override; llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *Addr, const MemberPointerType *MPT) override; void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, const CXXDestructorDecl *Dtor) override; /// Itanium says that an _Unwind_Exception has to be "double-word" /// aligned (and thus the end of it is also so-aligned), meaning 16 /// bytes. Of course, that was written for the actual Itanium, /// which is a 64-bit platform. Classically, the ABI doesn't really /// specify the alignment on other platforms, but in practice /// libUnwind declares the struct with __attribute__((aligned)), so /// we assume that alignment here. (It's generally 16 bytes, but /// some targets overwrite it.) CharUnits getAlignmentOfExnObject() { auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned(); return CGM.getContext().toCharUnitsFromBits(align); } void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override; void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override; void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override; llvm::CallInst * emitTerminateForUnexpectedException(CodeGenFunction &CGF, llvm::Value *Exn) override; void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD); llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; CatchTypeInfo getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override { return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0}; } bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; void EmitBadTypeidCall(CodeGenFunction &CGF) override; llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, Address ThisPtr, llvm::Type *StdTypeInfoPtrTy) override; bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, QualType SrcRecordTy) override; llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) override; llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy) override; bool EmitBadCastCall(CodeGenFunction &CGF) override; llvm::Value * GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl) override; void EmitCXXConstructors(const CXXConstructorDecl *D) override; AddedStructorArgs buildStructorSignature(const CXXMethodDecl *MD, StructorType T, SmallVectorImpl &ArgTys) override; bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, CXXDtorType DT) const override { // Itanium does not emit any destructor variant as an inline thunk. // Delegating may occur as an optimization, but all variants are either // emitted with external linkage or as linkonce if they are inline and used. return false; } void EmitCXXDestructors(const CXXDestructorDecl *D) override; void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params) override; void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; AddedStructorArgs addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, CallArgList &Args) override; void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This) override; void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD) override; bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) override; bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override { return true; } llvm::Constant * getVTableAddressPoint(BaseSubobject Base, const CXXRecordDecl *VTableClass) override; llvm::Value *getVTableAddressPointInStructor( CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, const CXXRecordDecl *NearestVBase) override; llvm::Value *getVTableAddressPointInStructorWithVTT( CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, const CXXRecordDecl *NearestVBase); llvm::Constant * getVTableAddressPointForConstExpr(BaseSubobject Base, const CXXRecordDecl *VTableClass) override; llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset) override; CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc) override; llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, Address This, const CXXMemberCallExpr *CE) override; void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override; bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const; void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment) override { // Allow inlining of thunks by emitting them with available_externally // linkage together with vtables when needed. if (ForVTable && !Thunk->hasLocalLinkage()) Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); CGM.setGVProperties(Thunk, GD); } bool exportThunk() override { return true; } llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA) override; llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA) override; size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, FunctionArgList &Args) const override { assert(!Args.empty() && "expected the arglist to not be empty!"); return Args.size() - 1; } StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; } StringRef GetDeletedVirtualCallName() override { return "__cxa_deleted_virtual"; } CharUnits getArrayCookieSizeImpl(QualType elementType) override; Address InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType) override; llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, CharUnits cookieSize) override; void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit) override; void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *dtor, llvm::Constant *addr) override; llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, llvm::Value *Val); void EmitThreadLocalInitFuncs( CodeGenModule &CGM, ArrayRef CXXThreadLocals, ArrayRef CXXThreadLocalInits, ArrayRef CXXThreadLocalInitVars) override; bool usesThreadWrapperFunction() const override { return true; } LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType) override; bool NeedsVTTParameter(GlobalDecl GD) override; /**************************** RTTI Uniqueness ******************************/ protected: /// Returns true if the ABI requires RTTI type_info objects to be unique /// across a program. virtual bool shouldRTTIBeUnique() const { return true; } public: /// What sort of unique-RTTI behavior should we use? enum RTTIUniquenessKind { /// We are guaranteeing, or need to guarantee, that the RTTI string /// is unique. RUK_Unique, /// We are not guaranteeing uniqueness for the RTTI string, so we /// can demote to hidden visibility but must use string comparisons. RUK_NonUniqueHidden, /// We are not guaranteeing uniqueness for the RTTI string, so we /// have to use string comparisons, but we also have to emit it with /// non-hidden visibility. RUK_NonUniqueVisible }; /// Return the required visibility status for the given type and linkage in /// the current ABI. RTTIUniquenessKind classifyRTTIUniqueness(QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const; friend class ItaniumRTTIBuilder; void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; std::pair LoadVTablePtr(CodeGenFunction &CGF, Address This, const CXXRecordDecl *RD) override; private: bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const { const auto &VtableLayout = CGM.getItaniumVTableContext().getVTableLayout(RD); for (const auto &VtableComponent : VtableLayout.vtable_components()) { // Skip empty slot. if (!VtableComponent.isUsedFunctionPointerKind()) continue; const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); if (!Method->getCanonicalDecl()->isInlined()) continue; StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl()); auto *Entry = CGM.GetGlobalValue(Name); // This checks if virtual inline function has already been emitted. // Note that it is possible that this inline function would be emitted // after trying to emit vtable speculatively. Because of this we do // an extra pass after emitting all deferred vtables to find and emit // these vtables opportunistically. if (!Entry || Entry->isDeclaration()) return true; } return false; } bool isVTableHidden(const CXXRecordDecl *RD) const { const auto &VtableLayout = CGM.getItaniumVTableContext().getVTableLayout(RD); for (const auto &VtableComponent : VtableLayout.vtable_components()) { if (VtableComponent.isRTTIKind()) { const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl(); if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility) return true; } else if (VtableComponent.isUsedFunctionPointerKind()) { const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); if (Method->getVisibility() == Visibility::HiddenVisibility && !Method->isDefined()) return true; } } return false; } }; class ARMCXXABI : public ItaniumCXXABI { public: ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, /* UseARMGuardVarABI = */ true) {} bool HasThisReturn(GlobalDecl GD) const override { return (isa(GD.getDecl()) || ( isa(GD.getDecl()) && GD.getDtorType() != Dtor_Deleting)); } void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy) override; CharUnits getArrayCookieSizeImpl(QualType elementType) override; Address InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType) override; llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, CharUnits cookieSize) override; }; class iOS64CXXABI : public ARMCXXABI { public: iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) { Use32BitVTableOffsetABI = true; } // ARM64 libraries are prepared for non-unique RTTI. bool shouldRTTIBeUnique() const override { return false; } }; class WebAssemblyCXXABI final : public ItaniumCXXABI { public: explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true, /*UseARMGuardVarABI=*/true) {} void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override; private: bool HasThisReturn(GlobalDecl GD) const override { return isa(GD.getDecl()) || (isa(GD.getDecl()) && GD.getDtorType() != Dtor_Deleting); } bool canCallMismatchedFunctionType() const override { return false; } }; } CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { switch (CGM.getTarget().getCXXABI().getKind()) { // For IR-generation purposes, there's no significant difference // between the ARM and iOS ABIs. case TargetCXXABI::GenericARM: case TargetCXXABI::iOS: case TargetCXXABI::WatchOS: return new ARMCXXABI(CGM); case TargetCXXABI::iOS64: return new iOS64CXXABI(CGM); // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't // include the other 32-bit ARM oddities: constructor/destructor return values // and array cookies. case TargetCXXABI::GenericAArch64: return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, /* UseARMGuardVarABI = */ true); case TargetCXXABI::GenericMIPS: return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true); case TargetCXXABI::WebAssembly: return new WebAssemblyCXXABI(CGM); case TargetCXXABI::GenericItanium: if (CGM.getContext().getTargetInfo().getTriple().getArch() == llvm::Triple::le32) { // For PNaCl, use ARM-style method pointers so that PNaCl code // does not assume anything about the alignment of function // pointers. return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, /* UseARMGuardVarABI = */ false); } return new ItaniumCXXABI(CGM); case TargetCXXABI::Microsoft: llvm_unreachable("Microsoft ABI is not Itanium-based"); } llvm_unreachable("bad ABI kind"); } llvm::Type * ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { if (MPT->isMemberDataPointer()) return CGM.PtrDiffTy; return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy); } /// In the Itanium and ARM ABIs, method pointers have the form: /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; /// /// In the Itanium ABI: /// - method pointers are virtual if (memptr.ptr & 1) is nonzero /// - the this-adjustment is (memptr.adj) /// - the virtual offset is (memptr.ptr - 1) /// /// In the ARM ABI: /// - method pointers are virtual if (memptr.adj & 1) is nonzero /// - the this-adjustment is (memptr.adj >> 1) /// - the virtual offset is (memptr.ptr) /// ARM uses 'adj' for the virtual flag because Thumb functions /// may be only single-byte aligned. /// /// If the member is virtual, the adjusted 'this' pointer points /// to a vtable pointer from which the virtual offset is applied. /// /// If the member is non-virtual, memptr.ptr is the address of /// the function to call. CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer( CodeGenFunction &CGF, const Expr *E, Address ThisAddr, llvm::Value *&ThisPtrForCall, llvm::Value *MemFnPtr, const MemberPointerType *MPT) { CGBuilderTy &Builder = CGF.Builder; const FunctionProtoType *FPT = MPT->getPointeeType()->getAs(); const CXXRecordDecl *RD = cast(MPT->getClass()->getAs()->getDecl()); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); // Extract memptr.adj, which is in the second field. llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); // Compute the true adjustment. llvm::Value *Adj = RawAdj; if (UseARMMethodPtrABI) Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); // Apply the adjustment and cast back to the original struct type // for consistency. llvm::Value *This = ThisAddr.getPointer(); llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); ThisPtrForCall = This; // Load the function pointer. llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); // If the LSB in the function pointer is 1, the function pointer points to // a virtual function. llvm::Value *IsVirtual; if (UseARMMethodPtrABI) IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); else IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); // In the virtual path, the adjustment left 'This' pointing to the // vtable of the correct base subobject. The "function pointer" is an // offset within the vtable (+1 for the virtual flag on non-ARM). CGF.EmitBlock(FnVirtual); // Cast the adjusted this to a pointer to vtable pointer and load. llvm::Type *VTableTy = Builder.getInt8PtrTy(); CharUnits VTablePtrAlign = CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD, CGF.getPointerAlign()); llvm::Value *VTable = CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD); // Apply the offset. // On ARM64, to reserve extra space in virtual member function pointers, // we only pay attention to the low 32 bits of the offset. llvm::Value *VTableOffset = FnAsInt; if (!UseARMMethodPtrABI) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); if (Use32BitVTableOffsetABI) { VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty); VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy); } // Compute the address of the virtual function pointer. llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset); // Check the address of the function pointer if CFI on member function // pointers is enabled. llvm::Constant *CheckSourceLocation; llvm::Constant *CheckTypeDesc; bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) && CGM.HasHiddenLTOVisibility(RD); if (ShouldEmitCFICheck) { CodeGenFunction::SanitizerScope SanScope(&CGF); CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc()); CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0)); llvm::Constant *StaticData[] = { llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall), CheckSourceLocation, CheckTypeDesc, }; llvm::Metadata *MD = CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0)); llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD); llvm::Value *TypeTest = Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId}); if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) { CGF.EmitTrapCheck(TypeTest); } else { llvm::Value *AllVtables = llvm::MetadataAsValue::get( CGM.getLLVMContext(), llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); llvm::Value *ValidVtable = Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables}); CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall), SanitizerHandler::CFICheckFail, StaticData, {VTable, ValidVtable}); } FnVirtual = Builder.GetInsertBlock(); } // Load the virtual function to call. VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo()); llvm::Value *VirtualFn = Builder.CreateAlignedLoad( VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn"); CGF.EmitBranch(FnEnd); // In the non-virtual path, the function pointer is actually a // function pointer. CGF.EmitBlock(FnNonVirtual); llvm::Value *NonVirtualFn = Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); // Check the function pointer if CFI on member function pointers is enabled. if (ShouldEmitCFICheck) { CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); if (RD->hasDefinition()) { CodeGenFunction::SanitizerScope SanScope(&CGF); llvm::Constant *StaticData[] = { llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall), CheckSourceLocation, CheckTypeDesc, }; llvm::Value *Bit = Builder.getFalse(); llvm::Value *CastedNonVirtualFn = Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy); for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) { llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType( getContext().getMemberPointerType( MPT->getPointeeType(), getContext().getRecordType(Base).getTypePtr())); llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD); llvm::Value *TypeTest = Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedNonVirtualFn, TypeId}); Bit = Builder.CreateOr(Bit, TypeTest); } CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall), SanitizerHandler::CFICheckFail, StaticData, {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)}); FnNonVirtual = Builder.GetInsertBlock(); } } // We're done. CGF.EmitBlock(FnEnd); llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2); CalleePtr->addIncoming(VirtualFn, FnVirtual); CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual); CGCallee Callee(FPT, CalleePtr); return Callee; } /// Compute an l-value by applying the given pointer-to-member to a /// base object. llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress( CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, const MemberPointerType *MPT) { assert(MemPtr->getType() == CGM.PtrDiffTy); CGBuilderTy &Builder = CGF.Builder; // Cast to char*. Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty); // Apply the offset, which we assume is non-null. llvm::Value *Addr = Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset"); // Cast the address to the appropriate pointer type, adopting the // address space of the base pointer. llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType()) ->getPointerTo(Base.getAddressSpace()); return Builder.CreateBitCast(Addr, PType); } /// Perform a bitcast, derived-to-base, or base-to-derived member pointer /// conversion. /// /// Bitcast conversions are always a no-op under Itanium. /// /// Obligatory offset/adjustment diagram: /// <-- offset --> <-- adjustment --> /// |--------------------------|----------------------|--------------------| /// ^Derived address point ^Base address point ^Member address point /// /// So when converting a base member pointer to a derived member pointer, /// we add the offset to the adjustment because the address point has /// decreased; and conversely, when converting a derived MP to a base MP /// we subtract the offset from the adjustment because the address point /// has increased. /// /// The standard forbids (at compile time) conversion to and from /// virtual bases, which is why we don't have to consider them here. /// /// The standard forbids (at run time) casting a derived MP to a base /// MP when the derived MP does not point to a member of the base. /// This is why -1 is a reasonable choice for null data member /// pointers. llvm::Value * ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *src) { assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || E->getCastKind() == CK_BaseToDerivedMemberPointer || E->getCastKind() == CK_ReinterpretMemberPointer); // Under Itanium, reinterprets don't require any additional processing. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; // Use constant emission if we can. if (isa(src)) return EmitMemberPointerConversion(E, cast(src)); llvm::Constant *adj = getMemberPointerAdjustment(E); if (!adj) return src; CGBuilderTy &Builder = CGF.Builder; bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); const MemberPointerType *destTy = E->getType()->castAs(); // For member data pointers, this is just a matter of adding the // offset if the source is non-null. if (destTy->isMemberDataPointer()) { llvm::Value *dst; if (isDerivedToBase) dst = Builder.CreateNSWSub(src, adj, "adj"); else dst = Builder.CreateNSWAdd(src, adj, "adj"); // Null check. llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); return Builder.CreateSelect(isNull, src, dst); } // The this-adjustment is left-shifted by 1 on ARM. if (UseARMMethodPtrABI) { uint64_t offset = cast(adj)->getZExtValue(); offset <<= 1; adj = llvm::ConstantInt::get(adj->getType(), offset); } llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); llvm::Value *dstAdj; if (isDerivedToBase) dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); else dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); return Builder.CreateInsertValue(src, dstAdj, 1); } llvm::Constant * ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, llvm::Constant *src) { assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || E->getCastKind() == CK_BaseToDerivedMemberPointer || E->getCastKind() == CK_ReinterpretMemberPointer); // Under Itanium, reinterprets don't require any additional processing. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; // If the adjustment is trivial, we don't need to do anything. llvm::Constant *adj = getMemberPointerAdjustment(E); if (!adj) return src; bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); const MemberPointerType *destTy = E->getType()->castAs(); // For member data pointers, this is just a matter of adding the // offset if the source is non-null. if (destTy->isMemberDataPointer()) { // null maps to null. if (src->isAllOnesValue()) return src; if (isDerivedToBase) return llvm::ConstantExpr::getNSWSub(src, adj); else return llvm::ConstantExpr::getNSWAdd(src, adj); } // The this-adjustment is left-shifted by 1 on ARM. if (UseARMMethodPtrABI) { uint64_t offset = cast(adj)->getZExtValue(); offset <<= 1; adj = llvm::ConstantInt::get(adj->getType(), offset); } llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); llvm::Constant *dstAdj; if (isDerivedToBase) dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); else dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); } llvm::Constant * ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { // Itanium C++ ABI 2.3: // A NULL pointer is represented as -1. if (MPT->isMemberDataPointer()) return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); llvm::Constant *Values[2] = { Zero, Zero }; return llvm::ConstantStruct::getAnon(Values); } llvm::Constant * ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset) { // Itanium C++ ABI 2.3: // A pointer to data member is an offset from the base address of // the class object containing it, represented as a ptrdiff_t return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); } llvm::Constant * ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) { return BuildMemberPointer(MD, CharUnits::Zero()); } llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, CharUnits ThisAdjustment) { assert(MD->isInstance() && "Member function must not be static!"); CodeGenTypes &Types = CGM.getTypes(); // Get the function pointer (or index if this is a virtual function). llvm::Constant *MemPtr[2]; if (MD->isVirtual()) { uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); const ASTContext &Context = getContext(); CharUnits PointerWidth = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); if (UseARMMethodPtrABI) { // ARM C++ ABI 3.2.1: // This ABI specifies that adj contains twice the this // adjustment, plus 1 if the member function is virtual. The // least significant bit of adj then makes exactly the same // discrimination as the least significant bit of ptr does for // Itanium. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 2 * ThisAdjustment.getQuantity() + 1); } else { // Itanium C++ ABI 2.3: // For a virtual function, [the pointer field] is 1 plus the // virtual table offset (in bytes) of the function, // represented as a ptrdiff_t. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, ThisAdjustment.getQuantity()); } } else { const FunctionProtoType *FPT = MD->getType()->castAs(); llvm::Type *Ty; // Check whether the function has a computable LLVM signature. if (Types.isFuncTypeConvertible(FPT)) { // The function has a computable LLVM signature; use the correct type. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); } else { // Use an arbitrary non-function type to tell GetAddrOfFunction that the // function type is incomplete. Ty = CGM.PtrDiffTy; } llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, (UseARMMethodPtrABI ? 2 : 1) * ThisAdjustment.getQuantity()); } return llvm::ConstantStruct::getAnon(MemPtr); } llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, QualType MPType) { const MemberPointerType *MPT = MPType->castAs(); const ValueDecl *MPD = MP.getMemberPointerDecl(); if (!MPD) return EmitNullMemberPointer(MPT); CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); if (const CXXMethodDecl *MD = dyn_cast(MPD)) return BuildMemberPointer(MD, ThisAdjustment); CharUnits FieldOffset = getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); } /// The comparison algorithm is pretty easy: the member pointers are /// the same if they're either bitwise identical *or* both null. /// /// ARM is different here only because null-ness is more complicated. llvm::Value * ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality) { CGBuilderTy &Builder = CGF.Builder; llvm::ICmpInst::Predicate Eq; llvm::Instruction::BinaryOps And, Or; if (Inequality) { Eq = llvm::ICmpInst::ICMP_NE; And = llvm::Instruction::Or; Or = llvm::Instruction::And; } else { Eq = llvm::ICmpInst::ICMP_EQ; And = llvm::Instruction::And; Or = llvm::Instruction::Or; } // Member data pointers are easy because there's a unique null // value, so it just comes down to bitwise equality. if (MPT->isMemberDataPointer()) return Builder.CreateICmp(Eq, L, R); // For member function pointers, the tautologies are more complex. // The Itanium tautology is: // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) // The ARM tautology is: // (L == R) <==> (L.ptr == R.ptr && // (L.adj == R.adj || // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) // The inequality tautologies have exactly the same structure, except // applying De Morgan's laws. llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); // This condition tests whether L.ptr == R.ptr. This must always be // true for equality to hold. llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); // This condition, together with the assumption that L.ptr == R.ptr, // tests whether the pointers are both null. ARM imposes an extra // condition. llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); // This condition tests whether L.adj == R.adj. If this isn't // true, the pointers are unequal unless they're both null. llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); // Null member function pointers on ARM clear the low bit of Adj, // so the zero condition has to check that neither low bit is set. if (UseARMMethodPtrABI) { llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); // Compute (l.adj | r.adj) & 1 and test it against zero. llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, "cmp.or.adj"); EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); } // Tie together all our conditions. llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); Result = Builder.CreateBinOp(And, PtrEq, Result, Inequality ? "memptr.ne" : "memptr.eq"); return Result; } llvm::Value * ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT) { CGBuilderTy &Builder = CGF.Builder; /// For member data pointers, this is just a check against -1. if (MPT->isMemberDataPointer()) { assert(MemPtr->getType() == CGM.PtrDiffTy); llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(MemPtr->getType()); return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); } // In Itanium, a member function pointer is not null if 'ptr' is not null. llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); // On ARM, a member function pointer is also non-null if the low bit of 'adj' // (the virtual bit) is set. if (UseARMMethodPtrABI) { llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, "memptr.isvirtual"); Result = Builder.CreateOr(Result, IsVirtual); } return Result; } bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const { const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); if (!RD) return false; // If C++ prohibits us from making a copy, return by address. if (passClassIndirect(RD)) { auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType()); FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false); return true; } return false; } /// The Itanium ABI requires non-zero initialization only for data /// member pointers, for which '0' is a valid offset. bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { return MPT->isMemberFunctionPointer(); } /// The Itanium ABI always places an offset to the complete object /// at entry -2 in the vtable. void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, const CXXDestructorDecl *Dtor) { bool UseGlobalDelete = DE->isGlobalDelete(); if (UseGlobalDelete) { // Derive the complete-object pointer, which is what we need // to pass to the deallocation function. // Grab the vtable pointer as an intptr_t*. auto *ClassDecl = cast(ElementType->getAs()->getDecl()); llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl); // Track back to entry -2 and pull out the offset there. llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64( VTable, -2, "complete-offset.ptr"); llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); // Apply the offset. llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy); CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset); // If we're supposed to call the global delete, make sure we do so // even if the destructor throws. CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr, ElementType); } // FIXME: Provide a source location here even though there's no // CXXMemberCallExpr for dtor call. CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting; EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr); if (UseGlobalDelete) CGF.PopCleanupBlock(); } void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) { // void __cxa_rethrow(); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow"); if (isNoReturn) CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None); else CGF.EmitRuntimeCallOrInvoke(Fn); } static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) { // void *__cxa_allocate_exception(size_t thrown_size); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false); return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); } static llvm::Constant *getThrowFn(CodeGenModule &CGM) { // void __cxa_throw(void *thrown_exception, std::type_info *tinfo, // void (*dest) (void *)); llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false); return CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); } void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) { QualType ThrowType = E->getSubExpr()->getType(); // Now allocate the exception object. llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType()); uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity(); llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM); llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall( AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception"); CharUnits ExnAlign = getAlignmentOfExnObject(); CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign)); // Now throw the exception. llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, /*ForEH=*/true); // The address of the destructor. If the exception type has a // trivial destructor (or isn't a record), we just pass null. llvm::Constant *Dtor = nullptr; if (const RecordType *RecordTy = ThrowType->getAs()) { CXXRecordDecl *Record = cast(RecordTy->getDecl()); if (!Record->hasTrivialDestructor()) { CXXDestructorDecl *DtorD = Record->getDestructor(); Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete); Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy); } } if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy); llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor }; CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args); } static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) { // void *__dynamic_cast(const void *sub, // const abi::__class_type_info *src, // const abi::__class_type_info *dst, // std::ptrdiff_t src2dst_offset); llvm::Type *Int8PtrTy = CGF.Int8PtrTy; llvm::Type *PtrDiffTy = CGF.ConvertType(CGF.getContext().getPointerDiffType()); llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false); // Mark the function as nounwind readonly. llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind, llvm::Attribute::ReadOnly }; llvm::AttributeList Attrs = llvm::AttributeList::get( CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs); return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs); } static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { // void __cxa_bad_cast(); llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); } /// Compute the src2dst_offset hint as described in the /// Itanium C++ ABI [2.9.7] static CharUnits computeOffsetHint(ASTContext &Context, const CXXRecordDecl *Src, const CXXRecordDecl *Dst) { CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); // If Dst is not derived from Src we can skip the whole computation below and // return that Src is not a public base of Dst. Record all inheritance paths. if (!Dst->isDerivedFrom(Src, Paths)) return CharUnits::fromQuantity(-2ULL); unsigned NumPublicPaths = 0; CharUnits Offset; // Now walk all possible inheritance paths. for (const CXXBasePath &Path : Paths) { if (Path.Access != AS_public) // Ignore non-public inheritance. continue; ++NumPublicPaths; for (const CXXBasePathElement &PathElement : Path) { // If the path contains a virtual base class we can't give any hint. // -1: no hint. if (PathElement.Base->isVirtual()) return CharUnits::fromQuantity(-1ULL); if (NumPublicPaths > 1) // Won't use offsets, skip computation. continue; // Accumulate the base class offsets. const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class); Offset += L.getBaseClassOffset( PathElement.Base->getType()->getAsCXXRecordDecl()); } } // -2: Src is not a public base of Dst. if (NumPublicPaths == 0) return CharUnits::fromQuantity(-2ULL); // -3: Src is a multiple public base type but never a virtual base type. if (NumPublicPaths > 1) return CharUnits::fromQuantity(-3ULL); // Otherwise, the Src type is a unique public nonvirtual base type of Dst. // Return the offset of Src from the origin of Dst. return Offset; } static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { // void __cxa_bad_typeid(); llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); } bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) { return IsDeref; } void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { llvm::Value *Fn = getBadTypeidFn(CGF); CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); CGF.Builder.CreateUnreachable(); } llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, Address ThisPtr, llvm::Type *StdTypeInfoPtrTy) { auto *ClassDecl = cast(SrcRecordTy->getAs()->getDecl()); llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl); // Load the type info. Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign()); } bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, QualType SrcRecordTy) { return SrcIsPtr; } llvm::Value *ItaniumCXXABI::EmitDynamicCastCall( CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { llvm::Type *PtrDiffLTy = CGF.ConvertType(CGF.getContext().getPointerDiffType()); llvm::Type *DestLTy = CGF.ConvertType(DestTy); llvm::Value *SrcRTTI = CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); llvm::Value *DestRTTI = CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); // Compute the offset hint. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl(); llvm::Value *OffsetHint = llvm::ConstantInt::get( PtrDiffLTy, computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity()); // Emit the call to __dynamic_cast. llvm::Value *Value = ThisAddr.getPointer(); Value = CGF.EmitCastToVoidPtr(Value); llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint}; Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args); Value = CGF.Builder.CreateBitCast(Value, DestLTy); /// C++ [expr.dynamic.cast]p9: /// A failed cast to reference type throws std::bad_cast if (DestTy->isReferenceType()) { llvm::BasicBlock *BadCastBlock = CGF.createBasicBlock("dynamic_cast.bad_cast"); llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); CGF.EmitBlock(BadCastBlock); EmitBadCastCall(CGF); } return Value; } llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy, QualType DestTy) { llvm::Type *PtrDiffLTy = CGF.ConvertType(CGF.getContext().getPointerDiffType()); llvm::Type *DestLTy = CGF.ConvertType(DestTy); auto *ClassDecl = cast(SrcRecordTy->getAs()->getDecl()); // Get the vtable pointer. llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(), ClassDecl); // Get the offset-to-top from the vtable. llvm::Value *OffsetToTop = CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); OffsetToTop = CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(), "offset.to.top"); // Finally, add the offset to the pointer. llvm::Value *Value = ThisAddr.getPointer(); Value = CGF.EmitCastToVoidPtr(Value); Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); return CGF.Builder.CreateBitCast(Value, DestLTy); } bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { llvm::Value *Fn = getBadCastFn(CGF); CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); CGF.Builder.CreateUnreachable(); return true; } llvm::Value * ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl) { llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl); CharUnits VBaseOffsetOffset = CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); llvm::Value *VBaseOffsetPtr = CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), "vbase.offset.ptr"); VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, CGM.PtrDiffTy->getPointerTo()); llvm::Value *VBaseOffset = CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(), "vbase.offset"); return VBaseOffset; } void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { // Just make sure we're in sync with TargetCXXABI. assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); // The constructor used for constructing this as a base class; // ignores virtual bases. CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); // The constructor used for constructing this as a complete class; // constructs the virtual bases, then calls the base constructor. if (!D->getParent()->isAbstract()) { // We don't need to emit the complete ctor if the class is abstract. CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); } } CGCXXABI::AddedStructorArgs ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, SmallVectorImpl &ArgTys) { ASTContext &Context = getContext(); // All parameters are already in place except VTT, which goes after 'this'. // These are Clang types, so we don't need to worry about sret yet. // Check if we need to add a VTT parameter (which has type void **). if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) { ArgTys.insert(ArgTys.begin() + 1, Context.getPointerType(Context.VoidPtrTy)); return AddedStructorArgs::prefix(1); } return AddedStructorArgs{}; } void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { // The destructor used for destructing this as a base class; ignores // virtual bases. CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); // The destructor used for destructing this as a most-derived class; // call the base destructor and then destructs any virtual bases. CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); // The destructor in a virtual table is always a 'deleting' // destructor, which calls the complete destructor and then uses the // appropriate operator delete. if (D->isVirtual()) CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); } void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params) { const CXXMethodDecl *MD = cast(CGF.CurGD.getDecl()); assert(isa(MD) || isa(MD)); // Check if we need a VTT parameter as well. if (NeedsVTTParameter(CGF.CurGD)) { ASTContext &Context = getContext(); // FIXME: avoid the fake decl QualType T = Context.getPointerType(Context.VoidPtrTy); auto *VTTDecl = ImplicitParamDecl::Create( Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"), T, ImplicitParamDecl::CXXVTT); Params.insert(Params.begin() + 1, VTTDecl); getStructorImplicitParamDecl(CGF) = VTTDecl; } } void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { // Naked functions have no prolog. if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr()) return; /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue /// adjustments are required, because they are all handled by thunks. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); /// Initialize the 'vtt' slot if needed. if (getStructorImplicitParamDecl(CGF)) { getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); } /// If this is a function that the ABI specifies returns 'this', initialize /// the return slot to 'this' at the start of the function. /// /// Unlike the setting of return types, this is done within the ABI /// implementation instead of by clients of CGCXXABI because: /// 1) getThisValue is currently protected /// 2) in theory, an ABI could implement 'this' returns some other way; /// HasThisReturn only specifies a contract, not the implementation if (HasThisReturn(CGF.CurGD)) CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); } CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs( CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, CallArgList &Args) { if (!NeedsVTTParameter(GlobalDecl(D, Type))) return AddedStructorArgs{}; // Insert the implicit 'vtt' argument as the second argument. llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy)); return AddedStructorArgs::prefix(1); // Added one arg. } void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This) { GlobalDecl GD(DD, Type); llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); CGCallee Callee; if (getContext().getLangOpts().AppleKext && Type != Dtor_Base && DD->isVirtual()) Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); else Callee = CGCallee::forDirect( CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)), GD); CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This.getPointer(), VTT, VTTTy, nullptr, nullptr); } void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD) { llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); if (VTable->hasInitializer()) return; ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD)); // Create and set the initializer. ConstantInitBuilder Builder(CGM); auto Components = Builder.beginStruct(); CGVT.createVTableInitializer(Components, VTLayout, RTTI); Components.finishAndSetAsInitializer(VTable); // Set the correct linkage. VTable->setLinkage(Linkage); if (CGM.supportsCOMDAT() && VTable->isWeakForLinker()) VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName())); // Set the right visibility. CGM.setGVProperties(VTable, RD); // If this is the magic class __cxxabiv1::__fundamental_type_info, // we will emit the typeinfo for the fundamental types. This is the // same behaviour as GCC. const DeclContext *DC = RD->getDeclContext(); if (RD->getIdentifier() && RD->getIdentifier()->isStr("__fundamental_type_info") && isa(DC) && cast(DC)->getIdentifier() && cast(DC)->getIdentifier()->isStr("__cxxabiv1") && DC->getParent()->isTranslationUnit()) EmitFundamentalRTTIDescriptors(RD); if (!VTable->isDeclarationForLinker()) CGM.EmitVTableTypeMetadata(VTable, VTLayout); } bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField( CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) { if (Vptr.NearestVBase == nullptr) return false; return NeedsVTTParameter(CGF.CurGD); } llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, const CXXRecordDecl *NearestVBase) { if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && NeedsVTTParameter(CGF.CurGD)) { return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base, NearestVBase); } return getVTableAddressPoint(Base, VTableClass); } llvm::Constant * ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base, const CXXRecordDecl *VTableClass) { llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits()); // Find the appropriate vtable within the vtable group, and the address point // within that vtable. VTableLayout::AddressPointLocation AddressPoint = CGM.getItaniumVTableContext() .getVTableLayout(VTableClass) .getAddressPoint(Base); llvm::Value *Indices[] = { llvm::ConstantInt::get(CGM.Int32Ty, 0), llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex), llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex), }; return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable, Indices, /*InBounds=*/true, /*InRangeIndex=*/1); } llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT( CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, const CXXRecordDecl *NearestVBase) { assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT"); // Get the secondary vpointer index. uint64_t VirtualPointerIndex = CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); /// Load the VTT. llvm::Value *VTT = CGF.LoadCXXVTT(); if (VirtualPointerIndex) VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); // And load the address point from the VTT. return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign()); } llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( BaseSubobject Base, const CXXRecordDecl *VTableClass) { return getVTableAddressPoint(Base, VTableClass); } llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset) { assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); llvm::GlobalVariable *&VTable = VTables[RD]; if (VTable) return VTable; // Queue up this vtable for possible deferred emission. CGM.addDeferredVTable(RD); SmallString<256> Name; llvm::raw_svector_ostream Out(Name); getMangleContext().mangleCXXVTable(RD, Out); const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD); llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout); // Use pointer alignment for the vtable. Otherwise we would align them based // on the size of the initializer which doesn't make sense as only single // values are read. unsigned PAlign = CGM.getTarget().getPointerAlign(0); VTable = CGM.CreateOrReplaceCXXRuntimeVariable( Name, VTableType, llvm::GlobalValue::ExternalLinkage, getContext().toCharUnitsFromBits(PAlign).getQuantity()); VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); CGM.setGVProperties(VTable, RD); return VTable; } CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc) { Ty = Ty->getPointerTo()->getPointerTo(); auto *MethodDecl = cast(GD.getDecl()); llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent()); uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); llvm::Value *VFunc; if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) { VFunc = CGF.EmitVTableTypeCheckedLoad( MethodDecl->getParent(), VTable, VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8); } else { CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc); llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); auto *VFuncLoad = CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); // Add !invariant.load md to virtual function load to indicate that // function didn't change inside vtable. // It's safe to add it without -fstrict-vtable-pointers, but it would not // help in devirtualization because it will only matter if we will have 2 // the same virtual function loads from the same vtable load, which won't // happen without enabled devirtualization with -fstrict-vtable-pointers. if (CGM.getCodeGenOpts().OptimizationLevel > 0 && CGM.getCodeGenOpts().StrictVTablePointers) VFuncLoad->setMetadata( llvm::LLVMContext::MD_invariant_load, llvm::MDNode::get(CGM.getLLVMContext(), llvm::ArrayRef())); VFunc = VFuncLoad; } CGCallee Callee(GD, VFunc); return Callee; } llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall( CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, Address This, const CXXMemberCallExpr *CE) { assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( Dtor, getFromDtorType(DtorType)); llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); CGCallee Callee = CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty); CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This.getPointer(), /*ImplicitParam=*/nullptr, QualType(), CE, nullptr); return nullptr; } void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { CodeGenVTables &VTables = CGM.getVTables(); llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); } bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass( const CXXRecordDecl *RD) const { // We don't emit available_externally vtables if we are in -fapple-kext mode // because kext mode does not permit devirtualization. if (CGM.getLangOpts().AppleKext) return false; // If the vtable is hidden then it is not safe to emit an available_externally // copy of vtable. if (isVTableHidden(RD)) return false; if (CGM.getCodeGenOpts().ForceEmitVTables) return true; // If we don't have any not emitted inline virtual function then we are safe // to emit an available_externally copy of vtable. // FIXME we can still emit a copy of the vtable if we // can emit definition of the inline functions. if (hasAnyUnusedVirtualInlineFunction(RD)) return false; // For a class with virtual bases, we must also be able to speculatively // emit the VTT, because CodeGen doesn't have separate notions of "can emit // the vtable" and "can emit the VTT". For a base subobject, this means we // need to be able to emit non-virtual base vtables. if (RD->getNumVBases()) { for (const auto &B : RD->bases()) { auto *BRD = B.getType()->getAsCXXRecordDecl(); assert(BRD && "no class for base specifier"); if (B.isVirtual() || !BRD->isDynamicClass()) continue; if (!canSpeculativelyEmitVTableAsBaseClass(BRD)) return false; } } return true; } bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const { if (!canSpeculativelyEmitVTableAsBaseClass(RD)) return false; // For a complete-object vtable (or more specifically, for the VTT), we need // to be able to speculatively emit the vtables of all dynamic virtual bases. for (const auto &B : RD->vbases()) { auto *BRD = B.getType()->getAsCXXRecordDecl(); assert(BRD && "no class for base specifier"); if (!BRD->isDynamicClass()) continue; if (!canSpeculativelyEmitVTableAsBaseClass(BRD)) return false; } return true; } static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, Address InitialPtr, int64_t NonVirtualAdjustment, int64_t VirtualAdjustment, bool IsReturnAdjustment) { if (!NonVirtualAdjustment && !VirtualAdjustment) return InitialPtr.getPointer(); Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty); // In a base-to-derived cast, the non-virtual adjustment is applied first. if (NonVirtualAdjustment && !IsReturnAdjustment) { V = CGF.Builder.CreateConstInBoundsByteGEP(V, CharUnits::fromQuantity(NonVirtualAdjustment)); } // Perform the virtual adjustment if we have one. llvm::Value *ResultPtr; if (VirtualAdjustment) { llvm::Type *PtrDiffTy = CGF.ConvertType(CGF.getContext().getPointerDiffType()); Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy); llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); // Load the adjustment offset from the vtable. llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); // Adjust our pointer. ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset); } else { ResultPtr = V.getPointer(); } // In a derived-to-base conversion, the non-virtual adjustment is // applied second. if (NonVirtualAdjustment && IsReturnAdjustment) { ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr, NonVirtualAdjustment); } // Cast back to the original type. return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType()); } llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA) { return performTypeAdjustment(CGF, This, TA.NonVirtual, TA.Virtual.Itanium.VCallOffsetOffset, /*IsReturnAdjustment=*/false); } llvm::Value * ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA) { return performTypeAdjustment(CGF, Ret, RA.NonVirtual, RA.Virtual.Itanium.VBaseOffsetOffset, /*IsReturnAdjustment=*/true); } void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType) { if (!isa(CGF.CurGD.getDecl())) return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); // Destructor thunks in the ARM ABI have indeterminate results. llvm::Type *T = CGF.ReturnValue.getElementType(); RValue Undef = RValue::get(llvm::UndefValue::get(T)); return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); } /************************** Array allocation cookies **************************/ CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { // The array cookie is a size_t; pad that up to the element alignment. // The cookie is actually right-justified in that space. return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), CGM.getContext().getTypeAlignInChars(elementType)); } Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType) { assert(requiresArrayCookie(expr)); unsigned AS = NewPtr.getAddressSpace(); ASTContext &Ctx = getContext(); CharUnits SizeSize = CGF.getSizeSize(); // The size of the cookie. CharUnits CookieSize = std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); assert(CookieSize == getArrayCookieSizeImpl(ElementType)); // Compute an offset to the cookie. Address CookiePtr = NewPtr; CharUnits CookieOffset = CookieSize - SizeSize; if (!CookieOffset.isZero()) CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset); // Write the number of elements into the appropriate slot. Address NumElementsPtr = CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy); llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr); // Handle the array cookie specially in ASan. if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 && (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() || CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) { // The store to the CookiePtr does not need to be instrumented. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false); llvm::Constant *F = CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie"); CGF.Builder.CreateCall(F, NumElementsPtr.getPointer()); } // Finally, compute a pointer to the actual data buffer by skipping // over the cookie completely. return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize); } llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, CharUnits cookieSize) { // The element size is right-justified in the cookie. Address numElementsPtr = allocPtr; CharUnits numElementsOffset = cookieSize - CGF.getSizeSize(); if (!numElementsOffset.isZero()) numElementsPtr = CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset); unsigned AS = allocPtr.getAddressSpace(); numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0) return CGF.Builder.CreateLoad(numElementsPtr); // In asan mode emit a function call instead of a regular load and let the // run-time deal with it: if the shadow is properly poisoned return the // cookie, otherwise return 0 to avoid an infinite loop calling DTORs. // We can't simply ignore this load using nosanitize metadata because // the metadata may be lost. llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false); llvm::Constant *F = CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie"); return CGF.Builder.CreateCall(F, numElementsPtr.getPointer()); } CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { // ARM says that the cookie is always: // struct array_cookie { // std::size_t element_size; // element_size != 0 // std::size_t element_count; // }; // But the base ABI doesn't give anything an alignment greater than // 8, so we can dismiss this as typical ABI-author blindness to // actual language complexity and round up to the element alignment. return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), CGM.getContext().getTypeAlignInChars(elementType)); } Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, Address newPtr, llvm::Value *numElements, const CXXNewExpr *expr, QualType elementType) { assert(requiresArrayCookie(expr)); // The cookie is always at the start of the buffer. Address cookie = newPtr; // The first element is the element size. cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy); llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, getContext().getTypeSizeInChars(elementType).getQuantity()); CGF.Builder.CreateStore(elementSize, cookie); // The second element is the element count. cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize()); CGF.Builder.CreateStore(numElements, cookie); // Finally, compute a pointer to the actual data buffer by skipping // over the cookie completely. CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize); } llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, CharUnits cookieSize) { // The number of elements is at offset sizeof(size_t) relative to // the allocated pointer. Address numElementsPtr = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize()); numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); return CGF.Builder.CreateLoad(numElementsPtr); } /*********************** Static local initialization **************************/ static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy) { // int __cxa_guard_acquire(__guard *guard_object); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), GuardPtrTy, /*isVarArg=*/false); return CGM.CreateRuntimeFunction( FTy, "__cxa_guard_acquire", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NoUnwind)); } static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy) { // void __cxa_guard_release(__guard *guard_object); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); return CGM.CreateRuntimeFunction( FTy, "__cxa_guard_release", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NoUnwind)); } static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy) { // void __cxa_guard_abort(__guard *guard_object); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); return CGM.CreateRuntimeFunction( FTy, "__cxa_guard_abort", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NoUnwind)); } namespace { struct CallGuardAbort final : EHScopeStack::Cleanup { llvm::GlobalVariable *Guard; CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} void Emit(CodeGenFunction &CGF, Flags flags) override { CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard); } }; } /// The ARM code here follows the Itanium code closely enough that we /// just special-case it at particular places. void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, llvm::GlobalVariable *var, bool shouldPerformInit) { CGBuilderTy &Builder = CGF.Builder; // Inline variables that weren't instantiated from variable templates have // partially-ordered initialization within their translation unit. bool NonTemplateInline = D.isInline() && !isTemplateInstantiation(D.getTemplateSpecializationKind()); // We only need to use thread-safe statics for local non-TLS variables and // inline variables; other global initialization is always single-threaded // or (through lazy dynamic loading in multiple threads) unsequenced. bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && (D.isLocalVarDecl() || NonTemplateInline) && !D.getTLSKind(); // If we have a global variable with internal linkage and thread-safe statics // are disabled, we can just let the guard variable be of type i8. bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); llvm::IntegerType *guardTy; CharUnits guardAlignment; if (useInt8GuardVariable) { guardTy = CGF.Int8Ty; guardAlignment = CharUnits::One(); } else { // Guard variables are 64 bits in the generic ABI and size width on ARM // (i.e. 32-bit on AArch32, 64-bit on AArch64). if (UseARMGuardVarABI) { guardTy = CGF.SizeTy; guardAlignment = CGF.getSizeAlign(); } else { guardTy = CGF.Int64Ty; guardAlignment = CharUnits::fromQuantity( CGM.getDataLayout().getABITypeAlignment(guardTy)); } } llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); // Create the guard variable if we don't already have it (as we // might if we're double-emitting this function body). llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); if (!guard) { // Mangle the name for the guard. SmallString<256> guardName; { llvm::raw_svector_ostream out(guardName); getMangleContext().mangleStaticGuardVariable(&D, out); } // Create the guard variable with a zero-initializer. // Just absorb linkage and visibility from the guarded variable. guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, false, var->getLinkage(), llvm::ConstantInt::get(guardTy, 0), guardName.str()); guard->setDSOLocal(var->isDSOLocal()); guard->setVisibility(var->getVisibility()); // If the variable is thread-local, so is its guard variable. guard->setThreadLocalMode(var->getThreadLocalMode()); guard->setAlignment(guardAlignment.getQuantity()); // The ABI says: "It is suggested that it be emitted in the same COMDAT // group as the associated data object." In practice, this doesn't work for // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm. llvm::Comdat *C = var->getComdat(); if (!D.isLocalVarDecl() && C && (CGM.getTarget().getTriple().isOSBinFormatELF() || CGM.getTarget().getTriple().isOSBinFormatWasm())) { guard->setComdat(C); // An inline variable's guard function is run from the per-TU // initialization function, not via a dedicated global ctor function, so // we can't put it in a comdat. if (!NonTemplateInline) CGF.CurFn->setComdat(C); } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) { guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName())); } CGM.setStaticLocalDeclGuardAddress(&D, guard); } Address guardAddr = Address(guard, guardAlignment); // Test whether the variable has completed initialization. // // Itanium C++ ABI 3.3.2: // The following is pseudo-code showing how these functions can be used: // if (obj_guard.first_byte == 0) { // if ( __cxa_guard_acquire (&obj_guard) ) { // try { // ... initialize the object ...; // } catch (...) { // __cxa_guard_abort (&obj_guard); // throw; // } // ... queue object destructor with __cxa_atexit() ...; // __cxa_guard_release (&obj_guard); // } // } // Load the first byte of the guard variable. llvm::LoadInst *LI = Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty)); // Itanium ABI: // An implementation supporting thread-safety on multiprocessor // systems must also guarantee that references to the initialized // object do not occur before the load of the initialization flag. // // In LLVM, we do this by marking the load Acquire. if (threadsafe) LI->setAtomic(llvm::AtomicOrdering::Acquire); // For ARM, we should only check the first bit, rather than the entire byte: // // ARM C++ ABI 3.2.3.1: // To support the potential use of initialization guard variables // as semaphores that are the target of ARM SWP and LDREX/STREX // synchronizing instructions we define a static initialization // guard variable to be a 4-byte aligned, 4-byte word with the // following inline access protocol. // #define INITIALIZED 1 // if ((obj_guard & INITIALIZED) != INITIALIZED) { // if (__cxa_guard_acquire(&obj_guard)) // ... // } // // and similarly for ARM64: // // ARM64 C++ ABI 3.2.2: // This ABI instead only specifies the value bit 0 of the static guard // variable; all other bits are platform defined. Bit 0 shall be 0 when the // variable is not initialized and 1 when it is. llvm::Value *V = (UseARMGuardVarABI && !useInt8GuardVariable) ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1)) : LI; llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized"); llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); // Check if the first byte of the guard variable is zero. CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock, CodeGenFunction::GuardKind::VariableGuard, &D); CGF.EmitBlock(InitCheckBlock); // Variables used when coping with thread-safe statics and exceptions. if (threadsafe) { // Call __cxa_guard_acquire. llvm::Value *V = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), InitBlock, EndBlock); // Call __cxa_guard_abort along the exceptional edge. CGF.EHStack.pushCleanup(EHCleanup, guard); CGF.EmitBlock(InitBlock); } // Emit the initializer and add a global destructor if appropriate. CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); if (threadsafe) { // Pop the guard-abort cleanup if we pushed one. CGF.PopCleanupBlock(); // Call __cxa_guard_release. This cannot throw. CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guardAddr.getPointer()); } else { Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr); } CGF.EmitBlock(EndBlock); } /// Register a global destructor using __cxa_atexit. static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, llvm::Constant *dtor, llvm::Constant *addr, bool TLS) { const char *Name = "__cxa_atexit"; if (TLS) { const llvm::Triple &T = CGF.getTarget().getTriple(); Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit"; } // We're assuming that the destructor function is something we can // reasonably call with the default CC. Go ahead and cast it to the // right prototype. llvm::Type *dtorTy = llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; llvm::FunctionType *atexitTy = llvm::FunctionType::get(CGF.IntTy, paramTys, false); // Fetch the actual function. llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); if (llvm::Function *fn = dyn_cast(atexit)) fn->setDoesNotThrow(); // Create a variable that binds the atexit to this shared object. llvm::Constant *handle = CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); auto *GV = cast(handle->stripPointerCasts()); GV->setVisibility(llvm::GlobalValue::HiddenVisibility); if (!addr) // addr is null when we are trying to register a dtor annotated with // __attribute__((destructor)) in a constructor function. Using null here is // okay because this argument is just passed back to the destructor // function. addr = llvm::Constant::getNullValue(CGF.Int8PtrTy); llvm::Value *args[] = { llvm::ConstantExpr::getBitCast(dtor, dtorTy), llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), handle }; CGF.EmitNounwindRuntimeCall(atexit, args); } void CodeGenModule::registerGlobalDtorsWithAtExit() { for (const auto I : DtorsUsingAtExit) { int Priority = I.first; const llvm::TinyPtrVector &Dtors = I.second; // Create a function that registers destructors that have the same priority. // // Since constructor functions are run in non-descending order of their // priorities, destructors are registered in non-descending order of their // priorities, and since destructor functions are run in the reverse order // of their registration, destructor functions are run in non-ascending // order of their priorities. CodeGenFunction CGF(*this); std::string GlobalInitFnName = std::string("__GLOBAL_init_") + llvm::to_string(Priority); llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction( FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(), SourceLocation()); ASTContext &Ctx = getContext(); QualType ReturnTy = Ctx.VoidTy; QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {}); FunctionDecl *FD = FunctionDecl::Create( Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static, false, false); CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn, getTypes().arrangeNullaryFunction(), FunctionArgList(), SourceLocation(), SourceLocation()); for (auto *Dtor : Dtors) { // Register the destructor function calling __cxa_atexit if it is // available. Otherwise fall back on calling atexit. if (getCodeGenOpts().CXAAtExit) emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false); else CGF.registerGlobalDtorWithAtExit(Dtor); } CGF.FinishFunction(); AddGlobalCtor(GlobalInitFn, Priority, nullptr); } } /// Register a global destructor as best as we know how. void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *dtor, llvm::Constant *addr) { if (D.isNoDestroy(CGM.getContext())) return; // Use __cxa_atexit if available. if (CGM.getCodeGenOpts().CXAAtExit) return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); if (D.getTLSKind()) CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); // In Apple kexts, we want to add a global destructor entry. // FIXME: shouldn't this be guarded by some variable? if (CGM.getLangOpts().AppleKext) { // Generate a global destructor entry. return CGM.AddCXXDtorEntry(dtor, addr); } CGF.registerGlobalDtorWithAtExit(D, dtor, addr); } static bool isThreadWrapperReplaceable(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!"); // Darwin prefers to have references to thread local variables to go through // the thread wrapper instead of directly referencing the backing variable. return VD->getTLSKind() == VarDecl::TLS_Dynamic && CGM.getTarget().getTriple().isOSDarwin(); } /// Get the appropriate linkage for the wrapper function. This is essentially /// the weak form of the variable's linkage; every translation unit which needs /// the wrapper emits a copy, and we want the linker to merge them. static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { llvm::GlobalValue::LinkageTypes VarLinkage = CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false); // For internal linkage variables, we don't need an external or weak wrapper. if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) return VarLinkage; // If the thread wrapper is replaceable, give it appropriate linkage. if (isThreadWrapperReplaceable(VD, CGM)) if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) && !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)) return VarLinkage; return llvm::GlobalValue::WeakODRLinkage; } llvm::Function * ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, llvm::Value *Val) { // Mangle the name for the thread_local wrapper function. SmallString<256> WrapperName; { llvm::raw_svector_ostream Out(WrapperName); getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); } // FIXME: If VD is a definition, we should regenerate the function attributes // before returning. if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName)) return cast(V); QualType RetQT = VD->getType(); if (RetQT->isReferenceType()) RetQT = RetQT.getNonReferenceType(); const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( getContext().getPointerType(RetQT), FunctionArgList()); llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI); llvm::Function *Wrapper = llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM), WrapperName.str(), &CGM.getModule()); CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper); if (VD->hasDefinition()) CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper); // Always resolve references to the wrapper at link time. - if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) && - !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) && - !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()))) - Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); + if (!Wrapper->hasLocalLinkage()) + if (!isThreadWrapperReplaceable(VD, CGM) || + llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) || + llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) || + VD->getVisibility() == HiddenVisibility) + Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); if (isThreadWrapperReplaceable(VD, CGM)) { Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); Wrapper->addFnAttr(llvm::Attribute::NoUnwind); } return Wrapper; } void ItaniumCXXABI::EmitThreadLocalInitFuncs( CodeGenModule &CGM, ArrayRef CXXThreadLocals, ArrayRef CXXThreadLocalInits, ArrayRef CXXThreadLocalInitVars) { llvm::Function *InitFunc = nullptr; // Separate initializers into those with ordered (or partially-ordered) // initialization and those with unordered initialization. llvm::SmallVector OrderedInits; llvm::SmallDenseMap UnorderedInits; for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) { if (isTemplateInstantiation( CXXThreadLocalInitVars[I]->getTemplateSpecializationKind())) UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] = CXXThreadLocalInits[I]; else OrderedInits.push_back(CXXThreadLocalInits[I]); } if (!OrderedInits.empty()) { // Generate a guarded initialization function. llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI, SourceLocation(), /*TLS=*/true); llvm::GlobalVariable *Guard = new llvm::GlobalVariable( CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false, llvm::GlobalVariable::InternalLinkage, llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard"); Guard->setThreadLocal(true); CharUnits GuardAlign = CharUnits::One(); Guard->setAlignment(GuardAlign.getQuantity()); CodeGenFunction(CGM).GenerateCXXGlobalInitFunc( InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign)); // On Darwin platforms, use CXX_FAST_TLS calling convention. if (CGM.getTarget().getTriple().isOSDarwin()) { InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); InitFunc->addFnAttr(llvm::Attribute::NoUnwind); } } // Emit thread wrappers. for (const VarDecl *VD : CXXThreadLocals) { llvm::GlobalVariable *Var = cast(CGM.GetGlobalValue(CGM.getMangledName(VD))); llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); // Some targets require that all access to thread local variables go through // the thread wrapper. This means that we cannot attempt to create a thread // wrapper or a thread helper. if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) { Wrapper->setLinkage(llvm::Function::ExternalLinkage); continue; } // Mangle the name for the thread_local initialization function. SmallString<256> InitFnName; { llvm::raw_svector_ostream Out(InitFnName); getMangleContext().mangleItaniumThreadLocalInit(VD, Out); } // If we have a definition for the variable, emit the initialization // function as an alias to the global Init function (if any). Otherwise, // produce a declaration of the initialization function. llvm::GlobalValue *Init = nullptr; bool InitIsInitFunc = false; if (VD->hasDefinition()) { InitIsInitFunc = true; llvm::Function *InitFuncToUse = InitFunc; if (isTemplateInstantiation(VD->getTemplateSpecializationKind())) InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl()); if (InitFuncToUse) Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(), InitFuncToUse); } else { // Emit a weak global function referring to the initialization function. // This function will not exist if the TU defining the thread_local // variable in question does not need any dynamic initialization for // its thread_local variables. llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); Init = llvm::Function::Create(FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(), &CGM.getModule()); const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, cast(Init)); } if (Init) { Init->setVisibility(Var->getVisibility()); Init->setDSOLocal(Var->isDSOLocal()); } llvm::LLVMContext &Context = CGM.getModule().getContext(); llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); CGBuilderTy Builder(CGM, Entry); if (InitIsInitFunc) { if (Init) { llvm::CallInst *CallVal = Builder.CreateCall(Init); if (isThreadWrapperReplaceable(VD, CGM)) { CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); llvm::Function *Fn = cast(cast(Init)->getAliasee()); Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); } } } else { // Don't know whether we have an init function. Call it if it exists. llvm::Value *Have = Builder.CreateIsNotNull(Init); llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); Builder.CreateCondBr(Have, InitBB, ExitBB); Builder.SetInsertPoint(InitBB); Builder.CreateCall(Init); Builder.CreateBr(ExitBB); Builder.SetInsertPoint(ExitBB); } // For a reference, the result of the wrapper function is a pointer to // the referenced object. llvm::Value *Val = Var; if (VD->getType()->isReferenceType()) { CharUnits Align = CGM.getContext().getDeclAlign(VD); Val = Builder.CreateAlignedLoad(Val, Align); } if (Val->getType() != Wrapper->getReturnType()) Val = Builder.CreatePointerBitCastOrAddrSpaceCast( Val, Wrapper->getReturnType(), ""); Builder.CreateRet(Val); } } LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType) { llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD); llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper); CallVal->setCallingConv(Wrapper->getCallingConv()); LValue LV; if (VD->getType()->isReferenceType()) LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType); else LV = CGF.MakeAddrLValue(CallVal, LValType, CGF.getContext().getDeclAlign(VD)); // FIXME: need setObjCGCLValueClass? return LV; } /// Return whether the given global decl needs a VTT parameter, which it does /// if it's a base constructor or destructor with virtual bases. bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { const CXXMethodDecl *MD = cast(GD.getDecl()); // We don't have any virtual bases, just return early. if (!MD->getParent()->getNumVBases()) return false; // Check if we have a base constructor. if (isa(MD) && GD.getCtorType() == Ctor_Base) return true; // Check if we have a base destructor. if (isa(MD) && GD.getDtorType() == Dtor_Base) return true; return false; } namespace { class ItaniumRTTIBuilder { CodeGenModule &CGM; // Per-module state. llvm::LLVMContext &VMContext; const ItaniumCXXABI &CXXABI; // Per-module state. /// Fields - The fields of the RTTI descriptor currently being built. SmallVector Fields; /// GetAddrOfTypeName - Returns the mangled type name of the given type. llvm::GlobalVariable * GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI /// descriptor of the given type. llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); /// BuildVTablePointer - Build the vtable pointer for the given type. void BuildVTablePointer(const Type *Ty); /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. void BuildSIClassTypeInfo(const CXXRecordDecl *RD); /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for /// classes with bases that do not satisfy the abi::__si_class_type_info /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used /// for pointer types. void BuildPointerTypeInfo(QualType PointeeTy); /// BuildObjCObjectTypeInfo - Build the appropriate kind of /// type_info for an object type. void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info /// struct, used for member pointer types. void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); public: ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} // Pointer type info flags. enum { /// PTI_Const - Type has const qualifier. PTI_Const = 0x1, /// PTI_Volatile - Type has volatile qualifier. PTI_Volatile = 0x2, /// PTI_Restrict - Type has restrict qualifier. PTI_Restrict = 0x4, /// PTI_Incomplete - Type is incomplete. PTI_Incomplete = 0x8, /// PTI_ContainingClassIncomplete - Containing class is incomplete. /// (in pointer to member). PTI_ContainingClassIncomplete = 0x10, /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS). //PTI_TransactionSafe = 0x20, /// PTI_Noexcept - Pointee is noexcept function (C++1z). PTI_Noexcept = 0x40, }; // VMI type info flags. enum { /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. VMI_NonDiamondRepeat = 0x1, /// VMI_DiamondShaped - Class is diamond shaped. VMI_DiamondShaped = 0x2 }; // Base class type info flags. enum { /// BCTI_Virtual - Base class is virtual. BCTI_Virtual = 0x1, /// BCTI_Public - Base class is public. BCTI_Public = 0x2 }; /// BuildTypeInfo - Build the RTTI type info struct for the given type, or /// link to an existing RTTI descriptor if one already exists. llvm::Constant *BuildTypeInfo(QualType Ty); /// BuildTypeInfo - Build the RTTI type info struct for the given type. llvm::Constant *BuildTypeInfo( QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage, llvm::GlobalValue::VisibilityTypes Visibility, llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass); }; } llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { SmallString<256> Name; llvm::raw_svector_ostream Out(Name); CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); // We know that the mangled name of the type starts at index 4 of the // mangled name of the typename, so we can just index into it in order to // get the mangled name of the type. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, Name.substr(4)); auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy); llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable( Name, Init->getType(), Linkage, Align.getQuantity()); GV->setInitializer(Init); return GV; } llvm::Constant * ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { // Mangle the RTTI name. SmallString<256> Name; llvm::raw_svector_ostream Out(Name); CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); // Look for an existing global. llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); if (!GV) { // Create a new global variable. // Note for the future: If we would ever like to do deferred emission of // RTTI, check if emitting vtables opportunistically need any adjustment. GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, /*Constant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, Name); const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); CGM.setGVProperties(GV, RD); } return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); } /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type /// info for that type is defined in the standard library. static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { // Itanium C++ ABI 2.9.2: // Basic type information (e.g. for "int", "bool", etc.) will be kept in // the run-time support library. Specifically, the run-time support // library should contain type_info objects for the types X, X* and // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, // unsigned char, signed char, short, unsigned short, int, unsigned int, // long, unsigned long, long long, unsigned long long, float, double, // long double, char16_t, char32_t, and the IEEE 754r decimal and // half-precision floating point types. // // GCC also emits RTTI for __int128. // FIXME: We do not emit RTTI information for decimal types here. // Types added here must also be added to EmitFundamentalRTTIDescriptors. switch (Ty->getKind()) { case BuiltinType::Void: case BuiltinType::NullPtr: case BuiltinType::Bool: case BuiltinType::WChar_S: case BuiltinType::WChar_U: case BuiltinType::Char_U: case BuiltinType::Char_S: case BuiltinType::UChar: case BuiltinType::SChar: case BuiltinType::Short: case BuiltinType::UShort: case BuiltinType::Int: case BuiltinType::UInt: case BuiltinType::Long: case BuiltinType::ULong: case BuiltinType::LongLong: case BuiltinType::ULongLong: case BuiltinType::Half: case BuiltinType::Float: case BuiltinType::Double: case BuiltinType::LongDouble: case BuiltinType::Float16: case BuiltinType::Float128: case BuiltinType::Char8: case BuiltinType::Char16: case BuiltinType::Char32: case BuiltinType::Int128: case BuiltinType::UInt128: return true; #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" case BuiltinType::OCLSampler: case BuiltinType::OCLEvent: case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLReserveID: case BuiltinType::ShortAccum: case BuiltinType::Accum: case BuiltinType::LongAccum: case BuiltinType::UShortAccum: case BuiltinType::UAccum: case BuiltinType::ULongAccum: case BuiltinType::ShortFract: case BuiltinType::Fract: case BuiltinType::LongFract: case BuiltinType::UShortFract: case BuiltinType::UFract: case BuiltinType::ULongFract: case BuiltinType::SatShortAccum: case BuiltinType::SatAccum: case BuiltinType::SatLongAccum: case BuiltinType::SatUShortAccum: case BuiltinType::SatUAccum: case BuiltinType::SatULongAccum: case BuiltinType::SatShortFract: case BuiltinType::SatFract: case BuiltinType::SatLongFract: case BuiltinType::SatUShortFract: case BuiltinType::SatUFract: case BuiltinType::SatULongFract: return false; case BuiltinType::Dependent: #define BUILTIN_TYPE(Id, SingletonId) #define PLACEHOLDER_TYPE(Id, SingletonId) \ case BuiltinType::Id: #include "clang/AST/BuiltinTypes.def" llvm_unreachable("asking for RRTI for a placeholder type!"); case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: llvm_unreachable("FIXME: Objective-C types are unsupported!"); } llvm_unreachable("Invalid BuiltinType Kind!"); } static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { QualType PointeeTy = PointerTy->getPointeeType(); const BuiltinType *BuiltinTy = dyn_cast(PointeeTy); if (!BuiltinTy) return false; // Check the qualifiers. Qualifiers Quals = PointeeTy.getQualifiers(); Quals.removeConst(); if (!Quals.empty()) return false; return TypeInfoIsInStandardLibrary(BuiltinTy); } /// IsStandardLibraryRTTIDescriptor - Returns whether the type /// information for the given type exists in the standard library. static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { // Type info for builtin types is defined in the standard library. if (const BuiltinType *BuiltinTy = dyn_cast(Ty)) return TypeInfoIsInStandardLibrary(BuiltinTy); // Type info for some pointer types to builtin types is defined in the // standard library. if (const PointerType *PointerTy = dyn_cast(Ty)) return TypeInfoIsInStandardLibrary(PointerTy); return false; } /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for /// the given type exists somewhere else, and that we should not emit the type /// information in this translation unit. Assumes that it is not a /// standard-library type. static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) { ASTContext &Context = CGM.getContext(); // If RTTI is disabled, assume it might be disabled in the // translation unit that defines any potential key function, too. if (!Context.getLangOpts().RTTI) return false; if (const RecordType *RecordTy = dyn_cast(Ty)) { const CXXRecordDecl *RD = cast(RecordTy->getDecl()); if (!RD->hasDefinition()) return false; if (!RD->isDynamicClass()) return false; // FIXME: this may need to be reconsidered if the key function // changes. // N.B. We must always emit the RTTI data ourselves if there exists a key // function. bool IsDLLImport = RD->hasAttr(); // Don't import the RTTI but emit it locally. if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport) return false; if (CGM.getVTables().isVTableExternal(RD)) return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment() ? false : true; if (IsDLLImport) return true; } return false; } /// IsIncompleteClassType - Returns whether the given record type is incomplete. static bool IsIncompleteClassType(const RecordType *RecordTy) { return !RecordTy->getDecl()->isCompleteDefinition(); } /// ContainsIncompleteClassType - Returns whether the given type contains an /// incomplete class type. This is true if /// /// * The given type is an incomplete class type. /// * The given type is a pointer type whose pointee type contains an /// incomplete class type. /// * The given type is a member pointer type whose class is an incomplete /// class type. /// * The given type is a member pointer type whoise pointee type contains an /// incomplete class type. /// is an indirect or direct pointer to an incomplete class type. static bool ContainsIncompleteClassType(QualType Ty) { if (const RecordType *RecordTy = dyn_cast(Ty)) { if (IsIncompleteClassType(RecordTy)) return true; } if (const PointerType *PointerTy = dyn_cast(Ty)) return ContainsIncompleteClassType(PointerTy->getPointeeType()); if (const MemberPointerType *MemberPointerTy = dyn_cast(Ty)) { // Check if the class type is incomplete. const RecordType *ClassType = cast(MemberPointerTy->getClass()); if (IsIncompleteClassType(ClassType)) return true; return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); } return false; } // CanUseSingleInheritance - Return whether the given record decl has a "single, // public, non-virtual base at offset zero (i.e. the derived class is dynamic // iff the base is)", according to Itanium C++ ABI, 2.95p6b. static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { // Check the number of bases. if (RD->getNumBases() != 1) return false; // Get the base. CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); // Check that the base is not virtual. if (Base->isVirtual()) return false; // Check that the base is public. if (Base->getAccessSpecifier() != AS_public) return false; // Check that the class is dynamic iff the base is. const CXXRecordDecl *BaseDecl = cast(Base->getType()->getAs()->getDecl()); if (!BaseDecl->isEmpty() && BaseDecl->isDynamicClass() != RD->isDynamicClass()) return false; return true; } void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { // abi::__class_type_info. static const char * const ClassTypeInfo = "_ZTVN10__cxxabiv117__class_type_infoE"; // abi::__si_class_type_info. static const char * const SIClassTypeInfo = "_ZTVN10__cxxabiv120__si_class_type_infoE"; // abi::__vmi_class_type_info. static const char * const VMIClassTypeInfo = "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; const char *VTableName = nullptr; switch (Ty->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.def" llvm_unreachable("Non-canonical and dependent types shouldn't get here"); case Type::LValueReference: case Type::RValueReference: llvm_unreachable("References shouldn't get here"); case Type::Auto: case Type::DeducedTemplateSpecialization: llvm_unreachable("Undeduced type shouldn't get here"); case Type::Pipe: llvm_unreachable("Pipe types shouldn't get here"); case Type::Builtin: // GCC treats vector and complex types as fundamental types. case Type::Vector: case Type::ExtVector: case Type::Complex: case Type::Atomic: // FIXME: GCC treats block pointers as fundamental types?! case Type::BlockPointer: // abi::__fundamental_type_info. VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; break; case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: // abi::__array_type_info. VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; break; case Type::FunctionNoProto: case Type::FunctionProto: // abi::__function_type_info. VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; break; case Type::Enum: // abi::__enum_type_info. VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; break; case Type::Record: { const CXXRecordDecl *RD = cast(cast(Ty)->getDecl()); if (!RD->hasDefinition() || !RD->getNumBases()) { VTableName = ClassTypeInfo; } else if (CanUseSingleInheritance(RD)) { VTableName = SIClassTypeInfo; } else { VTableName = VMIClassTypeInfo; } break; } case Type::ObjCObject: // Ignore protocol qualifiers. Ty = cast(Ty)->getBaseType().getTypePtr(); // Handle id and Class. if (isa(Ty)) { VTableName = ClassTypeInfo; break; } assert(isa(Ty)); LLVM_FALLTHROUGH; case Type::ObjCInterface: if (cast(Ty)->getDecl()->getSuperClass()) { VTableName = SIClassTypeInfo; } else { VTableName = ClassTypeInfo; } break; case Type::ObjCObjectPointer: case Type::Pointer: // abi::__pointer_type_info. VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; break; case Type::MemberPointer: // abi::__pointer_to_member_type_info. VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; break; } llvm::Constant *VTable = CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); CGM.setDSOLocal(cast(VTable->stripPointerCasts())); llvm::Type *PtrDiffTy = CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); // The vtable address point is 2. llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two); VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); Fields.push_back(VTable); } /// Return the linkage that the type info and type info name constants /// should have for the given type. static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) { // Itanium C++ ABI 2.9.5p7: // In addition, it and all of the intermediate abi::__pointer_type_info // structs in the chain down to the abi::__class_type_info for the // incomplete class type must be prevented from resolving to the // corresponding type_info structs for the complete class type, possibly // by making them local static objects. Finally, a dummy class RTTI is // generated for the incomplete type that will not resolve to the final // complete class RTTI (because the latter need not exist), possibly by // making it a local static object. if (ContainsIncompleteClassType(Ty)) return llvm::GlobalValue::InternalLinkage; switch (Ty->getLinkage()) { case NoLinkage: case InternalLinkage: case UniqueExternalLinkage: return llvm::GlobalValue::InternalLinkage; case VisibleNoLinkage: case ModuleInternalLinkage: case ModuleLinkage: case ExternalLinkage: // RTTI is not enabled, which means that this type info struct is going // to be used for exception handling. Give it linkonce_odr linkage. if (!CGM.getLangOpts().RTTI) return llvm::GlobalValue::LinkOnceODRLinkage; if (const RecordType *Record = dyn_cast(Ty)) { const CXXRecordDecl *RD = cast(Record->getDecl()); if (RD->hasAttr()) return llvm::GlobalValue::WeakODRLinkage; if (CGM.getTriple().isWindowsItaniumEnvironment()) if (RD->hasAttr() && ShouldUseExternalRTTIDescriptor(CGM, Ty)) return llvm::GlobalValue::ExternalLinkage; // MinGW always uses LinkOnceODRLinkage for type info. if (RD->isDynamicClass() && !CGM.getContext() .getTargetInfo() .getTriple() .isWindowsGNUEnvironment()) return CGM.getVTableLinkage(RD); } return llvm::GlobalValue::LinkOnceODRLinkage; } llvm_unreachable("Invalid linkage!"); } llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) { // We want to operate on the canonical type. Ty = Ty.getCanonicalType(); // Check if we've already emitted an RTTI descriptor for this type. SmallString<256> Name; llvm::raw_svector_ostream Out(Name); CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); if (OldGV && !OldGV->isDeclaration()) { assert(!OldGV->hasAvailableExternallyLinkage() && "available_externally typeinfos not yet implemented"); return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); } // Check if there is already an external RTTI descriptor for this type. if (IsStandardLibraryRTTIDescriptor(Ty) || ShouldUseExternalRTTIDescriptor(CGM, Ty)) return GetAddrOfExternalRTTIDescriptor(Ty); // Emit the standard library with external linkage. llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty); // Give the type_info object and name the formal visibility of the // type itself. llvm::GlobalValue::VisibilityTypes llvmVisibility; if (llvm::GlobalValue::isLocalLinkage(Linkage)) // If the linkage is local, only default visibility makes sense. llvmVisibility = llvm::GlobalValue::DefaultVisibility; else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) == ItaniumCXXABI::RUK_NonUniqueHidden) llvmVisibility = llvm::GlobalValue::HiddenVisibility; else llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass = llvm::GlobalValue::DefaultStorageClass; if (CGM.getTriple().isWindowsItaniumEnvironment()) { auto RD = Ty->getAsCXXRecordDecl(); if (RD && RD->hasAttr()) DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass; } return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass); } llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo( QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage, llvm::GlobalValue::VisibilityTypes Visibility, llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) { // Add the vtable pointer. BuildVTablePointer(cast(Ty)); // And the name. llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage); llvm::Constant *TypeNameField; // If we're supposed to demote the visibility, be sure to set a flag // to use a string comparison for type_info comparisons. ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = CXXABI.classifyRTTIUniqueness(Ty, Linkage); if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { // The flag is the sign bit, which on ARM64 is defined to be clear // for global pointers. This is very ARM64-specific. TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); llvm::Constant *flag = llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); TypeNameField = llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); } else { TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); } Fields.push_back(TypeNameField); switch (Ty->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.def" llvm_unreachable("Non-canonical and dependent types shouldn't get here"); // GCC treats vector types as fundamental types. case Type::Builtin: case Type::Vector: case Type::ExtVector: case Type::Complex: case Type::BlockPointer: // Itanium C++ ABI 2.9.5p4: // abi::__fundamental_type_info adds no data members to std::type_info. break; case Type::LValueReference: case Type::RValueReference: llvm_unreachable("References shouldn't get here"); case Type::Auto: case Type::DeducedTemplateSpecialization: llvm_unreachable("Undeduced type shouldn't get here"); case Type::Pipe: llvm_unreachable("Pipe type shouldn't get here"); case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: // Itanium C++ ABI 2.9.5p5: // abi::__array_type_info adds no data members to std::type_info. break; case Type::FunctionNoProto: case Type::FunctionProto: // Itanium C++ ABI 2.9.5p5: // abi::__function_type_info adds no data members to std::type_info. break; case Type::Enum: // Itanium C++ ABI 2.9.5p5: // abi::__enum_type_info adds no data members to std::type_info. break; case Type::Record: { const CXXRecordDecl *RD = cast(cast(Ty)->getDecl()); if (!RD->hasDefinition() || !RD->getNumBases()) { // We don't need to emit any fields. break; } if (CanUseSingleInheritance(RD)) BuildSIClassTypeInfo(RD); else BuildVMIClassTypeInfo(RD); break; } case Type::ObjCObject: case Type::ObjCInterface: BuildObjCObjectTypeInfo(cast(Ty)); break; case Type::ObjCObjectPointer: BuildPointerTypeInfo(cast(Ty)->getPointeeType()); break; case Type::Pointer: BuildPointerTypeInfo(cast(Ty)->getPointeeType()); break; case Type::MemberPointer: BuildPointerToMemberTypeInfo(cast(Ty)); break; case Type::Atomic: // No fields, at least for the moment. break; } llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); SmallString<256> Name; llvm::raw_svector_ostream Out(Name); CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); llvm::Module &M = CGM.getModule(); llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name); llvm::GlobalVariable *GV = new llvm::GlobalVariable(M, Init->getType(), /*Constant=*/true, Linkage, Init, Name); // If there's already an old global variable, replace it with the new one. if (OldGV) { GV->takeName(OldGV); llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); OldGV->replaceAllUsesWith(NewPtr); OldGV->eraseFromParent(); } if (CGM.supportsCOMDAT() && GV->isWeakForLinker()) GV->setComdat(M.getOrInsertComdat(GV->getName())); CharUnits Align = CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0)); GV->setAlignment(Align.getQuantity()); // The Itanium ABI specifies that type_info objects must be globally // unique, with one exception: if the type is an incomplete class // type or a (possibly indirect) pointer to one. That exception // affects the general case of comparing type_info objects produced // by the typeid operator, which is why the comparison operators on // std::type_info generally use the type_info name pointers instead // of the object addresses. However, the language's built-in uses // of RTTI generally require class types to be complete, even when // manipulating pointers to those class types. This allows the // implementation of dynamic_cast to rely on address equality tests, // which is much faster. // All of this is to say that it's important that both the type_info // object and the type_info name be uniqued when weakly emitted. TypeName->setVisibility(Visibility); CGM.setDSOLocal(TypeName); GV->setVisibility(Visibility); CGM.setDSOLocal(GV); TypeName->setDLLStorageClass(DLLStorageClass); GV->setDLLStorageClass(DLLStorageClass); return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); } /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info /// for the given Objective-C object type. void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { // Drop qualifiers. const Type *T = OT->getBaseType().getTypePtr(); assert(isa(T) || isa(T)); // The builtin types are abi::__class_type_infos and don't require // extra fields. if (isa(T)) return; ObjCInterfaceDecl *Class = cast(T)->getDecl(); ObjCInterfaceDecl *Super = Class->getSuperClass(); // Root classes are also __class_type_info. if (!Super) return; QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); // Everything else is single inheritance. llvm::Constant *BaseTypeInfo = ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); Fields.push_back(BaseTypeInfo); } /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single /// inheritance, according to the Itanium C++ ABI, 2.95p6b. void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { // Itanium C++ ABI 2.9.5p6b: // It adds to abi::__class_type_info a single member pointing to the // type_info structure for the base type, llvm::Constant *BaseTypeInfo = ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); Fields.push_back(BaseTypeInfo); } namespace { /// SeenBases - Contains virtual and non-virtual bases seen when traversing /// a class hierarchy. struct SeenBases { llvm::SmallPtrSet NonVirtualBases; llvm::SmallPtrSet VirtualBases; }; } /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in /// abi::__vmi_class_type_info. /// static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, SeenBases &Bases) { unsigned Flags = 0; const CXXRecordDecl *BaseDecl = cast(Base->getType()->getAs()->getDecl()); if (Base->isVirtual()) { // Mark the virtual base as seen. if (!Bases.VirtualBases.insert(BaseDecl).second) { // If this virtual base has been seen before, then the class is diamond // shaped. Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; } else { if (Bases.NonVirtualBases.count(BaseDecl)) Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; } } else { // Mark the non-virtual base as seen. if (!Bases.NonVirtualBases.insert(BaseDecl).second) { // If this non-virtual base has been seen before, then the class has non- // diamond shaped repeated inheritance. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; } else { if (Bases.VirtualBases.count(BaseDecl)) Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; } } // Walk all bases. for (const auto &I : BaseDecl->bases()) Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); return Flags; } static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { unsigned Flags = 0; SeenBases Bases; // Walk all bases. for (const auto &I : RD->bases()) Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); return Flags; } /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for /// classes with bases that do not satisfy the abi::__si_class_type_info /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { llvm::Type *UnsignedIntLTy = CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); // Itanium C++ ABI 2.9.5p6c: // __flags is a word with flags describing details about the class // structure, which may be referenced by using the __flags_masks // enumeration. These flags refer to both direct and indirect bases. unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); // Itanium C++ ABI 2.9.5p6c: // __base_count is a word with the number of direct proper base class // descriptions that follow. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); if (!RD->getNumBases()) return; // Now add the base class descriptions. // Itanium C++ ABI 2.9.5p6c: // __base_info[] is an array of base class descriptions -- one for every // direct proper base. Each description is of the type: // // struct abi::__base_class_type_info { // public: // const __class_type_info *__base_type; // long __offset_flags; // // enum __offset_flags_masks { // __virtual_mask = 0x1, // __public_mask = 0x2, // __offset_shift = 8 // }; // }; // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on // LLP64 platforms. // FIXME: Consider updating libc++abi to match, and extend this logic to all // LLP64 platforms. QualType OffsetFlagsTy = CGM.getContext().LongTy; const TargetInfo &TI = CGM.getContext().getTargetInfo(); if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth()) OffsetFlagsTy = CGM.getContext().LongLongTy; llvm::Type *OffsetFlagsLTy = CGM.getTypes().ConvertType(OffsetFlagsTy); for (const auto &Base : RD->bases()) { // The __base_type member points to the RTTI for the base type. Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); const CXXRecordDecl *BaseDecl = cast(Base.getType()->getAs()->getDecl()); int64_t OffsetFlags = 0; // All but the lower 8 bits of __offset_flags are a signed offset. // For a non-virtual base, this is the offset in the object of the base // subobject. For a virtual base, this is the offset in the virtual table of // the virtual base offset for the virtual base referenced (negative). CharUnits Offset; if (Base.isVirtual()) Offset = CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); else { const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); Offset = Layout.getBaseClassOffset(BaseDecl); }; OffsetFlags = uint64_t(Offset.getQuantity()) << 8; // The low-order byte of __offset_flags contains flags, as given by the // masks from the enumeration __offset_flags_masks. if (Base.isVirtual()) OffsetFlags |= BCTI_Virtual; if (Base.getAccessSpecifier() == AS_public) OffsetFlags |= BCTI_Public; Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags)); } } /// Compute the flags for a __pbase_type_info, and remove the corresponding /// pieces from \p Type. static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) { unsigned Flags = 0; if (Type.isConstQualified()) Flags |= ItaniumRTTIBuilder::PTI_Const; if (Type.isVolatileQualified()) Flags |= ItaniumRTTIBuilder::PTI_Volatile; if (Type.isRestrictQualified()) Flags |= ItaniumRTTIBuilder::PTI_Restrict; Type = Type.getUnqualifiedType(); // Itanium C++ ABI 2.9.5p7: // When the abi::__pbase_type_info is for a direct or indirect pointer to an // incomplete class type, the incomplete target type flag is set. if (ContainsIncompleteClassType(Type)) Flags |= ItaniumRTTIBuilder::PTI_Incomplete; if (auto *Proto = Type->getAs()) { if (Proto->isNothrow()) { Flags |= ItaniumRTTIBuilder::PTI_Noexcept; Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None); } } return Flags; } /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, /// used for pointer types. void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { // Itanium C++ ABI 2.9.5p7: // __flags is a flag word describing the cv-qualification and other // attributes of the type pointed to unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); llvm::Type *UnsignedIntLTy = CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); // Itanium C++ ABI 2.9.5p7: // __pointee is a pointer to the std::type_info derivation for the // unqualified type being pointed to. llvm::Constant *PointeeTypeInfo = ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); Fields.push_back(PointeeTypeInfo); } /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info /// struct, used for member pointer types. void ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { QualType PointeeTy = Ty->getPointeeType(); // Itanium C++ ABI 2.9.5p7: // __flags is a flag word describing the cv-qualification and other // attributes of the type pointed to. unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); const RecordType *ClassType = cast(Ty->getClass()); if (IsIncompleteClassType(ClassType)) Flags |= PTI_ContainingClassIncomplete; llvm::Type *UnsignedIntLTy = CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); // Itanium C++ ABI 2.9.5p7: // __pointee is a pointer to the std::type_info derivation for the // unqualified type being pointed to. llvm::Constant *PointeeTypeInfo = ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); Fields.push_back(PointeeTypeInfo); // Itanium C++ ABI 2.9.5p9: // __context is a pointer to an abi::__class_type_info corresponding to the // class type containing the member pointed to // (e.g., the "A" in "int A::*"). Fields.push_back( ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); } llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); } void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) { // Types added here must also be added to TypeInfoIsInStandardLibrary. QualType FundamentalTypes[] = { getContext().VoidTy, getContext().NullPtrTy, getContext().BoolTy, getContext().WCharTy, getContext().CharTy, getContext().UnsignedCharTy, getContext().SignedCharTy, getContext().ShortTy, getContext().UnsignedShortTy, getContext().IntTy, getContext().UnsignedIntTy, getContext().LongTy, getContext().UnsignedLongTy, getContext().LongLongTy, getContext().UnsignedLongLongTy, getContext().Int128Ty, getContext().UnsignedInt128Ty, getContext().HalfTy, getContext().FloatTy, getContext().DoubleTy, getContext().LongDoubleTy, getContext().Float128Ty, getContext().Char8Ty, getContext().Char16Ty, getContext().Char32Ty }; llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass = RD->hasAttr() ? llvm::GlobalValue::DLLExportStorageClass : llvm::GlobalValue::DefaultStorageClass; llvm::GlobalValue::VisibilityTypes Visibility = CodeGenModule::GetLLVMVisibility(RD->getVisibility()); for (const QualType &FundamentalType : FundamentalTypes) { QualType PointerType = getContext().getPointerType(FundamentalType); QualType PointerTypeConst = getContext().getPointerType( FundamentalType.withConst()); for (QualType Type : {FundamentalType, PointerType, PointerTypeConst}) ItaniumRTTIBuilder(*this).BuildTypeInfo( Type, llvm::GlobalValue::ExternalLinkage, Visibility, DLLStorageClass); } } /// What sort of uniqueness rules should we use for the RTTI for the /// given type? ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { if (shouldRTTIBeUnique()) return RUK_Unique; // It's only necessary for linkonce_odr or weak_odr linkage. if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && Linkage != llvm::GlobalValue::WeakODRLinkage) return RUK_Unique; // It's only necessary with default visibility. if (CanTy->getVisibility() != DefaultVisibility) return RUK_Unique; // If we're not required to publish this symbol, hide it. if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) return RUK_NonUniqueHidden; // If we're required to publish this symbol, as we might be under an // explicit instantiation, leave it with default visibility but // enable string-comparisons. assert(Linkage == llvm::GlobalValue::WeakODRLinkage); return RUK_NonUniqueVisible; } // Find out how to codegen the complete destructor and constructor namespace { enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; } static StructorCodegen getCodegenToUse(CodeGenModule &CGM, const CXXMethodDecl *MD) { if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) return StructorCodegen::Emit; // The complete and base structors are not equivalent if there are any virtual // bases, so emit separate functions. if (MD->getParent()->getNumVBases()) return StructorCodegen::Emit; GlobalDecl AliasDecl; if (const auto *DD = dyn_cast(MD)) { AliasDecl = GlobalDecl(DD, Dtor_Complete); } else { const auto *CD = cast(MD); AliasDecl = GlobalDecl(CD, Ctor_Complete); } llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) return StructorCodegen::RAUW; // FIXME: Should we allow available_externally aliases? if (!llvm::GlobalAlias::isValidLinkage(Linkage)) return StructorCodegen::RAUW; if (llvm::GlobalValue::isWeakForLinker(Linkage)) { // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). if (CGM.getTarget().getTriple().isOSBinFormatELF() || CGM.getTarget().getTriple().isOSBinFormatWasm()) return StructorCodegen::COMDAT; return StructorCodegen::Emit; } return StructorCodegen::Alias; } static void emitConstructorDestructorAlias(CodeGenModule &CGM, GlobalDecl AliasDecl, GlobalDecl TargetDecl) { llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); StringRef MangledName = CGM.getMangledName(AliasDecl); llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); if (Entry && !Entry->isDeclaration()) return; auto *Aliasee = cast(CGM.GetAddrOfGlobal(TargetDecl)); // Create the alias with no name. auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee); // Constructors and destructors are always unnamed_addr. Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); // Switch any previous uses to the alias. if (Entry) { assert(Entry->getType() == Aliasee->getType() && "declaration exists with different type"); Alias->takeName(Entry); Entry->replaceAllUsesWith(Alias); Entry->eraseFromParent(); } else { Alias->setName(MangledName); } // Finally, set up the alias with its proper name and attributes. CGM.SetCommonAttributes(AliasDecl, Alias); } void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) { auto *CD = dyn_cast(MD); const CXXDestructorDecl *DD = CD ? nullptr : cast(MD); StructorCodegen CGType = getCodegenToUse(CGM, MD); if (Type == StructorType::Complete) { GlobalDecl CompleteDecl; GlobalDecl BaseDecl; if (CD) { CompleteDecl = GlobalDecl(CD, Ctor_Complete); BaseDecl = GlobalDecl(CD, Ctor_Base); } else { CompleteDecl = GlobalDecl(DD, Dtor_Complete); BaseDecl = GlobalDecl(DD, Dtor_Base); } if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); return; } if (CGType == StructorCodegen::RAUW) { StringRef MangledName = CGM.getMangledName(CompleteDecl); auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl); CGM.addReplacement(MangledName, Aliasee); return; } } // The base destructor is equivalent to the base destructor of its // base class if there is exactly one non-virtual base class with a // non-trivial destructor, there are no fields with a non-trivial // destructor, and the body of the destructor is trivial. if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && !CGM.TryEmitBaseDestructorAsAlias(DD)) return; // FIXME: The deleting destructor is equivalent to the selected operator // delete if: // * either the delete is a destroying operator delete or the destructor // would be trivial if it weren't virtual, // * the conversion from the 'this' parameter to the first parameter of the // destructor is equivalent to a bitcast, // * the destructor does not have an implicit "this" return, and // * the operator delete has the same calling convention and IR function type // as the destructor. // In such cases we should try to emit the deleting dtor as an alias to the // selected 'operator delete'. llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); if (CGType == StructorCodegen::COMDAT) { SmallString<256> Buffer; llvm::raw_svector_ostream Out(Buffer); if (DD) getMangleContext().mangleCXXDtorComdat(DD, Out); else getMangleContext().mangleCXXCtorComdat(CD, Out); llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); Fn->setComdat(C); } else { CGM.maybeSetTrivialComdat(*MD, *Fn); } } static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { // void *__cxa_begin_catch(void*); llvm::FunctionType *FTy = llvm::FunctionType::get( CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); } static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { // void __cxa_end_catch(); llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); } static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { // void *__cxa_get_exception_ptr(void*); llvm::FunctionType *FTy = llvm::FunctionType::get( CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); } namespace { /// A cleanup to call __cxa_end_catch. In many cases, the caught /// exception type lets us state definitively that the thrown exception /// type does not have a destructor. In particular: /// - Catch-alls tell us nothing, so we have to conservatively /// assume that the thrown exception might have a destructor. /// - Catches by reference behave according to their base types. /// - Catches of non-record types will only trigger for exceptions /// of non-record types, which never have destructors. /// - Catches of record types can trigger for arbitrary subclasses /// of the caught type, so we have to assume the actual thrown /// exception type might have a throwing destructor, even if the /// caught type's destructor is trivial or nothrow. struct CallEndCatch final : EHScopeStack::Cleanup { CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} bool MightThrow; void Emit(CodeGenFunction &CGF, Flags flags) override { if (!MightThrow) { CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); return; } CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); } }; } /// Emits a call to __cxa_begin_catch and enters a cleanup to call /// __cxa_end_catch. /// /// \param EndMightThrow - true if __cxa_end_catch might throw static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, llvm::Value *Exn, bool EndMightThrow) { llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); CGF.EHStack.pushCleanup(NormalAndEHCleanup, EndMightThrow); return call; } /// A "special initializer" callback for initializing a catch /// parameter during catch initialization. static void InitCatchParam(CodeGenFunction &CGF, const VarDecl &CatchParam, Address ParamAddr, SourceLocation Loc) { // Load the exception from where the landing pad saved it. llvm::Value *Exn = CGF.getExceptionFromSlot(); CanQualType CatchType = CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); // If we're catching by reference, we can just cast the object // pointer to the appropriate pointer. if (isa(CatchType)) { QualType CaughtType = cast(CatchType)->getPointeeType(); bool EndCatchMightThrow = CaughtType->isRecordType(); // __cxa_begin_catch returns the adjusted object pointer. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); // We have no way to tell the personality function that we're // catching by reference, so if we're catching a pointer, // __cxa_begin_catch will actually return that pointer by value. if (const PointerType *PT = dyn_cast(CaughtType)) { QualType PointeeType = PT->getPointeeType(); // When catching by reference, generally we should just ignore // this by-value pointer and use the exception object instead. if (!PointeeType->isRecordType()) { // Exn points to the struct _Unwind_Exception header, which // we have to skip past in order to reach the exception data. unsigned HeaderSize = CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); // However, if we're catching a pointer-to-record type that won't // work, because the personality function might have adjusted // the pointer. There's actually no way for us to fully satisfy // the language/ABI contract here: we can't use Exn because it // might have the wrong adjustment, but we can't use the by-value // pointer because it's off by a level of abstraction. // // The current solution is to dump the adjusted pointer into an // alloca, which breaks language semantics (because changing the // pointer doesn't change the exception) but at least works. // The better solution would be to filter out non-exact matches // and rethrow them, but this is tricky because the rethrow // really needs to be catchable by other sites at this landing // pad. The best solution is to fix the personality function. } else { // Pull the pointer for the reference type off. llvm::Type *PtrTy = cast(LLVMCatchTy)->getElementType(); // Create the temporary and write the adjusted pointer into it. Address ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp"); llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); CGF.Builder.CreateStore(Casted, ExnPtrTmp); // Bind the reference to the temporary. AdjustedExn = ExnPtrTmp.getPointer(); } } llvm::Value *ExnCast = CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); CGF.Builder.CreateStore(ExnCast, ParamAddr); return; } // Scalars and complexes. TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); if (TEK != TEK_Aggregate) { llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); // If the catch type is a pointer type, __cxa_begin_catch returns // the pointer by value. if (CatchType->hasPointerRepresentation()) { llvm::Value *CastExn = CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); switch (CatchType.getQualifiers().getObjCLifetime()) { case Qualifiers::OCL_Strong: CastExn = CGF.EmitARCRetainNonBlock(CastExn); LLVM_FALLTHROUGH; case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: CGF.Builder.CreateStore(CastExn, ParamAddr); return; case Qualifiers::OCL_Weak: CGF.EmitARCInitWeak(ParamAddr, CastExn); return; } llvm_unreachable("bad ownership qualifier!"); } // Otherwise, it returns a pointer into the exception object. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType); switch (TEK) { case TEK_Complex: CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV, /*init*/ true); return; case TEK_Scalar: { llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc); CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); return; } case TEK_Aggregate: llvm_unreachable("evaluation kind filtered out!"); } llvm_unreachable("bad evaluation kind"); } assert(isa(CatchType) && "unexpected catch type!"); auto catchRD = CatchType->getAsCXXRecordDecl(); CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD); llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok // Check for a copy expression. If we don't have a copy expression, // that means a trivial copy is okay. const Expr *copyExpr = CatchParam.getInit(); if (!copyExpr) { llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), caughtExnAlignment); LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType); LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType); CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap); return; } // We have to call __cxa_get_exception_ptr to get the adjusted // pointer before copying. llvm::CallInst *rawAdjustedExn = CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); // Cast that to the appropriate type. Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), caughtExnAlignment); // The copy expression is defined in terms of an OpaqueValueExpr. // Find it and map it to the adjusted expression. CodeGenFunction::OpaqueValueMapping opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); // Call the copy ctor in a terminate scope. CGF.EHStack.pushTerminate(); // Perform the copy construction. CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(), AggValueSlot::IsNotDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); // Leave the terminate scope. CGF.EHStack.popTerminate(); // Undo the opaque value mapping. opaque.pop(); // Finally we can call __cxa_begin_catch. CallBeginCatch(CGF, Exn, true); } /// Begins a catch statement by initializing the catch variable and /// calling __cxa_begin_catch. void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) { // We have to be very careful with the ordering of cleanups here: // C++ [except.throw]p4: // The destruction [of the exception temporary] occurs // immediately after the destruction of the object declared in // the exception-declaration in the handler. // // So the precise ordering is: // 1. Construct catch variable. // 2. __cxa_begin_catch // 3. Enter __cxa_end_catch cleanup // 4. Enter dtor cleanup // // We do this by using a slightly abnormal initialization process. // Delegation sequence: // - ExitCXXTryStmt opens a RunCleanupsScope // - EmitAutoVarAlloca creates the variable and debug info // - InitCatchParam initializes the variable from the exception // - CallBeginCatch calls __cxa_begin_catch // - CallBeginCatch enters the __cxa_end_catch cleanup // - EmitAutoVarCleanups enters the variable destructor cleanup // - EmitCXXTryStmt emits the code for the catch body // - EmitCXXTryStmt close the RunCleanupsScope VarDecl *CatchParam = S->getExceptionDecl(); if (!CatchParam) { llvm::Value *Exn = CGF.getExceptionFromSlot(); CallBeginCatch(CGF, Exn, true); return; } // Emit the local. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc()); CGF.EmitAutoVarCleanups(var); } /// Get or define the following function: /// void @__clang_call_terminate(i8* %exn) nounwind noreturn /// This code is used only in C++. static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { llvm::FunctionType *fnTy = llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); llvm::Constant *fnRef = CGM.CreateRuntimeFunction( fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true); llvm::Function *fn = dyn_cast(fnRef); if (fn && fn->empty()) { fn->setDoesNotThrow(); fn->setDoesNotReturn(); // What we really want is to massively penalize inlining without // forbidding it completely. The difference between that and // 'noinline' is negligible. fn->addFnAttr(llvm::Attribute::NoInline); // Allow this function to be shared across translation units, but // we don't want it to turn into an exported symbol. fn->setLinkage(llvm::Function::LinkOnceODRLinkage); fn->setVisibility(llvm::Function::HiddenVisibility); if (CGM.supportsCOMDAT()) fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName())); // Set up the function. llvm::BasicBlock *entry = llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); CGBuilderTy builder(CGM, entry); // Pull the exception pointer out of the parameter list. llvm::Value *exn = &*fn->arg_begin(); // Call __cxa_begin_catch(exn). llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); catchCall->setDoesNotThrow(); catchCall->setCallingConv(CGM.getRuntimeCC()); // Call std::terminate(). llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn()); termCall->setDoesNotThrow(); termCall->setDoesNotReturn(); termCall->setCallingConv(CGM.getRuntimeCC()); // std::terminate cannot return. builder.CreateUnreachable(); } return fnRef; } llvm::CallInst * ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, llvm::Value *Exn) { // In C++, we want to call __cxa_begin_catch() before terminating. if (Exn) { assert(CGF.CGM.getLangOpts().CPlusPlus); return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn); } return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn()); } std::pair ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This, const CXXRecordDecl *RD) { return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD}; } void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) { if (CGF.getTarget().hasFeature("exception-handling")) CGF.EHStack.pushCleanup( NormalCleanup, cast(CGF.CurrentFuncletPad)); ItaniumCXXABI::emitBeginCatch(CGF, C); } Index: vendor/clang/dist-release_80/lib/CodeGen/TargetInfo.cpp =================================================================== --- vendor/clang/dist-release_80/lib/CodeGen/TargetInfo.cpp (revision 343192) +++ vendor/clang/dist-release_80/lib/CodeGen/TargetInfo.cpp (revision 343193) @@ -1,9526 +1,9524 @@ //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These classes wrap the information about a call or function // definition used to handle ABI compliancy. // //===----------------------------------------------------------------------===// #include "TargetInfo.h" #include "ABIInfo.h" #include "CGBlocks.h" #include "CGCXXABI.h" #include "CGValue.h" #include "CodeGenFunction.h" #include "clang/AST/RecordLayout.h" #include "clang/Basic/CodeGenOptions.h" #include "clang/CodeGen/CGFunctionInfo.h" #include "clang/CodeGen/SwiftCallingConv.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Type.h" #include "llvm/Support/raw_ostream.h" #include // std::sort using namespace clang; using namespace CodeGen; // Helper for coercing an aggregate argument or return value into an integer // array of the same size (including padding) and alignment. This alternate // coercion happens only for the RenderScript ABI and can be removed after // runtimes that rely on it are no longer supported. // // RenderScript assumes that the size of the argument / return value in the IR // is the same as the size of the corresponding qualified type. This helper // coerces the aggregate type into an array of the same size (including // padding). This coercion is used in lieu of expansion of struct members or // other canonical coercions that return a coerced-type of larger size. // // Ty - The argument / return value type // Context - The associated ASTContext // LLVMContext - The associated LLVMContext static ABIArgInfo coerceToIntArray(QualType Ty, ASTContext &Context, llvm::LLVMContext &LLVMContext) { // Alignment and Size are measured in bits. const uint64_t Size = Context.getTypeSize(Ty); const uint64_t Alignment = Context.getTypeAlign(Ty); llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); const uint64_t NumElements = (Size + Alignment - 1) / Alignment; return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); } static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, llvm::Value *Array, llvm::Value *Value, unsigned FirstIndex, unsigned LastIndex) { // Alternatively, we could emit this as a loop in the source. for (unsigned I = FirstIndex; I <= LastIndex; ++I) { llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); } } static bool isAggregateTypeForABI(QualType T) { return !CodeGenFunction::hasScalarEvaluationKind(T) || T->isMemberFunctionPointerType(); } ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign, llvm::Type *Padding) const { return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByRef, Realign, Padding); } ABIArgInfo ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), /*ByRef*/ false, Realign); } Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { return Address::invalid(); } ABIInfo::~ABIInfo() {} /// Does the given lowering require more than the given number of /// registers when expanded? /// /// This is intended to be the basis of a reasonable basic implementation /// of should{Pass,Return}IndirectlyForSwift. /// /// For most targets, a limit of four total registers is reasonable; this /// limits the amount of code required in order to move around the value /// in case it wasn't produced immediately prior to the call by the caller /// (or wasn't produced in exactly the right registers) or isn't used /// immediately within the callee. But some targets may need to further /// limit the register count due to an inability to support that many /// return registers. static bool occupiesMoreThan(CodeGenTypes &cgt, ArrayRef scalarTypes, unsigned maxAllRegisters) { unsigned intCount = 0, fpCount = 0; for (llvm::Type *type : scalarTypes) { if (type->isPointerTy()) { intCount++; } else if (auto intTy = dyn_cast(type)) { auto ptrWidth = cgt.getTarget().getPointerWidth(0); intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; } else { assert(type->isVectorTy() || type->isFloatingPointTy()); fpCount++; } } return (intCount + fpCount > maxAllRegisters); } bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, llvm::Type *eltTy, unsigned numElts) const { // The default implementation of this assumes that the target guarantees // 128-bit SIMD support but nothing more. return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); } static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI) { const CXXRecordDecl *RD = dyn_cast(RT->getDecl()); if (!RD) { if (!RT->getDecl()->canPassInRegisters()) return CGCXXABI::RAA_Indirect; return CGCXXABI::RAA_Default; } return CXXABI.getRecordArgABI(RD); } static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, CGCXXABI &CXXABI) { const RecordType *RT = T->getAs(); if (!RT) return CGCXXABI::RAA_Default; return getRecordArgABI(RT, CXXABI); } static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info) { QualType Ty = FI.getReturnType(); if (const auto *RT = Ty->getAs()) if (!isa(RT->getDecl()) && !RT->getDecl()->canPassInRegisters()) { FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); return true; } return CXXABI.classifyReturnType(FI); } /// Pass transparent unions as if they were the type of the first element. Sema /// should ensure that all elements of the union have the same "machine type". static QualType useFirstFieldIfTransparentUnion(QualType Ty) { if (const RecordType *UT = Ty->getAsUnionType()) { const RecordDecl *UD = UT->getDecl(); if (UD->hasAttr()) { assert(!UD->field_empty() && "sema created an empty transparent union"); return UD->field_begin()->getType(); } } return Ty; } CGCXXABI &ABIInfo::getCXXABI() const { return CGT.getCXXABI(); } ASTContext &ABIInfo::getContext() const { return CGT.getContext(); } llvm::LLVMContext &ABIInfo::getVMContext() const { return CGT.getLLVMContext(); } const llvm::DataLayout &ABIInfo::getDataLayout() const { return CGT.getDataLayout(); } const TargetInfo &ABIInfo::getTarget() const { return CGT.getTarget(); } const CodeGenOptions &ABIInfo::getCodeGenOpts() const { return CGT.getCodeGenOpts(); } bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { return false; } bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const { return false; } LLVM_DUMP_METHOD void ABIArgInfo::dump() const { raw_ostream &OS = llvm::errs(); OS << "(ABIArgInfo Kind="; switch (TheKind) { case Direct: OS << "Direct Type="; if (llvm::Type *Ty = getCoerceToType()) Ty->print(OS); else OS << "null"; break; case Extend: OS << "Extend"; break; case Ignore: OS << "Ignore"; break; case InAlloca: OS << "InAlloca Offset=" << getInAllocaFieldIndex(); break; case Indirect: OS << "Indirect Align=" << getIndirectAlign().getQuantity() << " ByVal=" << getIndirectByVal() << " Realign=" << getIndirectRealign(); break; case Expand: OS << "Expand"; break; case CoerceAndExpand: OS << "CoerceAndExpand Type="; getCoerceAndExpandType()->print(OS); break; } OS << ")\n"; } // Dynamically round a pointer up to a multiple of the given alignment. static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, llvm::Value *Ptr, CharUnits Align) { llvm::Value *PtrAsInt = Ptr; // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, Ptr->getType(), Ptr->getName() + ".aligned"); return PtrAsInt; } /// Emit va_arg for a platform using the common void* representation, /// where arguments are simply emitted in an array of slots on the stack. /// /// This version implements the core direct-value passing rules. /// /// \param SlotSize - The size and alignment of a stack slot. /// Each argument will be allocated to a multiple of this number of /// slots, and all the slots will be aligned to this value. /// \param AllowHigherAlign - The slot alignment is not a cap; /// an argument type with an alignment greater than the slot size /// will be emitted on a higher-alignment address, potentially /// leaving one or more empty slots behind as padding. If this /// is false, the returned address might be less-aligned than /// DirectAlign. static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, Address VAListAddr, llvm::Type *DirectTy, CharUnits DirectSize, CharUnits DirectAlign, CharUnits SlotSize, bool AllowHigherAlign) { // Cast the element type to i8* if necessary. Some platforms define // va_list as a struct containing an i8* instead of just an i8*. if (VAListAddr.getElementType() != CGF.Int8PtrTy) VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); // If the CC aligns values higher than the slot size, do so if needed. Address Addr = Address::invalid(); if (AllowHigherAlign && DirectAlign > SlotSize) { Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), DirectAlign); } else { Addr = Address(Ptr, SlotSize); } // Advance the pointer past the argument, then store that back. CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); llvm::Value *NextPtr = CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize, "argp.next"); CGF.Builder.CreateStore(NextPtr, VAListAddr); // If the argument is smaller than a slot, and this is a big-endian // target, the argument will be right-adjusted in its slot. if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && !DirectTy->isStructTy()) { Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); } Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); return Addr; } /// Emit va_arg for a platform using the common void* representation, /// where arguments are simply emitted in an array of slots on the stack. /// /// \param IsIndirect - Values of this type are passed indirectly. /// \param ValueInfo - The size and alignment of this type, generally /// computed with getContext().getTypeInfoInChars(ValueTy). /// \param SlotSizeAndAlign - The size and alignment of a stack slot. /// Each argument will be allocated to a multiple of this number of /// slots, and all the slots will be aligned to this value. /// \param AllowHigherAlign - The slot alignment is not a cap; /// an argument type with an alignment greater than the slot size /// will be emitted on a higher-alignment address, potentially /// leaving one or more empty slots behind as padding. static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, std::pair ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign) { // The size and alignment of the value that was passed directly. CharUnits DirectSize, DirectAlign; if (IsIndirect) { DirectSize = CGF.getPointerSize(); DirectAlign = CGF.getPointerAlign(); } else { DirectSize = ValueInfo.first; DirectAlign = ValueInfo.second; } // Cast the address we've calculated to the right type. llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); if (IsIndirect) DirectTy = DirectTy->getPointerTo(0); Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign, SlotSizeAndAlign, AllowHigherAlign); if (IsIndirect) { Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second); } return Addr; } static Address emitMergePHI(CodeGenFunction &CGF, Address Addr1, llvm::BasicBlock *Block1, Address Addr2, llvm::BasicBlock *Block2, const llvm::Twine &Name = "") { assert(Addr1.getType() == Addr2.getType()); llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); PHI->addIncoming(Addr1.getPointer(), Block1); PHI->addIncoming(Addr2.getPointer(), Block2); CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); return Address(PHI, Align); } TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } // If someone can figure out a general rule for this, that would be great. // It's probably just doomed to be platform-dependent, though. unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { // Verified for: // x86-64 FreeBSD, Linux, Darwin // x86-32 FreeBSD, Linux, Darwin // PowerPC Linux, Darwin // ARM Darwin (*not* EABI) // AArch64 Linux return 32; } bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, const FunctionNoProtoType *fnType) const { // The following conventions are known to require this to be false: // x86_stdcall // MIPS // For everything else, we just prefer false unless we opt out. return false; } void TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const { // This assumes the user is passing a library name like "rt" instead of a // filename like "librt.a/so", and that they don't care whether it's static or // dynamic. Opt = "-l"; Opt += Lib; } unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { // OpenCL kernels are called via an explicit runtime API with arguments // set with clSetKernelArg(), not as normal sub-functions. // Return SPIR_KERNEL by default as the kernel calling convention to // ensure the fingerprint is fixed such way that each OpenCL argument // gets one matching argument in the produced kernel function argument // list to enable feasible implementation of clSetKernelArg() with // aggregates etc. In case we would use the default C calling conv here, // clSetKernelArg() might break depending on the target-specific // conventions; different targets might split structs passed as values // to multiple function arguments etc. return llvm::CallingConv::SPIR_KERNEL; } llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, llvm::PointerType *T, QualType QT) const { return llvm::ConstantPointerNull::get(T); } LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const { assert(!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && "Address space agnostic languages only"); return D ? D->getType().getAddressSpace() : LangAS::Default; } llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { // Since target may map different address spaces in AST to the same address // space, an address space conversion may end up as a bitcast. if (auto *C = dyn_cast(Src)) return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy); } llvm::Constant * TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy) const { // Since target may map different address spaces in AST to the same address // space, an address space conversion may end up as a bitcast. return llvm::ConstantExpr::getPointerCast(Src, DestTy); } llvm::SyncScope::ID TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const { return C.getOrInsertSyncScopeID(""); /* default sync scope */ } static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); /// isEmptyField - Return true iff a the field is "empty", that is it /// is an unnamed bit-field or an (array of) empty record(s). static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, bool AllowArrays) { if (FD->isUnnamedBitfield()) return true; QualType FT = FD->getType(); // Constant arrays of empty records count as empty, strip them off. // Constant arrays of zero length always count as empty. if (AllowArrays) while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { if (AT->getSize() == 0) return true; FT = AT->getElementType(); } const RecordType *RT = FT->getAs(); if (!RT) return false; // C++ record fields are never empty, at least in the Itanium ABI. // // FIXME: We should use a predicate for whether this behavior is true in the // current ABI. if (isa(RT->getDecl())) return false; return isEmptyRecord(Context, FT, AllowArrays); } /// isEmptyRecord - Return true iff a structure contains only empty /// fields. Note that a structure with a flexible array member is not /// considered empty. static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { const RecordType *RT = T->getAs(); if (!RT) return false; const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return false; // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) for (const auto &I : CXXRD->bases()) if (!isEmptyRecord(Context, I.getType(), true)) return false; for (const auto *I : RD->fields()) if (!isEmptyField(Context, I, AllowArrays)) return false; return true; } /// isSingleElementStruct - Determine if a structure is a "single /// element struct", i.e. it has exactly one non-empty field or /// exactly one field which is itself a single element /// struct. Structures with flexible array members are never /// considered single element structs. /// /// \return The field declaration for the single non-empty field, if /// it exists. static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { const RecordType *RT = T->getAs(); if (!RT) return nullptr; const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return nullptr; const Type *Found = nullptr; // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { for (const auto &I : CXXRD->bases()) { // Ignore empty records. if (isEmptyRecord(Context, I.getType(), true)) continue; // If we already found an element then this isn't a single-element struct. if (Found) return nullptr; // If this is non-empty and not a single element struct, the composite // cannot be a single element struct. Found = isSingleElementStruct(I.getType(), Context); if (!Found) return nullptr; } } // Check for single element. for (const auto *FD : RD->fields()) { QualType FT = FD->getType(); // Ignore empty fields. if (isEmptyField(Context, FD, true)) continue; // If we already found an element then this isn't a single-element // struct. if (Found) return nullptr; // Treat single element arrays as the element. while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { if (AT->getSize().getZExtValue() != 1) break; FT = AT->getElementType(); } if (!isAggregateTypeForABI(FT)) { Found = FT.getTypePtr(); } else { Found = isSingleElementStruct(FT, Context); if (!Found) return nullptr; } } // We don't consider a struct a single-element struct if it has // padding beyond the element type. if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) return nullptr; return Found; } namespace { Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, const ABIArgInfo &AI) { // This default implementation defers to the llvm backend's va_arg // instruction. It can handle only passing arguments directly // (typically only handled in the backend for primitive types), or // aggregates passed indirectly by pointer (NOTE: if the "byval" // flag has ABI impact in the callee, this implementation cannot // work.) // Only a few cases are covered here at the moment -- those needed // by the default abi. llvm::Value *Val; if (AI.isIndirect()) { assert(!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); assert( !AI.getIndirectRealign() && "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); CharUnits TyAlignForABI = TyInfo.second; llvm::Type *BaseTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); llvm::Value *Addr = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); return Address(Addr, TyAlignForABI); } else { assert((AI.isDirect() || AI.isExtend()) && "Unexpected ArgInfo Kind in generic VAArg emitter!"); assert(!AI.getInReg() && "Unexpected InReg seen in arginfo in generic VAArg emitter!"); assert(!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); assert(!AI.getDirectOffset() && "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); assert(!AI.getCoerceToType() && "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); Address Temp = CGF.CreateMemTemp(Ty, "varet"); Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); CGF.Builder.CreateStore(Val, Temp); return Temp; } } /// DefaultABIInfo - The default implementation for ABI specific /// details. This implementation provides information which results in /// self-consistent and sensible LLVM IR generation, but does not /// conform to any particular ABI. class DefaultABIInfo : public ABIInfo { public: DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType RetTy) const; void computeInfo(CGFunctionInfo &FI) const override { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type); } Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override { return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); } }; class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { public: DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} }; ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { Ty = useFirstFieldIfTransparentUnion(Ty); if (isAggregateTypeForABI(Ty)) { // Records with non-trivial destructors/copy-constructors should not be // passed by value. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); return getNaturalAlignIndirect(Ty); } // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); if (isAggregateTypeForABI(RetTy)) return getNaturalAlignIndirect(RetTy); // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } //===----------------------------------------------------------------------===// // WebAssembly ABI Implementation // // This is a very simple ABI that relies a lot on DefaultABIInfo. //===----------------------------------------------------------------------===// class WebAssemblyABIInfo final : public SwiftABIInfo { DefaultABIInfo defaultInfo; public: explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT) : SwiftABIInfo(CGT), defaultInfo(CGT) {} private: ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType Ty) const; // DefaultABIInfo's classifyReturnType and classifyArgumentType are // non-virtual, but computeInfo and EmitVAArg are virtual, so we // overload them. void computeInfo(CGFunctionInfo &FI) const override { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &Arg : FI.arguments()) Arg.info = classifyArgumentType(Arg.type); } Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return false; } }; class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { public: explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { if (auto *FD = dyn_cast_or_null(D)) { llvm::Function *Fn = cast(GV); if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) Fn->addFnAttr("no-prototype"); } } }; /// Classify argument of given type \p Ty. ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { Ty = useFirstFieldIfTransparentUnion(Ty); if (isAggregateTypeForABI(Ty)) { // Records with non-trivial destructors/copy-constructors should not be // passed by value. if (auto RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // Ignore empty structs/unions. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); // Lower single-element structs to just pass a regular value. TODO: We // could do reasonable-size multiple-element structs too, using getExpand(), // though watch out for things like bitfields. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); } // Otherwise just do the default thing. return defaultInfo.classifyArgumentType(Ty); } ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { if (isAggregateTypeForABI(RetTy)) { // Records with non-trivial destructors/copy-constructors should not be // returned by value. if (!getRecordArgABI(RetTy, getCXXABI())) { // Ignore empty structs/unions. if (isEmptyRecord(getContext(), RetTy, true)) return ABIArgInfo::getIgnore(); // Lower single-element structs to just return a regular value. TODO: We // could do reasonable-size multiple-element structs too, using // ABIArgInfo::getDirect(). if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); } } // Otherwise just do the default thing. return defaultInfo.classifyReturnType(RetTy); } Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false, getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(4), /*AllowHigherAlign=*/ true); } //===----------------------------------------------------------------------===// // le32/PNaCl bitcode ABI Implementation // // This is a simplified version of the x86_32 ABI. Arguments and return values // are always passed on the stack. //===----------------------------------------------------------------------===// class PNaClABIInfo : public ABIInfo { public: PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType RetTy) const; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; }; class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { public: PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} }; void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type); } Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { // The PNaCL ABI is a bit odd, in that varargs don't use normal // function classification. Structs get passed directly for varargs // functions, through a rewriting transform in // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows // this target to actually support a va_arg instructions with an // aggregate type, unlike other targets. return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); } /// Classify argument of given type \p Ty. ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { if (isAggregateTypeForABI(Ty)) { if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); return getNaturalAlignIndirect(Ty); } else if (const EnumType *EnumTy = Ty->getAs()) { // Treat an enum type as its underlying type. Ty = EnumTy->getDecl()->getIntegerType(); } else if (Ty->isFloatingType()) { // Floating-point types don't go inreg. return ABIArgInfo::getDirect(); } return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); // In the PNaCl ABI we always return records/structures on the stack. if (isAggregateTypeForABI(RetTy)) return getNaturalAlignIndirect(RetTy); // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } /// IsX86_MMXType - Return true if this is an MMX type. bool IsX86_MMXType(llvm::Type *IRType) { // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && cast(IRType)->getElementType()->isIntegerTy() && IRType->getScalarSizeInBits() != 64; } static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, StringRef Constraint, llvm::Type* Ty) { bool IsMMXCons = llvm::StringSwitch(Constraint) .Cases("y", "&y", "^Ym", true) .Default(false); if (IsMMXCons && Ty->isVectorTy()) { if (cast(Ty)->getBitWidth() != 64) { // Invalid MMX constraint return nullptr; } return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); } // No operation needed return Ty; } /// Returns true if this type can be passed in SSE registers with the /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { if (const BuiltinType *BT = Ty->getAs()) { if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { if (BT->getKind() == BuiltinType::LongDouble) { if (&Context.getTargetInfo().getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended()) return false; } return true; } } else if (const VectorType *VT = Ty->getAs()) { // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX // registers specially. unsigned VecSize = Context.getTypeSize(VT); if (VecSize == 128 || VecSize == 256 || VecSize == 512) return true; } return false; } /// Returns true if this aggregate is small enough to be passed in SSE registers /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { return NumMembers <= 4; } /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { auto AI = ABIArgInfo::getDirect(T); AI.setInReg(true); AI.setCanBeFlattened(false); return AI; } //===----------------------------------------------------------------------===// // X86-32 ABI Implementation //===----------------------------------------------------------------------===// /// Similar to llvm::CCState, but for Clang. struct CCState { CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {} unsigned CC; unsigned FreeRegs; unsigned FreeSSERegs; }; enum { // Vectorcall only allows the first 6 parameters to be passed in registers. VectorcallMaxParamNumAsReg = 6 }; /// X86_32ABIInfo - The X86-32 ABI information. class X86_32ABIInfo : public SwiftABIInfo { enum Class { Integer, Float }; static const unsigned MinABIStackAlignInBytes = 4; bool IsDarwinVectorABI; bool IsRetSmallStructInRegABI; bool IsWin32StructABI; bool IsSoftFloatABI; bool IsMCUABI; unsigned DefaultNumRegisterParameters; static bool isRegisterSize(unsigned Size) { return (Size == 8 || Size == 16 || Size == 32 || Size == 64); } bool isHomogeneousAggregateBaseType(QualType Ty) const override { // FIXME: Assumes vectorcall is in use. return isX86VectorTypeForVectorCall(getContext(), Ty); } bool isHomogeneousAggregateSmallEnough(const Type *Ty, uint64_t NumMembers) const override { // FIXME: Assumes vectorcall is in use. return isX86VectorCallAggregateSmallEnough(NumMembers); } bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; /// getIndirectResult - Give a source type \arg Ty, return a suitable result /// such that the argument will be passed in memory. ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; /// Return the alignment to use for the given type on the stack. unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; Class classify(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; /// Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, bool &NeedsPadding) const; bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; bool canExpandIndirectArgument(QualType Ty) const; /// Rewrite the function info so that all memory arguments use /// inalloca. void rewriteWithInAlloca(CGFunctionInfo &FI) const; void addFieldToArgStruct(SmallVector &FrameFields, CharUnits &StackOffset, ABIArgInfo &Info, QualType Type) const; void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State, bool &UsedInAlloca) const; public: void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI) : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), IsRetSmallStructInRegABI(RetSmallStructInRegABI), IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), DefaultNumRegisterParameters(NumRegisterParameters) {} bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { // LLVM's x86-32 lowering currently only assigns up to three // integer registers and three fp registers. Oddly, it'll use up to // four vector registers for vectors, but those can overlap with the // scalar registers. return occupiesMoreThan(CGT, scalars, /*total*/ 3); } bool isSwiftErrorInRegister() const override { // x86-32 lowering does not support passing swifterror in a register. return false; } }; class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { public: X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI) : TargetCodeGenInfo(new X86_32ABIInfo( CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, NumRegisterParameters, SoftFloatABI)) {} static bool isStructReturnInRegABI( const llvm::Triple &Triple, const CodeGenOptions &Opts); void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override; int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { // Darwin uses different dwarf register numbers for EH. if (CGM.getTarget().getTriple().isOSDarwin()) return 5; return 4; } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, StringRef Constraint, llvm::Type* Ty) const override { return X86AdjustInlineAsmType(CGF, Constraint, Ty); } void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, std::string &Constraints, std::vector &ResultRegTypes, std::vector &ResultTruncRegTypes, std::vector &ResultRegDests, std::string &AsmString, unsigned NumOutputs) const override; llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { unsigned Sig = (0xeb << 0) | // jmp rel8 (0x06 << 8) | // .+0x08 ('v' << 16) | ('2' << 24); return llvm::ConstantInt::get(CGM.Int32Ty, Sig); } StringRef getARCRetainAutoreleasedReturnValueMarker() const override { return "movl\t%ebp, %ebp" "\t\t// marker for objc_retainAutoreleaseReturnValue"; } }; } /// Rewrite input constraint references after adding some output constraints. /// In the case where there is one output and one input and we add one output, /// we need to replace all operand references greater than or equal to 1: /// mov $0, $1 /// mov eax, $1 /// The result will be: /// mov $0, $2 /// mov eax, $2 static void rewriteInputConstraintReferences(unsigned FirstIn, unsigned NumNewOuts, std::string &AsmString) { std::string Buf; llvm::raw_string_ostream OS(Buf); size_t Pos = 0; while (Pos < AsmString.size()) { size_t DollarStart = AsmString.find('$', Pos); if (DollarStart == std::string::npos) DollarStart = AsmString.size(); size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); if (DollarEnd == std::string::npos) DollarEnd = AsmString.size(); OS << StringRef(&AsmString[Pos], DollarEnd - Pos); Pos = DollarEnd; size_t NumDollars = DollarEnd - DollarStart; if (NumDollars % 2 != 0 && Pos < AsmString.size()) { // We have an operand reference. size_t DigitStart = Pos; size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); if (DigitEnd == std::string::npos) DigitEnd = AsmString.size(); StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); unsigned OperandIndex; if (!OperandStr.getAsInteger(10, OperandIndex)) { if (OperandIndex >= FirstIn) OperandIndex += NumNewOuts; OS << OperandIndex; } else { OS << OperandStr; } Pos = DigitEnd; } } AsmString = std::move(OS.str()); } /// Add output constraints for EAX:EDX because they are return registers. void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, std::vector &ResultRegTypes, std::vector &ResultTruncRegTypes, std::vector &ResultRegDests, std::string &AsmString, unsigned NumOutputs) const { uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is // larger. if (!Constraints.empty()) Constraints += ','; if (RetWidth <= 32) { Constraints += "={eax}"; ResultRegTypes.push_back(CGF.Int32Ty); } else { // Use the 'A' constraint for EAX:EDX. Constraints += "=A"; ResultRegTypes.push_back(CGF.Int64Ty); } // Truncate EAX or EAX:EDX to an integer of the appropriate size. llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); ResultTruncRegTypes.push_back(CoerceTy); // Coerce the integer by bitcasting the return slot pointer. ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(), CoerceTy->getPointerTo())); ResultRegDests.push_back(ReturnSlot); rewriteInputConstraintReferences(NumOutputs, 1, AsmString); } /// shouldReturnTypeInRegister - Determine if the given type should be /// returned in a register (for the Darwin and MCU ABI). bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const { uint64_t Size = Context.getTypeSize(Ty); // For i386, type must be register sized. // For the MCU ABI, it only needs to be <= 8-byte if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) return false; if (Ty->isVectorType()) { // 64- and 128- bit vectors inside structures are not returned in // registers. if (Size == 64 || Size == 128) return false; return true; } // If this is a builtin, pointer, enum, complex type, member pointer, or // member function pointer it is ok. if (Ty->getAs() || Ty->hasPointerRepresentation() || Ty->isAnyComplexType() || Ty->isEnumeralType() || Ty->isBlockPointerType() || Ty->isMemberPointerType()) return true; // Arrays are treated like records. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) return shouldReturnTypeInRegister(AT->getElementType(), Context); // Otherwise, it must be a record type. const RecordType *RT = Ty->getAs(); if (!RT) return false; // FIXME: Traverse bases here too. // Structure types are passed in register if all fields would be // passed in a register. for (const auto *FD : RT->getDecl()->fields()) { // Empty fields are ignored. if (isEmptyField(Context, FD, true)) continue; // Check fields recursively. if (!shouldReturnTypeInRegister(FD->getType(), Context)) return false; } return true; } static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { // Treat complex types as the element type. if (const ComplexType *CTy = Ty->getAs()) Ty = CTy->getElementType(); // Check for a type which we know has a simple scalar argument-passing // convention without any padding. (We're specifically looking for 32 // and 64-bit integer and integer-equivalents, float, and double.) if (!Ty->getAs() && !Ty->hasPointerRepresentation() && !Ty->isEnumeralType() && !Ty->isBlockPointerType()) return false; uint64_t Size = Context.getTypeSize(Ty); return Size == 32 || Size == 64; } static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, uint64_t &Size) { for (const auto *FD : RD->fields()) { // Scalar arguments on the stack get 4 byte alignment on x86. If the // argument is smaller than 32-bits, expanding the struct will create // alignment padding. if (!is32Or64BitBasicType(FD->getType(), Context)) return false; // FIXME: Reject bit-fields wholesale; there are two problems, we don't know // how to expand them yet, and the predicate for telling if a bitfield still // counts as "basic" is more complicated than what we were doing previously. if (FD->isBitField()) return false; Size += Context.getTypeSize(FD->getType()); } return true; } static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, uint64_t &Size) { // Don't do this if there are any non-empty bases. for (const CXXBaseSpecifier &Base : RD->bases()) { if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), Size)) return false; } if (!addFieldSizes(Context, RD, Size)) return false; return true; } /// Test whether an argument type which is to be passed indirectly (on the /// stack) would have the equivalent layout if it was expanded into separate /// arguments. If so, we prefer to do the latter to avoid inhibiting /// optimizations. bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { // We can only expand structure types. const RecordType *RT = Ty->getAs(); if (!RT) return false; const RecordDecl *RD = RT->getDecl(); uint64_t Size = 0; if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { if (!IsWin32StructABI) { // On non-Windows, we have to conservatively match our old bitcode // prototypes in order to be ABI-compatible at the bitcode level. if (!CXXRD->isCLike()) return false; } else { // Don't do this for dynamic classes. if (CXXRD->isDynamicClass()) return false; } if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) return false; } else { if (!addFieldSizes(getContext(), RD, Size)) return false; } // We can do this if there was no alignment padding. return Size == getContext().getTypeSize(Ty); } ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { // If the return value is indirect, then the hidden argument is consuming one // integer register. if (State.FreeRegs) { --State.FreeRegs; if (!IsMCUABI) return getNaturalAlignIndirectInReg(RetTy); } return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); } ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); const Type *Base = nullptr; uint64_t NumElts = 0; if ((State.CC == llvm::CallingConv::X86_VectorCall || State.CC == llvm::CallingConv::X86_RegCall) && isHomogeneousAggregate(RetTy, Base, NumElts)) { // The LLVM struct type for such an aggregate should lower properly. return ABIArgInfo::getDirect(); } if (const VectorType *VT = RetTy->getAs()) { // On Darwin, some vectors are returned in registers. if (IsDarwinVectorABI) { uint64_t Size = getContext().getTypeSize(RetTy); // 128-bit vectors are a special case; they are returned in // registers and we need to make sure to pick a type the LLVM // backend will like. if (Size == 128) return ABIArgInfo::getDirect(llvm::VectorType::get( llvm::Type::getInt64Ty(getVMContext()), 2)); // Always return in register if it fits in a general purpose // register, or if it is 64 bits and has a single element. if ((Size == 8 || Size == 16 || Size == 32) || (Size == 64 && VT->getNumElements() == 1)) return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); return getIndirectReturnResult(RetTy, State); } return ABIArgInfo::getDirect(); } if (isAggregateTypeForABI(RetTy)) { if (const RecordType *RT = RetTy->getAs()) { // Structures with flexible arrays are always indirect. if (RT->getDecl()->hasFlexibleArrayMember()) return getIndirectReturnResult(RetTy, State); } // If specified, structs and unions are always indirect. if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) return getIndirectReturnResult(RetTy, State); // Ignore empty structs/unions. if (isEmptyRecord(getContext(), RetTy, true)) return ABIArgInfo::getIgnore(); // Small structures which are register sized are generally returned // in a register. if (shouldReturnTypeInRegister(RetTy, getContext())) { uint64_t Size = getContext().getTypeSize(RetTy); // As a special-case, if the struct is a "single-element" struct, and // the field is of type "float" or "double", return it in a // floating-point register. (MSVC does not apply this special case.) // We apply a similar transformation for pointer types to improve the // quality of the generated IR. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) || SeltTy->hasPointerRepresentation()) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); // FIXME: We should be able to narrow this integer in cases with dead // padding. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); } return getIndirectReturnResult(RetTy, State); } // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } static bool isSSEVectorType(ASTContext &Context, QualType Ty) { return Ty->getAs() && Context.getTypeSize(Ty) == 128; } static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { const RecordType *RT = Ty->getAs(); if (!RT) return 0; const RecordDecl *RD = RT->getDecl(); // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) for (const auto &I : CXXRD->bases()) if (!isRecordWithSSEVectorType(Context, I.getType())) return false; for (const auto *i : RD->fields()) { QualType FT = i->getType(); if (isSSEVectorType(Context, FT)) return true; if (isRecordWithSSEVectorType(Context, FT)) return true; } return false; } unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, unsigned Align) const { // Otherwise, if the alignment is less than or equal to the minimum ABI // alignment, just use the default; the backend will handle this. if (Align <= MinABIStackAlignInBytes) return 0; // Use default alignment. // On non-Darwin, the stack type alignment is always 4. if (!IsDarwinVectorABI) { // Set explicit alignment, since we may need to realign the top. return MinABIStackAlignInBytes; } // Otherwise, if the type contains an SSE vector type, the alignment is 16. if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || isRecordWithSSEVectorType(getContext(), Ty))) return 16; return MinABIStackAlignInBytes; } ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, CCState &State) const { if (!ByVal) { if (State.FreeRegs) { --State.FreeRegs; // Non-byval indirects just use one pointer. if (!IsMCUABI) return getNaturalAlignIndirectInReg(Ty); } return getNaturalAlignIndirect(Ty, false); } // Compute the byval alignment. unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); if (StackAlign == 0) return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); // If the stack alignment is less than the type alignment, realign the // argument. bool Realign = TypeAlign > StackAlign; return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), /*ByVal=*/true, Realign); } X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { const Type *T = isSingleElementStruct(Ty, getContext()); if (!T) T = Ty.getTypePtr(); if (const BuiltinType *BT = T->getAs()) { BuiltinType::Kind K = BT->getKind(); if (K == BuiltinType::Float || K == BuiltinType::Double) return Float; } return Integer; } bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { if (!IsSoftFloatABI) { Class C = classify(Ty); if (C == Float) return false; } unsigned Size = getContext().getTypeSize(Ty); unsigned SizeInRegs = (Size + 31) / 32; if (SizeInRegs == 0) return false; if (!IsMCUABI) { if (SizeInRegs > State.FreeRegs) { State.FreeRegs = 0; return false; } } else { // The MCU psABI allows passing parameters in-reg even if there are // earlier parameters that are passed on the stack. Also, // it does not allow passing >8-byte structs in-register, // even if there are 3 free registers available. if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) return false; } State.FreeRegs -= SizeInRegs; return true; } bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, bool &NeedsPadding) const { // On Windows, aggregates other than HFAs are never passed in registers, and // they do not consume register slots. Homogenous floating-point aggregates // (HFAs) have already been dealt with at this point. if (IsWin32StructABI && isAggregateTypeForABI(Ty)) return false; NeedsPadding = false; InReg = !IsMCUABI; if (!updateFreeRegs(Ty, State)) return false; if (IsMCUABI) return true; if (State.CC == llvm::CallingConv::X86_FastCall || State.CC == llvm::CallingConv::X86_VectorCall || State.CC == llvm::CallingConv::X86_RegCall) { if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) NeedsPadding = true; return false; } return true; } bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { if (!updateFreeRegs(Ty, State)) return false; if (IsMCUABI) return false; if (State.CC == llvm::CallingConv::X86_FastCall || State.CC == llvm::CallingConv::X86_VectorCall || State.CC == llvm::CallingConv::X86_RegCall) { if (getContext().getTypeSize(Ty) > 32) return false; return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || Ty->isReferenceType()); } return true; } ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { // FIXME: Set alignment on indirect arguments. Ty = useFirstFieldIfTransparentUnion(Ty); // Check with the C++ ABI first. const RecordType *RT = Ty->getAs(); if (RT) { CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); if (RAA == CGCXXABI::RAA_Indirect) { return getIndirectResult(Ty, false, State); } else if (RAA == CGCXXABI::RAA_DirectInMemory) { // The field index doesn't matter, we'll fix it up later. return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); } } // Regcall uses the concept of a homogenous vector aggregate, similar // to other targets. const Type *Base = nullptr; uint64_t NumElts = 0; if (State.CC == llvm::CallingConv::X86_RegCall && isHomogeneousAggregate(Ty, Base, NumElts)) { if (State.FreeSSERegs >= NumElts) { State.FreeSSERegs -= NumElts; if (Ty->isBuiltinType() || Ty->isVectorType()) return ABIArgInfo::getDirect(); return ABIArgInfo::getExpand(); } return getIndirectResult(Ty, /*ByVal=*/false, State); } if (isAggregateTypeForABI(Ty)) { // Structures with flexible arrays are always indirect. // FIXME: This should not be byval! if (RT && RT->getDecl()->hasFlexibleArrayMember()) return getIndirectResult(Ty, true, State); // Ignore empty structs/unions on non-Windows. if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); llvm::LLVMContext &LLVMContext = getVMContext(); llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); bool NeedsPadding = false; bool InReg; if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; SmallVector Elements(SizeInRegs, Int32); llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); if (InReg) return ABIArgInfo::getDirectInReg(Result); else return ABIArgInfo::getDirect(Result); } llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; // Expand small (<= 128-bit) record types when we know that the stack layout // of those arguments will match the struct. This is important because the // LLVM backend isn't smart enough to remove byval, which inhibits many // optimizations. // Don't do this for the MCU if there are still free integer registers // (see X86_64 ABI for full explanation). if (getContext().getTypeSize(Ty) <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty)) return ABIArgInfo::getExpandWithPadding( State.CC == llvm::CallingConv::X86_FastCall || State.CC == llvm::CallingConv::X86_VectorCall || State.CC == llvm::CallingConv::X86_RegCall, PaddingType); return getIndirectResult(Ty, true, State); } if (const VectorType *VT = Ty->getAs()) { // On Darwin, some vectors are passed in memory, we handle this by passing // it as an i8/i16/i32/i64. if (IsDarwinVectorABI) { uint64_t Size = getContext().getTypeSize(Ty); if ((Size == 8 || Size == 16 || Size == 32) || (Size == 64 && VT->getNumElements() == 1)) return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); } if (IsX86_MMXType(CGT.ConvertType(Ty))) return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); return ABIArgInfo::getDirect(); } if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); bool InReg = shouldPrimitiveUseInReg(Ty, State); if (Ty->isPromotableIntegerType()) { if (InReg) return ABIArgInfo::getExtendInReg(Ty); return ABIArgInfo::getExtend(Ty); } if (InReg) return ABIArgInfo::getDirectInReg(); return ABIArgInfo::getDirect(); } void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State, bool &UsedInAlloca) const { // Vectorcall x86 works subtly different than in x64, so the format is // a bit different than the x64 version. First, all vector types (not HVAs) // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers. // This differs from the x64 implementation, where the first 6 by INDEX get // registers. // After that, integers AND HVAs are assigned Left to Right in the same pass. // Integers are passed as ECX/EDX if one is available (in order). HVAs will // first take up the remaining YMM/XMM registers. If insufficient registers // remain but an integer register (ECX/EDX) is available, it will be passed // in that, else, on the stack. for (auto &I : FI.arguments()) { // First pass do all the vector types. const Type *Base = nullptr; uint64_t NumElts = 0; const QualType& Ty = I.type; if ((Ty->isVectorType() || Ty->isBuiltinType()) && isHomogeneousAggregate(Ty, Base, NumElts)) { if (State.FreeSSERegs >= NumElts) { State.FreeSSERegs -= NumElts; I.info = ABIArgInfo::getDirect(); } else { I.info = classifyArgumentType(Ty, State); } UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); } } for (auto &I : FI.arguments()) { // Second pass, do the rest! const Type *Base = nullptr; uint64_t NumElts = 0; const QualType& Ty = I.type; bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts); if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) { // Assign true HVAs (non vector/native FP types). if (State.FreeSSERegs >= NumElts) { State.FreeSSERegs -= NumElts; I.info = getDirectX86Hva(); } else { I.info = getIndirectResult(Ty, /*ByVal=*/false, State); } } else if (!IsHva) { // Assign all Non-HVAs, so this will exclude Vector/FP args. I.info = classifyArgumentType(Ty, State); UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); } } } void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { CCState State(FI.getCallingConvention()); if (IsMCUABI) State.FreeRegs = 3; else if (State.CC == llvm::CallingConv::X86_FastCall) State.FreeRegs = 2; else if (State.CC == llvm::CallingConv::X86_VectorCall) { State.FreeRegs = 2; State.FreeSSERegs = 6; } else if (FI.getHasRegParm()) State.FreeRegs = FI.getRegParm(); else if (State.CC == llvm::CallingConv::X86_RegCall) { State.FreeRegs = 5; State.FreeSSERegs = 8; } else State.FreeRegs = DefaultNumRegisterParameters; if (!::classifyReturnType(getCXXABI(), FI, *this)) { FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); } else if (FI.getReturnInfo().isIndirect()) { // The C++ ABI is not aware of register usage, so we have to check if the // return value was sret and put it in a register ourselves if appropriate. if (State.FreeRegs) { --State.FreeRegs; // The sret parameter consumes a register. if (!IsMCUABI) FI.getReturnInfo().setInReg(true); } } // The chain argument effectively gives us another free register. if (FI.isChainCall()) ++State.FreeRegs; bool UsedInAlloca = false; if (State.CC == llvm::CallingConv::X86_VectorCall) { computeVectorCallArgs(FI, State, UsedInAlloca); } else { // If not vectorcall, revert to normal behavior. for (auto &I : FI.arguments()) { I.info = classifyArgumentType(I.type, State); UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); } } // If we needed to use inalloca for any argument, do a second pass and rewrite // all the memory arguments to use inalloca. if (UsedInAlloca) rewriteWithInAlloca(FI); } void X86_32ABIInfo::addFieldToArgStruct(SmallVector &FrameFields, CharUnits &StackOffset, ABIArgInfo &Info, QualType Type) const { // Arguments are always 4-byte-aligned. CharUnits FieldAlign = CharUnits::fromQuantity(4); assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct"); Info = ABIArgInfo::getInAlloca(FrameFields.size()); FrameFields.push_back(CGT.ConvertTypeForMem(Type)); StackOffset += getContext().getTypeSizeInChars(Type); // Insert padding bytes to respect alignment. CharUnits FieldEnd = StackOffset; StackOffset = FieldEnd.alignTo(FieldAlign); if (StackOffset != FieldEnd) { CharUnits NumBytes = StackOffset - FieldEnd; llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); FrameFields.push_back(Ty); } } static bool isArgInAlloca(const ABIArgInfo &Info) { // Leave ignored and inreg arguments alone. switch (Info.getKind()) { case ABIArgInfo::InAlloca: return true; case ABIArgInfo::Indirect: assert(Info.getIndirectByVal()); return true; case ABIArgInfo::Ignore: return false; case ABIArgInfo::Direct: case ABIArgInfo::Extend: if (Info.getInReg()) return false; return true; case ABIArgInfo::Expand: case ABIArgInfo::CoerceAndExpand: // These are aggregate types which are never passed in registers when // inalloca is involved. return true; } llvm_unreachable("invalid enum"); } void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { assert(IsWin32StructABI && "inalloca only supported on win32"); // Build a packed struct type for all of the arguments in memory. SmallVector FrameFields; // The stack alignment is always 4. CharUnits StackAlign = CharUnits::fromQuantity(4); CharUnits StackOffset; CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); // Put 'this' into the struct before 'sret', if necessary. bool IsThisCall = FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; ABIArgInfo &Ret = FI.getReturnInfo(); if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && isArgInAlloca(I->info)) { addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); ++I; } // Put the sret parameter into the inalloca struct if it's in memory. if (Ret.isIndirect() && !Ret.getInReg()) { CanQualType PtrTy = getContext().getPointerType(FI.getReturnType()); addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy); // On Windows, the hidden sret parameter is always returned in eax. Ret.setInAllocaSRet(IsWin32StructABI); } // Skip the 'this' parameter in ecx. if (IsThisCall) ++I; // Put arguments passed in memory into the struct. for (; I != E; ++I) { if (isArgInAlloca(I->info)) addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); } FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, /*isPacked=*/true), StackAlign); } Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { auto TypeInfo = getContext().getTypeInfoInChars(Ty); // x86-32 changes the alignment of certain arguments on the stack. // // Just messing with TypeInfo like this works because we never pass // anything indirectly. TypeInfo.second = CharUnits::fromQuantity( getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, CharUnits::fromQuantity(4), /*AllowHigherAlign*/ true); } bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( const llvm::Triple &Triple, const CodeGenOptions &Opts) { assert(Triple.getArch() == llvm::Triple::x86); switch (Opts.getStructReturnConvention()) { case CodeGenOptions::SRCK_Default: break; case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return return false; case CodeGenOptions::SRCK_InRegs: // -freg-struct-return return true; } if (Triple.isOSDarwin() || Triple.isOSIAMCU()) return true; switch (Triple.getOS()) { case llvm::Triple::DragonFly: case llvm::Triple::FreeBSD: case llvm::Triple::OpenBSD: case llvm::Triple::Win32: return true; default: return false; } } void X86_32TargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { if (GV->isDeclaration()) return; if (const FunctionDecl *FD = dyn_cast_or_null(D)) { if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->addFnAttr("stackrealign"); } if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->setCallingConv(llvm::CallingConv::X86_INTR); } } } bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { CodeGen::CGBuilderTy &Builder = CGF.Builder; llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); // 0-7 are the eight integer registers; the order is different // on Darwin (for EH), but the range is the same. // 8 is %eip. AssignToArrayRange(Builder, Address, Four8, 0, 8); if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { // 12-16 are st(0..4). Not sure why we stop at 4. // These have size 16, which is sizeof(long double) on // platforms with 8-byte alignment for that type. llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); } else { // 9 is %eflags, which doesn't get a size on Darwin for some // reason. Builder.CreateAlignedStore( Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), CharUnits::One()); // 11-16 are st(0..5). Not sure why we stop at 5. // These have size 12, which is sizeof(long double) on // platforms with 4-byte alignment for that type. llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); AssignToArrayRange(Builder, Address, Twelve8, 11, 16); } return false; } //===----------------------------------------------------------------------===// // X86-64 ABI Implementation //===----------------------------------------------------------------------===// namespace { /// The AVX ABI level for X86 targets. enum class X86AVXABILevel { None, AVX, AVX512 }; /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { switch (AVXLevel) { case X86AVXABILevel::AVX512: return 512; case X86AVXABILevel::AVX: return 256; case X86AVXABILevel::None: return 128; } llvm_unreachable("Unknown AVXLevel"); } /// X86_64ABIInfo - The X86_64 ABI information. class X86_64ABIInfo : public SwiftABIInfo { enum Class { Integer = 0, SSE, SSEUp, X87, X87Up, ComplexX87, NoClass, Memory }; /// merge - Implement the X86_64 ABI merging algorithm. /// /// Merge an accumulating classification \arg Accum with a field /// classification \arg Field. /// /// \param Accum - The accumulating classification. This should /// always be either NoClass or the result of a previous merge /// call. In addition, this should never be Memory (the caller /// should just return Memory for the aggregate). static Class merge(Class Accum, Class Field); /// postMerge - Implement the X86_64 ABI post merging algorithm. /// /// Post merger cleanup, reduces a malformed Hi and Lo pair to /// final MEMORY or SSE classes when necessary. /// /// \param AggregateSize - The size of the current aggregate in /// the classification process. /// /// \param Lo - The classification for the parts of the type /// residing in the low word of the containing object. /// /// \param Hi - The classification for the parts of the type /// residing in the higher words of the containing object. /// void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; /// classify - Determine the x86_64 register classes in which the /// given type T should be passed. /// /// \param Lo - The classification for the parts of the type /// residing in the low word of the containing object. /// /// \param Hi - The classification for the parts of the type /// residing in the high word of the containing object. /// /// \param OffsetBase - The bit offset of this type in the /// containing object. Some parameters are classified different /// depending on whether they straddle an eightbyte boundary. /// /// \param isNamedArg - Whether the argument in question is a "named" /// argument, as used in AMD64-ABI 3.5.7. /// /// If a word is unused its result will be NoClass; if a type should /// be passed in Memory then at least the classification of \arg Lo /// will be Memory. /// /// The \arg Lo class will be NoClass iff the argument is ignored. /// /// If the \arg Lo class is ComplexX87, then the \arg Hi class will /// also be ComplexX87. void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, bool isNamedArg) const; llvm::Type *GetByteVectorType(QualType Ty) const; llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, QualType SourceTy, unsigned SourceOffset) const; llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, QualType SourceTy, unsigned SourceOffset) const; /// getIndirectResult - Give a source type \arg Ty, return a suitable result /// such that the argument will be returned in memory. ABIArgInfo getIndirectReturnResult(QualType Ty) const; /// getIndirectResult - Give a source type \arg Ty, return a suitable result /// such that the argument will be passed in memory. /// /// \param freeIntRegs - The number of free integer registers remaining /// available. ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, bool isNamedArg) const; ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, unsigned &NeededSSE) const; ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, unsigned &NeededSSE) const; bool IsIllegalVectorType(QualType Ty) const; /// The 0.98 ABI revision clarified a lot of ambiguities, /// unfortunately in ways that were not always consistent with /// certain previous compilers. In particular, platforms which /// required strict binary compatibility with older versions of GCC /// may need to exempt themselves. bool honorsRevision0_98() const { return !getTarget().getTriple().isOSDarwin(); } /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to /// classify it as INTEGER (for compatibility with older clang compilers). bool classifyIntegerMMXAsSSE() const { // Clang <= 3.8 did not do this. if (getContext().getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver3_8) return false; const llvm::Triple &Triple = getTarget().getTriple(); if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) return false; if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) return false; return true; } X86AVXABILevel AVXLevel; // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on // 64-bit hardware. bool Has64BitPointers; public: X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : SwiftABIInfo(CGT), AVXLevel(AVXLevel), Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { } bool isPassedUsingAVXType(QualType type) const { unsigned neededInt, neededSSE; // The freeIntRegs argument doesn't matter here. ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, /*isNamedArg*/true); if (info.isDirect()) { llvm::Type *ty = info.getCoerceToType(); if (llvm::VectorType *vectorTy = dyn_cast_or_null(ty)) return (vectorTy->getBitWidth() > 128); } return false; } void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool has64BitPointers() const { return Has64BitPointers; } bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return true; } }; /// WinX86_64ABIInfo - The Windows X86_64 ABI information. class WinX86_64ABIInfo : public SwiftABIInfo { public: WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : SwiftABIInfo(CGT), IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool isHomogeneousAggregateBaseType(QualType Ty) const override { // FIXME: Assumes vectorcall is in use. return isX86VectorTypeForVectorCall(getContext(), Ty); } bool isHomogeneousAggregateSmallEnough(const Type *Ty, uint64_t NumMembers) const override { // FIXME: Assumes vectorcall is in use. return isX86VectorCallAggregateSmallEnough(NumMembers); } bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return true; } private: ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, bool IsVectorCall, bool IsRegCall) const; ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const; void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, bool IsVectorCall, bool IsRegCall) const; bool IsMingw64; }; class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { public: X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {} const X86_64ABIInfo &getABIInfo() const { return static_cast(TargetCodeGenInfo::getABIInfo()); } int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { return 7; } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override { llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); // 0-15 are the 16 integer registers. // 16 is %rip. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); return false; } llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, StringRef Constraint, llvm::Type* Ty) const override { return X86AdjustInlineAsmType(CGF, Constraint, Ty); } bool isNoProtoCallVariadic(const CallArgList &args, const FunctionNoProtoType *fnType) const override { // The default CC on x86-64 sets %al to the number of SSA // registers used, and GCC sets this when calling an unprototyped // function, so we override the default behavior. However, don't do // that when AVX types are involved: the ABI explicitly states it is // undefined, and it doesn't work in practice because of how the ABI // defines varargs anyway. if (fnType->getCallConv() == CC_C) { bool HasAVXType = false; for (CallArgList::const_iterator it = args.begin(), ie = args.end(); it != ie; ++it) { if (getABIInfo().isPassedUsingAVXType(it->Ty)) { HasAVXType = true; break; } } if (!HasAVXType) return true; } return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); } llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { unsigned Sig = (0xeb << 0) | // jmp rel8 (0x06 << 8) | // .+0x08 ('v' << 16) | ('2' << 24); return llvm::ConstantInt::get(CGM.Int32Ty, Sig); } void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { if (GV->isDeclaration()) return; if (const FunctionDecl *FD = dyn_cast_or_null(D)) { if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->addFnAttr("stackrealign"); } if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->setCallingConv(llvm::CallingConv::X86_INTR); } } } }; class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo { public: PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : X86_64TargetCodeGenInfo(CGT, AVXLevel) {} void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const override { Opt = "\01"; // If the argument contains a space, enclose it in quotes. if (Lib.find(" ") != StringRef::npos) Opt += "\"" + Lib.str() + "\""; else Opt += Lib; } }; static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { // If the argument does not end in .lib, automatically add the suffix. // If the argument contains a space, enclose it in quotes. // This matches the behavior of MSVC. bool Quote = (Lib.find(" ") != StringRef::npos); std::string ArgStr = Quote ? "\"" : ""; ArgStr += Lib; if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) ArgStr += ".lib"; ArgStr += Quote ? "\"" : ""; return ArgStr; } class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { public: WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, unsigned NumRegisterParameters) : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, NumRegisterParameters, false) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override; void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const override { Opt = "/DEFAULTLIB:"; Opt += qualifyWindowsLibrary(Lib); } void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString<32> &Opt) const override { Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; } }; static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) { if (llvm::Function *Fn = dyn_cast_or_null(GV)) { if (CGM.getCodeGenOpts().StackProbeSize != 4096) Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); if (CGM.getCodeGenOpts().NoStackArgProbe) Fn->addFnAttr("no-stack-arg-probe"); } } void WinX86_32TargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); if (GV->isDeclaration()) return; addStackProbeTargetAttributes(D, GV, CGM); } class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { public: WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override; int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { return 7; } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override { llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); // 0-15 are the 16 integer registers. // 16 is %rip. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); return false; } void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const override { Opt = "/DEFAULTLIB:"; Opt += qualifyWindowsLibrary(Lib); } void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString<32> &Opt) const override { Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; } }; void WinX86_64TargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); if (GV->isDeclaration()) return; if (const FunctionDecl *FD = dyn_cast_or_null(D)) { if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->addFnAttr("stackrealign"); } if (FD->hasAttr()) { llvm::Function *Fn = cast(GV); Fn->setCallingConv(llvm::CallingConv::X86_INTR); } } addStackProbeTargetAttributes(D, GV, CGM); } } void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const { // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: // // (a) If one of the classes is Memory, the whole argument is passed in // memory. // // (b) If X87UP is not preceded by X87, the whole argument is passed in // memory. // // (c) If the size of the aggregate exceeds two eightbytes and the first // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole // argument is passed in memory. NOTE: This is necessary to keep the // ABI working for processors that don't support the __m256 type. // // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. // // Some of these are enforced by the merging logic. Others can arise // only with unions; for example: // union { _Complex double; unsigned; } // // Note that clauses (b) and (c) were added in 0.98. // if (Hi == Memory) Lo = Memory; if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) Lo = Memory; if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) Lo = Memory; if (Hi == SSEUp && Lo != SSE) Hi = SSE; } X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is // classified recursively so that always two fields are // considered. The resulting class is calculated according to // the classes of the fields in the eightbyte: // // (a) If both classes are equal, this is the resulting class. // // (b) If one of the classes is NO_CLASS, the resulting class is // the other class. // // (c) If one of the classes is MEMORY, the result is the MEMORY // class. // // (d) If one of the classes is INTEGER, the result is the // INTEGER. // // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, // MEMORY is used as class. // // (f) Otherwise class SSE is used. // Accum should never be memory (we should have returned) or // ComplexX87 (because this cannot be passed in a structure). assert((Accum != Memory && Accum != ComplexX87) && "Invalid accumulated classification during merge."); if (Accum == Field || Field == NoClass) return Accum; if (Field == Memory) return Memory; if (Accum == NoClass) return Field; if (Accum == Integer || Field == Integer) return Integer; if (Field == X87 || Field == X87Up || Field == ComplexX87 || Accum == X87 || Accum == X87Up) return Memory; return SSE; } void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo, Class &Hi, bool isNamedArg) const { // FIXME: This code can be simplified by introducing a simple value class for // Class pairs with appropriate constructor methods for the various // situations. // FIXME: Some of the split computations are wrong; unaligned vectors // shouldn't be passed in registers for example, so there is no chance they // can straddle an eightbyte. Verify & simplify. Lo = Hi = NoClass; Class &Current = OffsetBase < 64 ? Lo : Hi; Current = Memory; if (const BuiltinType *BT = Ty->getAs()) { BuiltinType::Kind k = BT->getKind(); if (k == BuiltinType::Void) { Current = NoClass; } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { Lo = Integer; Hi = Integer; } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { Current = Integer; } else if (k == BuiltinType::Float || k == BuiltinType::Double) { Current = SSE; } else if (k == BuiltinType::LongDouble) { const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); if (LDF == &llvm::APFloat::IEEEquad()) { Lo = SSE; Hi = SSEUp; } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { Lo = X87; Hi = X87Up; } else if (LDF == &llvm::APFloat::IEEEdouble()) { Current = SSE; } else llvm_unreachable("unexpected long double representation!"); } // FIXME: _Decimal32 and _Decimal64 are SSE. // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). return; } if (const EnumType *ET = Ty->getAs()) { // Classify the underlying integer type. classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); return; } if (Ty->hasPointerRepresentation()) { Current = Integer; return; } if (Ty->isMemberPointerType()) { if (Ty->isMemberFunctionPointerType()) { if (Has64BitPointers) { // If Has64BitPointers, this is an {i64, i64}, so classify both // Lo and Hi now. Lo = Hi = Integer; } else { // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that // straddles an eightbyte boundary, Hi should be classified as well. uint64_t EB_FuncPtr = (OffsetBase) / 64; uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; if (EB_FuncPtr != EB_ThisAdj) { Lo = Hi = Integer; } else { Current = Integer; } } } else { Current = Integer; } return; } if (const VectorType *VT = Ty->getAs()) { uint64_t Size = getContext().getTypeSize(VT); if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { // gcc passes the following as integer: // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> // 2 bytes - <2 x char>, <1 x short> // 1 byte - <1 x char> Current = Integer; // If this type crosses an eightbyte boundary, it should be // split. uint64_t EB_Lo = (OffsetBase) / 64; uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; if (EB_Lo != EB_Hi) Hi = Lo; } else if (Size == 64) { QualType ElementType = VT->getElementType(); // gcc passes <1 x double> in memory. :( if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) return; // gcc passes <1 x long long> as SSE but clang used to unconditionally // pass them as integer. For platforms where clang is the de facto // platform compiler, we must continue to use integer. if (!classifyIntegerMMXAsSSE() && (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || ElementType->isSpecificBuiltinType(BuiltinType::Long) || ElementType->isSpecificBuiltinType(BuiltinType::ULong))) Current = Integer; else Current = SSE; // If this type crosses an eightbyte boundary, it should be // split. if (OffsetBase && OffsetBase != 64) Hi = Lo; } else if (Size == 128 || (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { // Arguments of 256-bits are split into four eightbyte chunks. The // least significant one belongs to class SSE and all the others to class // SSEUP. The original Lo and Hi design considers that types can't be // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. // This design isn't correct for 256-bits, but since there're no cases // where the upper parts would need to be inspected, avoid adding // complexity and just consider Hi to match the 64-256 part. // // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in // registers if they are "named", i.e. not part of the "..." of a // variadic function. // // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are // split into eight eightbyte chunks, one SSE and seven SSEUP. Lo = SSE; Hi = SSEUp; } return; } if (const ComplexType *CT = Ty->getAs()) { QualType ET = getContext().getCanonicalType(CT->getElementType()); uint64_t Size = getContext().getTypeSize(Ty); if (ET->isIntegralOrEnumerationType()) { if (Size <= 64) Current = Integer; else if (Size <= 128) Lo = Hi = Integer; } else if (ET == getContext().FloatTy) { Current = SSE; } else if (ET == getContext().DoubleTy) { Lo = Hi = SSE; } else if (ET == getContext().LongDoubleTy) { const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); if (LDF == &llvm::APFloat::IEEEquad()) Current = Memory; else if (LDF == &llvm::APFloat::x87DoubleExtended()) Current = ComplexX87; else if (LDF == &llvm::APFloat::IEEEdouble()) Lo = Hi = SSE; else llvm_unreachable("unexpected long double representation!"); } // If this complex type crosses an eightbyte boundary then it // should be split. uint64_t EB_Real = (OffsetBase) / 64; uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; if (Hi == NoClass && EB_Real != EB_Imag) Hi = Lo; return; } if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { // Arrays are treated like structures. uint64_t Size = getContext().getTypeSize(Ty); // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger // than eight eightbytes, ..., it has class MEMORY. if (Size > 512) return; // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned // fields, it has class MEMORY. // // Only need to check alignment of array base. if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) return; // Otherwise implement simplified merge. We could be smarter about // this, but it isn't worth it and would be harder to verify. Current = NoClass; uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); uint64_t ArraySize = AT->getSize().getZExtValue(); // The only case a 256-bit wide vector could be used is when the array // contains a single 256-bit element. Since Lo and Hi logic isn't extended // to work for sizes wider than 128, early check and fallback to memory. // if (Size > 128 && (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) return; for (uint64_t i=0, Offset=OffsetBase; igetElementType(), Offset, FieldLo, FieldHi, isNamedArg); Lo = merge(Lo, FieldLo); Hi = merge(Hi, FieldHi); if (Lo == Memory || Hi == Memory) break; } postMerge(Size, Lo, Hi); assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); return; } if (const RecordType *RT = Ty->getAs()) { uint64_t Size = getContext().getTypeSize(Ty); // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger // than eight eightbytes, ..., it has class MEMORY. if (Size > 512) return; // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial // copy constructor or a non-trivial destructor, it is passed by invisible // reference. if (getRecordArgABI(RT, getCXXABI())) return; const RecordDecl *RD = RT->getDecl(); // Assume variable sized types are passed in memory. if (RD->hasFlexibleArrayMember()) return; const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); // Reset Lo class, this will be recomputed. Current = NoClass; // If this is a C++ record, classify the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { for (const auto &I : CXXRD->bases()) { assert(!I.isVirtual() && !I.getType()->isDependentType() && "Unexpected base class!"); const CXXRecordDecl *Base = cast(I.getType()->getAs()->getDecl()); // Classify this field. // // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a // single eightbyte, each is classified separately. Each eightbyte gets // initialized to class NO_CLASS. Class FieldLo, FieldHi; uint64_t Offset = OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); Lo = merge(Lo, FieldLo); Hi = merge(Hi, FieldHi); if (Lo == Memory || Hi == Memory) { postMerge(Size, Lo, Hi); return; } } } // Classify the fields one at a time, merging the results. unsigned idx = 0; for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i, ++idx) { uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); bool BitField = i->isBitField(); // Ignore padding bit-fields. if (BitField && i->isUnnamedBitfield()) continue; // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than // four eightbytes, or it contains unaligned fields, it has class MEMORY. // // The only case a 256-bit wide vector could be used is when the struct // contains a single 256-bit element. Since Lo and Hi logic isn't extended // to work for sizes wider than 128, early check and fallback to memory. // if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || Size > getNativeVectorSizeForAVXABI(AVXLevel))) { Lo = Memory; postMerge(Size, Lo, Hi); return; } // Note, skip this test for bit-fields, see below. if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { Lo = Memory; postMerge(Size, Lo, Hi); return; } // Classify this field. // // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate // exceeds a single eightbyte, each is classified // separately. Each eightbyte gets initialized to class // NO_CLASS. Class FieldLo, FieldHi; // Bit-fields require special handling, they do not force the // structure to be passed in memory even if unaligned, and // therefore they can straddle an eightbyte. if (BitField) { assert(!i->isUnnamedBitfield()); uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); uint64_t Size = i->getBitWidthValue(getContext()); uint64_t EB_Lo = Offset / 64; uint64_t EB_Hi = (Offset + Size - 1) / 64; if (EB_Lo) { assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); FieldLo = NoClass; FieldHi = Integer; } else { FieldLo = Integer; FieldHi = EB_Hi ? Integer : NoClass; } } else classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); Lo = merge(Lo, FieldLo); Hi = merge(Hi, FieldHi); if (Lo == Memory || Hi == Memory) break; } postMerge(Size, Lo, Hi); } } ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { // If this is a scalar LLVM value then assume LLVM will pass it in the right // place naturally. if (!isAggregateTypeForABI(Ty)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } return getNaturalAlignIndirect(Ty); } bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { if (const VectorType *VecTy = Ty->getAs()) { uint64_t Size = getContext().getTypeSize(VecTy); unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); if (Size <= 64 || Size > LargestVector) return true; } return false; } ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, unsigned freeIntRegs) const { // If this is a scalar LLVM value then assume LLVM will pass it in the right // place naturally. // // This assumption is optimistic, as there could be free registers available // when we need to pass this argument in memory, and LLVM could try to pass // the argument in the free register. This does not seem to happen currently, // but this code would be much safer if we could mark the argument with // 'onstack'. See PR12193. if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // Compute the byval alignment. We specify the alignment of the byval in all // cases so that the mid-level optimizer knows the alignment of the byval. unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); // Attempt to avoid passing indirect results using byval when possible. This // is important for good codegen. // // We do this by coercing the value into a scalar type which the backend can // handle naturally (i.e., without using byval). // // For simplicity, we currently only do this when we have exhausted all of the // free integer registers. Doing this when there are free integer registers // would require more care, as we would have to ensure that the coerced value // did not claim the unused register. That would require either reording the // arguments to the function (so that any subsequent inreg values came first), // or only doing this optimization when there were no following arguments that // might be inreg. // // We currently expect it to be rare (particularly in well written code) for // arguments to be passed on the stack when there are still free integer // registers available (this would typically imply large structs being passed // by value), so this seems like a fair tradeoff for now. // // We can revisit this if the backend grows support for 'onstack' parameter // attributes. See PR12193. if (freeIntRegs == 0) { uint64_t Size = getContext().getTypeSize(Ty); // If this type fits in an eightbyte, coerce it into the matching integral // type, which will end up on the stack (with alignment 8). if (Align == 8 && Size <= 64) return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); } return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); } /// The ABI specifies that a value should be passed in a full vector XMM/YMM /// register. Pick an LLVM IR type that will be passed as a vector register. llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { // Wrapper structs/arrays that only contain vectors are passed just like // vectors; strip them off if present. if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) Ty = QualType(InnerTy, 0); llvm::Type *IRType = CGT.ConvertType(Ty); if (isa(IRType) || IRType->getTypeID() == llvm::Type::FP128TyID) return IRType; // We couldn't find the preferred IR vector type for 'Ty'. uint64_t Size = getContext().getTypeSize(Ty); assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); // Return a LLVM IR vector type based on the size of 'Ty'. return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), Size / 64); } /// BitsContainNoUserData - Return true if the specified [start,end) bit range /// is known to either be off the end of the specified type or being in /// alignment padding. The user type specified is known to be at most 128 bits /// in size, and have passed through X86_64ABIInfo::classify with a successful /// classification that put one of the two halves in the INTEGER class. /// /// It is conservatively correct to return false. static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, unsigned EndBit, ASTContext &Context) { // If the bytes being queried are off the end of the type, there is no user // data hiding here. This handles analysis of builtins, vectors and other // types that don't contain interesting padding. unsigned TySize = (unsigned)Context.getTypeSize(Ty); if (TySize <= StartBit) return true; if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); // Check each element to see if the element overlaps with the queried range. for (unsigned i = 0; i != NumElts; ++i) { // If the element is after the span we care about, then we're done.. unsigned EltOffset = i*EltSize; if (EltOffset >= EndBit) break; unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; if (!BitsContainNoUserData(AT->getElementType(), EltStart, EndBit-EltOffset, Context)) return false; } // If it overlaps no elements, then it is safe to process as padding. return true; } if (const RecordType *RT = Ty->getAs()) { const RecordDecl *RD = RT->getDecl(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { for (const auto &I : CXXRD->bases()) { assert(!I.isVirtual() && !I.getType()->isDependentType() && "Unexpected base class!"); const CXXRecordDecl *Base = cast(I.getType()->getAs()->getDecl()); // If the base is after the span we care about, ignore it. unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); if (BaseOffset >= EndBit) continue; unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; if (!BitsContainNoUserData(I.getType(), BaseStart, EndBit-BaseOffset, Context)) return false; } } // Verify that no field has data that overlaps the region of interest. Yes // this could be sped up a lot by being smarter about queried fields, // however we're only looking at structs up to 16 bytes, so we don't care // much. unsigned idx = 0; for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i, ++idx) { unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); // If we found a field after the region we care about, then we're done. if (FieldOffset >= EndBit) break; unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, Context)) return false; } // If nothing in this record overlapped the area of interest, then we're // clean. return true; } return false; } /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a /// float member at the specified offset. For example, {int,{float}} has a /// float at offset 4. It is conservatively correct for this routine to return /// false. static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, const llvm::DataLayout &TD) { // Base case if we find a float. if (IROffset == 0 && IRType->isFloatTy()) return true; // If this is a struct, recurse into the field at the specified offset. if (llvm::StructType *STy = dyn_cast(IRType)) { const llvm::StructLayout *SL = TD.getStructLayout(STy); unsigned Elt = SL->getElementContainingOffset(IROffset); IROffset -= SL->getElementOffset(Elt); return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); } // If this is an array, recurse into the field at the specified offset. if (llvm::ArrayType *ATy = dyn_cast(IRType)) { llvm::Type *EltTy = ATy->getElementType(); unsigned EltSize = TD.getTypeAllocSize(EltTy); IROffset -= IROffset/EltSize*EltSize; return ContainsFloatAtOffset(EltTy, IROffset, TD); } return false; } /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the /// low 8 bytes of an XMM register, corresponding to the SSE class. llvm::Type *X86_64ABIInfo:: GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, QualType SourceTy, unsigned SourceOffset) const { // The only three choices we have are either double, <2 x float>, or float. We // pass as float if the last 4 bytes is just padding. This happens for // structs that contain 3 floats. if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, SourceOffset*8+64, getContext())) return llvm::Type::getFloatTy(getVMContext()); // We want to pass as <2 x float> if the LLVM IR type contains a float at // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the // case. if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); return llvm::Type::getDoubleTy(getVMContext()); } /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in /// an 8-byte GPR. This means that we either have a scalar or we are talking /// about the high or low part of an up-to-16-byte struct. This routine picks /// the best LLVM IR type to represent this, which may be i64 or may be anything /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, /// etc). /// /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for /// the source type. IROffset is an offset in bytes into the LLVM IR type that /// the 8-byte value references. PrefType may be null. /// /// SourceTy is the source-level type for the entire argument. SourceOffset is /// an offset into this that we're processing (which is always either 0 or 8). /// llvm::Type *X86_64ABIInfo:: GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, QualType SourceTy, unsigned SourceOffset) const { // If we're dealing with an un-offset LLVM IR type, then it means that we're // returning an 8-byte unit starting with it. See if we can safely use it. if (IROffset == 0) { // Pointers and int64's always fill the 8-byte unit. if ((isa(IRType) && Has64BitPointers) || IRType->isIntegerTy(64)) return IRType; // If we have a 1/2/4-byte integer, we can use it only if the rest of the // goodness in the source type is just tail padding. This is allowed to // kick in for struct {double,int} on the int, but not on // struct{double,int,int} because we wouldn't return the second int. We // have to do this analysis on the source type because we can't depend on // unions being lowered a specific way etc. if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || IRType->isIntegerTy(32) || (isa(IRType) && !Has64BitPointers)) { unsigned BitWidth = isa(IRType) ? 32 : cast(IRType)->getBitWidth(); if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, SourceOffset*8+64, getContext())) return IRType; } } if (llvm::StructType *STy = dyn_cast(IRType)) { // If this is a struct, recurse into the field at the specified offset. const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); if (IROffset < SL->getSizeInBytes()) { unsigned FieldIdx = SL->getElementContainingOffset(IROffset); IROffset -= SL->getElementOffset(FieldIdx); return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, SourceTy, SourceOffset); } } if (llvm::ArrayType *ATy = dyn_cast(IRType)) { llvm::Type *EltTy = ATy->getElementType(); unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); unsigned EltOffset = IROffset/EltSize*EltSize; return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, SourceOffset); } // Okay, we don't have any better idea of what to pass, so we pass this in an // integer register that isn't too big to fit the rest of the struct. unsigned TySizeInBytes = (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); assert(TySizeInBytes != SourceOffset && "Empty field?"); // It is always safe to classify this as an integer type up to i64 that // isn't larger than the structure. return llvm::IntegerType::get(getVMContext(), std::min(TySizeInBytes-SourceOffset, 8U)*8); } /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally /// be used as elements of a two register pair to pass or return, return a /// first class aggregate to represent them. For example, if the low part of /// a by-value argument should be passed as i32* and the high part as float, /// return {i32*, float}. static llvm::Type * GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, const llvm::DataLayout &TD) { // In order to correctly satisfy the ABI, we need to the high part to start // at offset 8. If the high and low parts we inferred are both 4-byte types // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have // the second element at offset 8. Check for this: unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); unsigned HiAlign = TD.getABITypeAlignment(Hi); unsigned HiStart = llvm::alignTo(LoSize, HiAlign); assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); // To handle this, we have to increase the size of the low part so that the // second element will start at an 8 byte offset. We can't increase the size // of the second element because it might make us access off the end of the // struct. if (HiStart != 8) { // There are usually two sorts of types the ABI generation code can produce // for the low part of a pair that aren't 8 bytes in size: float or // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and // NaCl). // Promote these to a larger type. if (Lo->isFloatTy()) Lo = llvm::Type::getDoubleTy(Lo->getContext()); else { assert((Lo->isIntegerTy() || Lo->isPointerTy()) && "Invalid/unknown lo type"); Lo = llvm::Type::getInt64Ty(Lo->getContext()); } } llvm::StructType *Result = llvm::StructType::get(Lo, Hi); // Verify that the second element is at an 8-byte offset. assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && "Invalid x86-64 argument pair!"); return Result; } ABIArgInfo X86_64ABIInfo:: classifyReturnType(QualType RetTy) const { // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the // classification algorithm. X86_64ABIInfo::Class Lo, Hi; classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); // Check some invariants. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); llvm::Type *ResType = nullptr; switch (Lo) { case NoClass: if (Hi == NoClass) return ABIArgInfo::getIgnore(); // If the low part is just padding, it takes no register, leave ResType // null. assert((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part"); break; case SSEUp: case X87Up: llvm_unreachable("Invalid classification for lo word."); // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via // hidden argument. case Memory: return getIndirectReturnResult(RetTy); // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next // available register of the sequence %rax, %rdx is used. case Integer: ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); // If we have a sign or zero extended integer, make sure to return Extend // so that the parameter gets the right LLVM IR attributes. if (Hi == NoClass && isa(ResType)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); if (RetTy->isIntegralOrEnumerationType() && RetTy->isPromotableIntegerType()) return ABIArgInfo::getExtend(RetTy); } break; // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next // available SSE register of the sequence %xmm0, %xmm1 is used. case SSE: ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); break; // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is // returned on the X87 stack in %st0 as 80-bit x87 number. case X87: ResType = llvm::Type::getX86_FP80Ty(getVMContext()); break; // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real // part of the value is returned in %st0 and the imaginary part in // %st1. case ComplexX87: assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), llvm::Type::getX86_FP80Ty(getVMContext())); break; } llvm::Type *HighPart = nullptr; switch (Hi) { // Memory was handled previously and X87 should // never occur as a hi class. case Memory: case X87: llvm_unreachable("Invalid classification for hi word."); case ComplexX87: // Previously handled. case NoClass: break; case Integer: HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); if (Lo == NoClass) // Return HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); break; case SSE: HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); if (Lo == NoClass) // Return HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); break; // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte // is passed in the next available eightbyte chunk if the last used // vector register. // // SSEUP should always be preceded by SSE, just widen. case SSEUp: assert(Lo == SSE && "Unexpected SSEUp classification."); ResType = GetByteVectorType(RetTy); break; // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is // returned together with the previous X87 value in %st0. case X87Up: // If X87Up is preceded by X87, we don't need to do // anything. However, in some cases with unions it may not be // preceded by X87. In such situations we follow gcc and pass the // extra bits in an SSE reg. if (Lo != X87) { HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); if (Lo == NoClass) // Return HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); } break; } // If a high part was specified, merge it together with the low part. It is // known to pass in the high eightbyte of the result. We do this by forming a // first class struct aggregate with the high and low part: {low, high} if (HighPart) ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); return ABIArgInfo::getDirect(ResType); } ABIArgInfo X86_64ABIInfo::classifyArgumentType( QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, bool isNamedArg) const { Ty = useFirstFieldIfTransparentUnion(Ty); X86_64ABIInfo::Class Lo, Hi; classify(Ty, 0, Lo, Hi, isNamedArg); // Check some invariants. // FIXME: Enforce these by construction. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); neededInt = 0; neededSSE = 0; llvm::Type *ResType = nullptr; switch (Lo) { case NoClass: if (Hi == NoClass) return ABIArgInfo::getIgnore(); // If the low part is just padding, it takes no register, leave ResType // null. assert((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part"); break; // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument // on the stack. case Memory: // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or // COMPLEX_X87, it is passed in memory. case X87: case ComplexX87: if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) ++neededInt; return getIndirectResult(Ty, freeIntRegs); case SSEUp: case X87Up: llvm_unreachable("Invalid classification for lo word."); // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 // and %r9 is used. case Integer: ++neededInt; // Pick an 8-byte type based on the preferred type. ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); // If we have a sign or zero extended integer, make sure to return Extend // so that the parameter gets the right LLVM IR attributes. if (Hi == NoClass && isa(ResType)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); if (Ty->isIntegralOrEnumerationType() && Ty->isPromotableIntegerType()) return ABIArgInfo::getExtend(Ty); } break; // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next // available SSE register is used, the registers are taken in the // order from %xmm0 to %xmm7. case SSE: { llvm::Type *IRType = CGT.ConvertType(Ty); ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); ++neededSSE; break; } } llvm::Type *HighPart = nullptr; switch (Hi) { // Memory was handled previously, ComplexX87 and X87 should // never occur as hi classes, and X87Up must be preceded by X87, // which is passed in memory. case Memory: case X87: case ComplexX87: llvm_unreachable("Invalid classification for hi word."); case NoClass: break; case Integer: ++neededInt; // Pick an 8-byte type based on the preferred type. HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); if (Lo == NoClass) // Pass HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); break; // X87Up generally doesn't occur here (long double is passed in // memory), except in situations involving unions. case X87Up: case SSE: HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); if (Lo == NoClass) // Pass HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); ++neededSSE; break; // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the // eightbyte is passed in the upper half of the last used SSE // register. This only happens when 128-bit vectors are passed. case SSEUp: assert(Lo == SSE && "Unexpected SSEUp classification"); ResType = GetByteVectorType(Ty); break; } // If a high part was specified, merge it together with the low part. It is // known to pass in the high eightbyte of the result. We do this by forming a // first class struct aggregate with the high and low part: {low, high} if (HighPart) ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); return ABIArgInfo::getDirect(ResType); } ABIArgInfo X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, unsigned &NeededSSE) const { auto RT = Ty->getAs(); assert(RT && "classifyRegCallStructType only valid with struct types"); if (RT->getDecl()->hasFlexibleArrayMember()) return getIndirectReturnResult(Ty); // Sum up bases if (auto CXXRD = dyn_cast(RT->getDecl())) { if (CXXRD->isDynamicClass()) { NeededInt = NeededSSE = 0; return getIndirectReturnResult(Ty); } for (const auto &I : CXXRD->bases()) if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) .isIndirect()) { NeededInt = NeededSSE = 0; return getIndirectReturnResult(Ty); } } // Sum up members for (const auto *FD : RT->getDecl()->fields()) { if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) .isIndirect()) { NeededInt = NeededSSE = 0; return getIndirectReturnResult(Ty); } } else { unsigned LocalNeededInt, LocalNeededSSE; if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, LocalNeededSSE, true) .isIndirect()) { NeededInt = NeededSSE = 0; return getIndirectReturnResult(Ty); } NeededInt += LocalNeededInt; NeededSSE += LocalNeededSSE; } } return ABIArgInfo::getDirect(); } ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt, unsigned &NeededSSE) const { NeededInt = 0; NeededSSE = 0; return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); } void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { const unsigned CallingConv = FI.getCallingConvention(); // It is possible to force Win64 calling convention on any x86_64 target by // using __attribute__((ms_abi)). In such case to correctly emit Win64 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. if (CallingConv == llvm::CallingConv::Win64) { WinX86_64ABIInfo Win64ABIInfo(CGT); Win64ABIInfo.computeInfo(FI); return; } bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; // Keep track of the number of assigned registers. unsigned FreeIntRegs = IsRegCall ? 11 : 6; unsigned FreeSSERegs = IsRegCall ? 16 : 8; unsigned NeededInt, NeededSSE; if (!::classifyReturnType(getCXXABI(), FI, *this)) { if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && !FI.getReturnType()->getTypePtr()->isUnionType()) { FI.getReturnInfo() = classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { FreeIntRegs -= NeededInt; FreeSSERegs -= NeededSSE; } else { FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); } } else if (IsRegCall && FI.getReturnType()->getAs()) { // Complex Long Double Type is passed in Memory when Regcall // calling convention is used. const ComplexType *CT = FI.getReturnType()->getAs(); if (getContext().getCanonicalType(CT->getElementType()) == getContext().LongDoubleTy) FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); } else FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); } // If the return value is indirect, then the hidden argument is consuming one // integer register. if (FI.getReturnInfo().isIndirect()) --FreeIntRegs; // The chain argument effectively gives us another free register. if (FI.isChainCall()) ++FreeIntRegs; unsigned NumRequiredArgs = FI.getNumRequiredArgs(); // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers // get assigned (in left-to-right order) for passing as follows... unsigned ArgNo = 0; for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it, ++ArgNo) { bool IsNamedArg = ArgNo < NumRequiredArgs; if (IsRegCall && it->type->isStructureOrClassType()) it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); else it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, NeededSSE, IsNamedArg); // AMD64-ABI 3.2.3p3: If there are no registers available for any // eightbyte of an argument, the whole argument is passed on the // stack. If registers have already been assigned for some // eightbytes of such an argument, the assignments get reverted. if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { FreeIntRegs -= NeededInt; FreeSSERegs -= NeededSSE; } else { it->info = getIndirectResult(it->type, FreeIntRegs); } } } static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) { Address overflow_arg_area_p = CGF.Builder.CreateStructGEP( VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p"); llvm::Value *overflow_arg_area = CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 // byte boundary if alignment needed by type exceeds 8 byte boundary. // It isn't stated explicitly in the standard, but in practice we use // alignment greater than 16 where necessary. CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); if (Align > CharUnits::fromQuantity(8)) { overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, Align); } // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); llvm::Value *Res = CGF.Builder.CreateBitCast(overflow_arg_area, llvm::PointerType::getUnqual(LTy)); // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: // l->overflow_arg_area + sizeof(type). // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to // an 8 byte boundary. uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, "overflow_arg_area.next"); CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. return Address(Res, Align); } Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { // Assume that va_list type is correct; should be pointer to LLVM type: // struct { // i32 gp_offset; // i32 fp_offset; // i8* overflow_arg_area; // i8* reg_save_area; // }; unsigned neededInt, neededSSE; Ty = getContext().getCanonicalType(Ty); ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, /*isNamedArg*/false); // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed // in the registers. If not go to step 7. if (!neededInt && !neededSSE) return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of // general purpose registers needed to pass type and num_fp to hold // the number of floating point registers needed. // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into // registers. In the case: l->gp_offset > 48 - num_gp * 8 or // l->fp_offset > 304 - num_fp * 16 go to step 7. // // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of // register save space). llvm::Value *InRegs = nullptr; Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; if (neededInt) { gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(), "gp_offset_p"); gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); } if (neededSSE) { fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4), "fp_offset_p"); fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); llvm::Value *FitsInFP = llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; } llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); // Emit code to load the value if it was passed in registers. CGF.EmitBlock(InRegBlock); // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with // an offset of l->gp_offset and/or l->fp_offset. This may require // copying to a temporary location in case the parameter is passed // in different register classes or requires an alignment greater // than 8 for general purpose registers and 16 for XMM registers. // // FIXME: This really results in shameful code when we end up needing to // collect arguments from different places; often what should result in a // simple assembling of a structure from scattered addresses has many more // loads than necessary. Can we clean this up? llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)), "reg_save_area"); Address RegAddr = Address::invalid(); if (neededInt && neededSSE) { // FIXME: Cleanup. assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); llvm::StructType *ST = cast(AI.getCoerceToType()); Address Tmp = CGF.CreateMemTemp(Ty); Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); llvm::Type *TyLo = ST->getElementType(0); llvm::Type *TyHi = ST->getElementType(1); assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && "Unexpected ABI info for mixed regs"); llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; // Copy the first element. // FIXME: Our choice of alignment here and below is probably pessimistic. llvm::Value *V = CGF.Builder.CreateAlignedLoad( TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero())); // Copy the second element. V = CGF.Builder.CreateAlignedLoad( TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); CharUnits Offset = CharUnits::fromQuantity( getDataLayout().getStructLayout(ST)->getElementOffset(1)); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset)); RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); } else if (neededInt) { RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), CharUnits::fromQuantity(8)); RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); // Copy to a temporary if necessary to ensure the appropriate alignment. std::pair SizeAlign = getContext().getTypeInfoInChars(Ty); uint64_t TySize = SizeAlign.first.getQuantity(); CharUnits TyAlign = SizeAlign.second; // Copy into a temporary if the type is more aligned than the // register save area. if (TyAlign.getQuantity() > 8) { Address Tmp = CGF.CreateMemTemp(Ty); CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); RegAddr = Tmp; } } else if (neededSSE == 1) { RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), CharUnits::fromQuantity(16)); RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); } else { assert(neededSSE == 2 && "Invalid number of needed registers!"); // SSE registers are spaced 16 bytes apart in the register save // area, we need to collect the two eightbytes together. // The ABI isn't explicit about this, but it seems reasonable // to assume that the slots are 16-byte aligned, since the stack is // naturally 16-byte aligned and the prologue is expected to store // all the SSE registers to the RSA. Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), CharUnits::fromQuantity(16)); Address RegAddrHi = CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, CharUnits::fromQuantity(16)); llvm::Type *ST = AI.canHaveCoerceToType() ? AI.getCoerceToType() : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); llvm::Value *V; Address Tmp = CGF.CreateMemTemp(Ty); Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( RegAddrLo, ST->getStructElementType(0))); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero())); V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( RegAddrHi, ST->getStructElementType(1))); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8))); RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); } // AMD64-ABI 3.5.7p5: Step 5. Set: // l->gp_offset = l->gp_offset + num_gp * 8 // l->fp_offset = l->fp_offset + num_fp * 16. if (neededInt) { llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), gp_offset_p); } if (neededSSE) { llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), fp_offset_p); } CGF.EmitBranch(ContBlock); // Emit code to load the value if it was passed in memory. CGF.EmitBlock(InMemBlock); Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); // Return the appropriate result. CGF.EmitBlock(ContBlock); Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, "vaarg.addr"); return ResAddr; } Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, CGF.getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(8), /*allowHigherAlign*/ false); } ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { // Assumes vectorCall calling convention. const Type *Base = nullptr; uint64_t NumElts = 0; if (!Ty->isBuiltinType() && !Ty->isVectorType() && isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { FreeSSERegs -= NumElts; return getDirectX86Hva(); } return current; } ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, bool IsVectorCall, bool IsRegCall) const { if (Ty->isVoidType()) return ABIArgInfo::getIgnore(); if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); TypeInfo Info = getContext().getTypeInfo(Ty); uint64_t Width = Info.Width; CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); const RecordType *RT = Ty->getAs(); if (RT) { if (!IsReturnType) { if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); } if (RT->getDecl()->hasFlexibleArrayMember()) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); } const Type *Base = nullptr; uint64_t NumElts = 0; // vectorcall adds the concept of a homogenous vector aggregate, similar to // other targets. if ((IsVectorCall || IsRegCall) && isHomogeneousAggregate(Ty, Base, NumElts)) { if (IsRegCall) { if (FreeSSERegs >= NumElts) { FreeSSERegs -= NumElts; if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) return ABIArgInfo::getDirect(); return ABIArgInfo::getExpand(); } return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); } else if (IsVectorCall) { if (FreeSSERegs >= NumElts && (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { FreeSSERegs -= NumElts; return ABIArgInfo::getDirect(); } else if (IsReturnType) { return ABIArgInfo::getExpand(); } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { // HVAs are delayed and reclassified in the 2nd step. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); } } } if (Ty->isMemberPointerType()) { // If the member pointer is represented by an LLVM int or ptr, pass it // directly. llvm::Type *LLTy = CGT.ConvertType(Ty); if (LLTy->isPointerTy() || LLTy->isIntegerTy()) return ABIArgInfo::getDirect(); } if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is // not 1, 2, 4, or 8 bytes, must be passed by reference." if (Width > 64 || !llvm::isPowerOf2_64(Width)) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); // Otherwise, coerce it to a small integer. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); } if (const BuiltinType *BT = Ty->getAs()) { switch (BT->getKind()) { case BuiltinType::Bool: // Bool type is always extended to the ABI, other builtin types are not // extended. return ABIArgInfo::getExtend(Ty); case BuiltinType::LongDouble: // Mingw64 GCC uses the old 80 bit extended precision floating point // unit. It passes them indirectly through memory. if (IsMingw64) { const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); if (LDF == &llvm::APFloat::x87DoubleExtended()) return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); } break; case BuiltinType::Int128: case BuiltinType::UInt128: // If it's a parameter type, the normal ABI rule is that arguments larger // than 8 bytes are passed indirectly. GCC follows it. We follow it too, // even though it isn't particularly efficient. if (!IsReturnType) return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. // Clang matches them for compatibility. return ABIArgInfo::getDirect( llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); default: break; } } return ABIArgInfo::getDirect(); } void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, bool IsVectorCall, bool IsRegCall) const { unsigned Count = 0; for (auto &I : FI.arguments()) { // Vectorcall in x64 only permits the first 6 arguments to be passed // as XMM/YMM registers. if (Count < VectorcallMaxParamNumAsReg) I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); else { // Since these cannot be passed in registers, pretend no registers // are left. unsigned ZeroSSERegsAvail = 0; I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, IsVectorCall, IsRegCall); } ++Count; } for (auto &I : FI.arguments()) { I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); } } void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { bool IsVectorCall = FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall; bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall; unsigned FreeSSERegs = 0; if (IsVectorCall) { // We can use up to 4 SSE return registers with vectorcall. FreeSSERegs = 4; } else if (IsRegCall) { // RegCall gives us 16 SSE registers. FreeSSERegs = 16; } if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, IsVectorCall, IsRegCall); if (IsVectorCall) { // We can use up to 6 SSE register parameters with vectorcall. FreeSSERegs = 6; } else if (IsRegCall) { // RegCall gives us 16 SSE registers, we can reuse the return registers. FreeSSERegs = 16; } if (IsVectorCall) { computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); } else { for (auto &I : FI.arguments()) I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); } } Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { bool IsIndirect = false; // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is // not 1, 2, 4, or 8 bytes, must be passed by reference." if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { uint64_t Width = getContext().getTypeSize(Ty); IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); } return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, CGF.getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(8), /*allowHigherAlign*/ false); } // PowerPC-32 namespace { /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. class PPC32_SVR4_ABIInfo : public DefaultABIInfo { bool IsSoftFloatABI; CharUnits getParamTypeAlignment(QualType Ty) const; public: PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI) : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {} Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; }; class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { public: PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { // This is recovered from gcc output. return 1; // r1 is the dedicated stack pointer } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; }; } CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { // Complex types are passed just like their elements if (const ComplexType *CTy = Ty->getAs()) Ty = CTy->getElementType(); if (Ty->isVectorType()) return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 4); // For single-element float/vector structs, we consider the whole type // to have the same alignment requirements as its single element. const Type *AlignTy = nullptr; if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { const BuiltinType *BT = EltType->getAs(); if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || (BT && BT->isFloatingPoint())) AlignTy = EltType; } if (AlignTy) return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); return CharUnits::fromQuantity(4); } // TODO: this implementation is now likely redundant with // DefaultABIInfo::EmitVAArg. Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, QualType Ty) const { if (getTarget().getTriple().isOSDarwin()) { auto TI = getContext().getTypeInfoInChars(Ty); TI.second = getParamTypeAlignment(Ty); CharUnits SlotSize = CharUnits::fromQuantity(4); return emitVoidPtrVAArg(CGF, VAList, Ty, classifyArgumentType(Ty).isIndirect(), TI, SlotSize, /*AllowHigherAlign=*/true); } const unsigned OverflowLimit = 8; if (const ComplexType *CTy = Ty->getAs()) { // TODO: Implement this. For now ignore. (void)CTy; return Address::invalid(); // FIXME? } // struct __va_list_tag { // unsigned char gpr; // unsigned char fpr; // unsigned short reserved; // void *overflow_arg_area; // void *reg_save_area; // }; bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; // All aggregates are passed indirectly? That doesn't seem consistent // with the argument-lowering code. bool isIndirect = Ty->isAggregateType(); CGBuilderTy &Builder = CGF.Builder; // The calling convention either uses 1-2 GPRs or 1 FPR. Address NumRegsAddr = Address::invalid(); if (isInt || IsSoftFloatABI) { NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr"); } else { NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr"); } llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); // "Align" the register count when TY is i64. if (isI64 || (isF64 && IsSoftFloatABI)) { NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); } llvm::Value *CC = Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); llvm::Type *DirectTy = CGF.ConvertType(Ty); if (isIndirect) DirectTy = DirectTy->getPointerTo(0); // Case 1: consume registers. Address RegAddr = Address::invalid(); { CGF.EmitBlock(UsingRegs); Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8)); RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CharUnits::fromQuantity(8)); assert(RegAddr.getElementType() == CGF.Int8Ty); // Floating-point registers start after the general-purpose registers. if (!(isInt || IsSoftFloatABI)) { RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, CharUnits::fromQuantity(32)); } // Get the address of the saved value by scaling the number of // registers we've used by the number of CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); llvm::Value *RegOffset = Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset), RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); // Increase the used-register count. NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); Builder.CreateStore(NumRegs, NumRegsAddr); CGF.EmitBranch(Cont); } // Case 2: consume space in the overflow area. Address MemAddr = Address::invalid(); { CGF.EmitBlock(UsingOverflow); Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); // Everything in the overflow area is rounded up to a size of at least 4. CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); CharUnits Size; if (!isIndirect) { auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); Size = TypeInfo.first.alignTo(OverflowAreaAlign); } else { Size = CGF.getPointerSize(); } Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4)); Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), OverflowAreaAlign); // Round up address of argument to alignment CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); if (Align > OverflowAreaAlign) { llvm::Value *Ptr = OverflowArea.getPointer(); OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), Align); } MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); // Increase the overflow area. OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); CGF.EmitBranch(Cont); } CGF.EmitBlock(Cont); // Merge the cases with a phi. Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, "vaarg.addr"); // Load the pointer if the argument was passed indirectly. if (isIndirect) { Result = Address(Builder.CreateLoad(Result, "aggr"), getContext().getTypeAlignInChars(Ty)); } return Result; } bool PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { // This is calculated from the LLVM and GCC tables and verified // against gcc output. AFAIK all ABIs use the same encoding. CodeGen::CGBuilderTy &Builder = CGF.Builder; llvm::IntegerType *i8 = CGF.Int8Ty; llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); // 0-31: r0-31, the 4-byte general-purpose registers AssignToArrayRange(Builder, Address, Four8, 0, 31); // 32-63: fp0-31, the 8-byte floating-point registers AssignToArrayRange(Builder, Address, Eight8, 32, 63); // 64-76 are various 4-byte special-purpose registers: // 64: mq // 65: lr // 66: ctr // 67: ap // 68-75 cr0-7 // 76: xer AssignToArrayRange(Builder, Address, Four8, 64, 76); // 77-108: v0-31, the 16-byte vector registers AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); // 109: vrsave // 110: vscr // 111: spe_acc // 112: spefscr // 113: sfp AssignToArrayRange(Builder, Address, Four8, 109, 113); return false; } // PowerPC-64 namespace { /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. class PPC64_SVR4_ABIInfo : public SwiftABIInfo { public: enum ABIKind { ELFv1 = 0, ELFv2 }; private: static const unsigned GPRBits = 64; ABIKind Kind; bool HasQPX; bool IsSoftFloatABI; // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and // will be passed in a QPX register. bool IsQPXVectorTy(const Type *Ty) const { if (!HasQPX) return false; if (const VectorType *VT = Ty->getAs()) { unsigned NumElements = VT->getNumElements(); if (NumElements == 1) return false; if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { if (getContext().getTypeSize(Ty) <= 256) return true; } else if (VT->getElementType()-> isSpecificBuiltinType(BuiltinType::Float)) { if (getContext().getTypeSize(Ty) <= 128) return true; } } return false; } bool IsQPXVectorTy(QualType Ty) const { return IsQPXVectorTy(Ty.getTypePtr()); } public: PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, bool SoftFloatABI) : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), IsSoftFloatABI(SoftFloatABI) {} bool isPromotableTypeForABI(QualType Ty) const; CharUnits getParamTypeAlignment(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType Ty) const; bool isHomogeneousAggregateBaseType(QualType Ty) const override; bool isHomogeneousAggregateSmallEnough(const Type *Ty, uint64_t Members) const override; // TODO: We can add more logic to computeInfo to improve performance. // Example: For aggregate arguments that fit in a register, we could // use getDirectInReg (as is done below for structs containing a single // floating-point value) to avoid pushing them to memory on function // entry. This would require changing the logic in PPCISelLowering // when lowering the parameters in the caller and args in the callee. void computeInfo(CGFunctionInfo &FI) const override { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) { // We rely on the default argument classification for the most part. // One exception: An aggregate containing a single floating-point // or vector item must be passed in a register if one is available. const Type *T = isSingleElementStruct(I.type, getContext()); if (T) { const BuiltinType *BT = T->getAs(); if (IsQPXVectorTy(T) || (T->isVectorType() && getContext().getTypeSize(T) == 128) || (BT && BT->isFloatingPoint())) { QualType QT(T, 0); I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); continue; } } I.info = classifyArgumentType(I.type); } } Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return false; } }; class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { public: PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, bool SoftFloatABI) : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX, SoftFloatABI)) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { // This is recovered from gcc output. return 1; // r1 is the dedicated stack pointer } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; }; class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { public: PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { // This is recovered from gcc output. return 1; // r1 is the dedicated stack pointer } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; }; } // Return true if the ABI requires Ty to be passed sign- or zero- // extended to 64 bits. bool PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // Promotable integer types are required to be promoted by the ABI. if (Ty->isPromotableIntegerType()) return true; // In addition to the usual promotable integer types, we also need to // extend all 32-bit types, since the ABI requires promotion to 64 bits. if (const BuiltinType *BT = Ty->getAs()) switch (BT->getKind()) { case BuiltinType::Int: case BuiltinType::UInt: return true; default: break; } return false; } /// isAlignedParamType - Determine whether a type requires 16-byte or /// higher alignment in the parameter area. Always returns at least 8. CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { // Complex types are passed just like their elements. if (const ComplexType *CTy = Ty->getAs()) Ty = CTy->getElementType(); // Only vector types of size 16 bytes need alignment (larger types are // passed via reference, smaller types are not aligned). if (IsQPXVectorTy(Ty)) { if (getContext().getTypeSize(Ty) > 128) return CharUnits::fromQuantity(32); return CharUnits::fromQuantity(16); } else if (Ty->isVectorType()) { return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); } // For single-element float/vector structs, we consider the whole type // to have the same alignment requirements as its single element. const Type *AlignAsType = nullptr; const Type *EltType = isSingleElementStruct(Ty, getContext()); if (EltType) { const BuiltinType *BT = EltType->getAs(); if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || (BT && BT->isFloatingPoint())) AlignAsType = EltType; } // Likewise for ELFv2 homogeneous aggregates. const Type *Base = nullptr; uint64_t Members = 0; if (!AlignAsType && Kind == ELFv2 && isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) AlignAsType = Base; // With special case aggregates, only vector base types need alignment. if (AlignAsType && IsQPXVectorTy(AlignAsType)) { if (getContext().getTypeSize(AlignAsType) > 128) return CharUnits::fromQuantity(32); return CharUnits::fromQuantity(16); } else if (AlignAsType) { return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); } // Otherwise, we only need alignment for any aggregate type that // has an alignment requirement of >= 16 bytes. if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { if (HasQPX && getContext().getTypeAlign(Ty) >= 256) return CharUnits::fromQuantity(32); return CharUnits::fromQuantity(16); } return CharUnits::fromQuantity(8); } /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous /// aggregate. Base is set to the base element type, and Members is set /// to the number of base elements. bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, uint64_t &Members) const { if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { uint64_t NElements = AT->getSize().getZExtValue(); if (NElements == 0) return false; if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) return false; Members *= NElements; } else if (const RecordType *RT = Ty->getAs()) { const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return false; Members = 0; // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { for (const auto &I : CXXRD->bases()) { // Ignore empty records. if (isEmptyRecord(getContext(), I.getType(), true)) continue; uint64_t FldMembers; if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) return false; Members += FldMembers; } } for (const auto *FD : RD->fields()) { // Ignore (non-zero arrays of) empty records. QualType FT = FD->getType(); while (const ConstantArrayType *AT = getContext().getAsConstantArrayType(FT)) { if (AT->getSize().getZExtValue() == 0) return false; FT = AT->getElementType(); } if (isEmptyRecord(getContext(), FT, true)) continue; // For compatibility with GCC, ignore empty bitfields in C++ mode. if (getContext().getLangOpts().CPlusPlus && FD->isZeroLengthBitField(getContext())) continue; uint64_t FldMembers; if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) return false; Members = (RD->isUnion() ? std::max(Members, FldMembers) : Members + FldMembers); } if (!Base) return false; // Ensure there is no padding. if (getContext().getTypeSize(Base) * Members != getContext().getTypeSize(Ty)) return false; } else { Members = 1; if (const ComplexType *CT = Ty->getAs()) { Members = 2; Ty = CT->getElementType(); } // Most ABIs only support float, double, and some vector type widths. if (!isHomogeneousAggregateBaseType(Ty)) return false; // The base type must be the same for all members. Types that // agree in both total size and mode (float vs. vector) are // treated as being equivalent here. const Type *TyPtr = Ty.getTypePtr(); if (!Base) { Base = TyPtr; // If it's a non-power-of-2 vector, its size is already a power-of-2, // so make sure to widen it explicitly. if (const VectorType *VT = Base->getAs()) { QualType EltTy = VT->getElementType(); unsigned NumElements = getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); Base = getContext() .getVectorType(EltTy, NumElements, VT->getVectorKind()) .getTypePtr(); } } if (Base->isVectorType() != TyPtr->isVectorType() || getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) return false; } return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); } bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { // Homogeneous aggregates for ELFv2 must have base types of float, // double, long double, or 128-bit vectors. if (const BuiltinType *BT = Ty->getAs()) { if (BT->getKind() == BuiltinType::Float || BT->getKind() == BuiltinType::Double || BT->getKind() == BuiltinType::LongDouble || (getContext().getTargetInfo().hasFloat128Type() && (BT->getKind() == BuiltinType::Float128))) { if (IsSoftFloatABI) return false; return true; } } if (const VectorType *VT = Ty->getAs()) { if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) return true; } return false; } bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( const Type *Base, uint64_t Members) const { // Vector and fp128 types require one register, other floating point types // require one or two registers depending on their size. uint32_t NumRegs = ((getContext().getTargetInfo().hasFloat128Type() && Base->isFloat128Type()) || Base->isVectorType()) ? 1 : (getContext().getTypeSize(Base) + 63) / 64; // Homogeneous Aggregates may occupy at most 8 registers. return Members * NumRegs <= 8; } ABIArgInfo PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { Ty = useFirstFieldIfTransparentUnion(Ty); if (Ty->isAnyComplexType()) return ABIArgInfo::getDirect(); // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) // or via reference (larger than 16 bytes). if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { uint64_t Size = getContext().getTypeSize(Ty); if (Size > 128) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); else if (Size < 128) { llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); return ABIArgInfo::getDirect(CoerceTy); } } if (isAggregateTypeForABI(Ty)) { if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); // ELFv2 homogeneous aggregates are passed as array types. const Type *Base = nullptr; uint64_t Members = 0; if (Kind == ELFv2 && isHomogeneousAggregate(Ty, Base, Members)) { llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); return ABIArgInfo::getDirect(CoerceTy); } // If an aggregate may end up fully in registers, we do not // use the ByVal method, but pass the aggregate as array. // This is usually beneficial since we avoid forcing the // back-end to store the argument to memory. uint64_t Bits = getContext().getTypeSize(Ty); if (Bits > 0 && Bits <= 8 * GPRBits) { llvm::Type *CoerceTy; // Types up to 8 bytes are passed as integer type (which will be // properly aligned in the argument save area doubleword). if (Bits <= GPRBits) CoerceTy = llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); // Larger types are passed as arrays, with the base type selected // according to the required alignment in the save area. else { uint64_t RegBits = ABIAlign * 8; uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); } return ABIArgInfo::getDirect(CoerceTy); } // All other aggregates are passed ByVal. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), /*ByVal=*/true, /*Realign=*/TyAlign > ABIAlign); } return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } ABIArgInfo PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); if (RetTy->isAnyComplexType()) return ABIArgInfo::getDirect(); // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) // or via reference (larger than 16 bytes). if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { uint64_t Size = getContext().getTypeSize(RetTy); if (Size > 128) return getNaturalAlignIndirect(RetTy); else if (Size < 128) { llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); return ABIArgInfo::getDirect(CoerceTy); } } if (isAggregateTypeForABI(RetTy)) { // ELFv2 homogeneous aggregates are returned as array types. const Type *Base = nullptr; uint64_t Members = 0; if (Kind == ELFv2 && isHomogeneousAggregate(RetTy, Base, Members)) { llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); return ABIArgInfo::getDirect(CoerceTy); } // ELFv2 small aggregates are returned in up to two registers. uint64_t Bits = getContext().getTypeSize(RetTy); if (Kind == ELFv2 && Bits <= 2 * GPRBits) { if (Bits == 0) return ABIArgInfo::getIgnore(); llvm::Type *CoerceTy; if (Bits > GPRBits) { CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); } else CoerceTy = llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); return ABIArgInfo::getDirect(CoerceTy); } // All other aggregates are returned indirectly. return getNaturalAlignIndirect(RetTy); } return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { auto TypeInfo = getContext().getTypeInfoInChars(Ty); TypeInfo.second = getParamTypeAlignment(Ty); CharUnits SlotSize = CharUnits::fromQuantity(8); // If we have a complex type and the base type is smaller than 8 bytes, // the ABI calls for the real and imaginary parts to be right-adjusted // in separate doublewords. However, Clang expects us to produce a // pointer to a structure with the two parts packed tightly. So generate // loads of the real and imaginary parts relative to the va_list pointer, // and store them to a temporary structure. if (const ComplexType *CTy = Ty->getAs()) { CharUnits EltSize = TypeInfo.first / 2; if (EltSize < SlotSize) { Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2, SlotSize, SlotSize, /*AllowHigher*/ true); Address RealAddr = Addr; Address ImagAddr = RealAddr; if (CGF.CGM.getDataLayout().isBigEndian()) { RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize); ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 2 * SlotSize - EltSize); } else { ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); } llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), /*init*/ true); return Temp; } } // Otherwise, just use the general rule. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, SlotSize, /*AllowHigher*/ true); } static bool PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) { // This is calculated from the LLVM and GCC tables and verified // against gcc output. AFAIK all ABIs use the same encoding. CodeGen::CGBuilderTy &Builder = CGF.Builder; llvm::IntegerType *i8 = CGF.Int8Ty; llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); // 0-31: r0-31, the 8-byte general-purpose registers AssignToArrayRange(Builder, Address, Eight8, 0, 31); // 32-63: fp0-31, the 8-byte floating-point registers AssignToArrayRange(Builder, Address, Eight8, 32, 63); // 64-67 are various 8-byte special-purpose registers: // 64: mq // 65: lr // 66: ctr // 67: ap AssignToArrayRange(Builder, Address, Eight8, 64, 67); // 68-76 are various 4-byte special-purpose registers: // 68-75 cr0-7 // 76: xer AssignToArrayRange(Builder, Address, Four8, 68, 76); // 77-108: v0-31, the 16-byte vector registers AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); // 109: vrsave // 110: vscr // 111: spe_acc // 112: spefscr // 113: sfp // 114: tfhar // 115: tfiar // 116: texasr AssignToArrayRange(Builder, Address, Eight8, 109, 116); return false; } bool PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { return PPC64_initDwarfEHRegSizeTable(CGF, Address); } bool PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { return PPC64_initDwarfEHRegSizeTable(CGF, Address); } //===----------------------------------------------------------------------===// // AArch64 ABI Implementation //===----------------------------------------------------------------------===// namespace { class AArch64ABIInfo : public SwiftABIInfo { public: enum ABIKind { AAPCS = 0, DarwinPCS, Win64 }; private: ABIKind Kind; public: AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : SwiftABIInfo(CGT), Kind(Kind) {} private: ABIKind getABIKind() const { return Kind; } bool isDarwinPCS() const { return Kind == DarwinPCS; } ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType RetTy) const; bool isHomogeneousAggregateBaseType(QualType Ty) const override; bool isHomogeneousAggregateSmallEnough(const Type *Ty, uint64_t Members) const override; bool isIllegalVectorType(QualType Ty) const; void computeInfo(CGFunctionInfo &FI) const override { if (!::classifyReturnType(getCXXABI(), FI, *this)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &it : FI.arguments()) it.info = classifyArgumentType(it.type); } Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF) const; Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF) const; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override { return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) : EmitAAPCSVAArg(VAListAddr, Ty, CGF); } Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return true; } bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, unsigned elts) const override; }; class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { public: AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {} StringRef getARCRetainAutoreleasedReturnValueMarker() const override { return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; } int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { return 31; } bool doesReturnSlotInterfereWithArgs() const override { return false; } void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; llvm::Function *Fn = cast(GV); auto Kind = CGM.getCodeGenOpts().getSignReturnAddress(); if (Kind != CodeGenOptions::SignReturnAddressScope::None) { Fn->addFnAttr("sign-return-address", Kind == CodeGenOptions::SignReturnAddressScope::All ? "all" : "non-leaf"); auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey(); Fn->addFnAttr("sign-return-address-key", Key == CodeGenOptions::SignReturnAddressKeyValue::AKey ? "a_key" : "b_key"); } if (CGM.getCodeGenOpts().BranchTargetEnforcement) Fn->addFnAttr("branch-target-enforcement"); } }; class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { public: WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) : AArch64TargetCodeGenInfo(CGT, K) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override; void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const override { Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); } void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString<32> &Opt) const override { Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; } }; void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); if (GV->isDeclaration()) return; addStackProbeTargetAttributes(D, GV, CGM); } } ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { Ty = useFirstFieldIfTransparentUnion(Ty); // Handle illegal vector types here. if (isIllegalVectorType(Ty)) { uint64_t Size = getContext().getTypeSize(Ty); // Android promotes <2 x i8> to i16, not i32 if (isAndroid() && (Size <= 16)) { llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); return ABIArgInfo::getDirect(ResType); } if (Size <= 32) { llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(ResType); } if (Size == 64) { llvm::Type *ResType = llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); return ABIArgInfo::getDirect(ResType); } if (Size == 128) { llvm::Type *ResType = llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); return ABIArgInfo::getDirect(ResType); } return getNaturalAlignIndirect(Ty, /*ByVal=*/false); } if (!isAggregateTypeForABI(Ty)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); return (Ty->isPromotableIntegerType() && isDarwinPCS() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } // Structures with either a non-trivial destructor or a non-trivial // copy constructor are always indirect. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == CGCXXABI::RAA_DirectInMemory); } // Empty records are always ignored on Darwin, but actually passed in C++ mode // elsewhere for GNU compatibility. uint64_t Size = getContext().getTypeSize(Ty); bool IsEmpty = isEmptyRecord(getContext(), Ty, true); if (IsEmpty || Size == 0) { if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) return ABIArgInfo::getIgnore(); // GNU C mode. The only argument that gets ignored is an empty one with size // 0. if (IsEmpty && Size == 0) return ABIArgInfo::getIgnore(); return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); } // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. const Type *Base = nullptr; uint64_t Members = 0; if (isHomogeneousAggregate(Ty, Base, Members)) { return ABIArgInfo::getDirect( llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); } // Aggregates <= 16 bytes are passed directly in registers or on the stack. if (Size <= 128) { // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of // same size and alignment. if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(Ty, getContext(), getVMContext()); } unsigned Alignment; if (Kind == AArch64ABIInfo::AAPCS) { Alignment = getContext().getTypeUnadjustedAlign(Ty); Alignment = Alignment < 128 ? 64 : 128; } else { Alignment = getContext().getTypeAlign(Ty); } Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. // For aggregates with 16-byte alignment, we use i128. if (Alignment < 128 && Size == 128) { llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); } return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); } return getNaturalAlignIndirect(Ty, /*ByVal=*/false); } ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); // Large vector types should be returned via memory. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) return getNaturalAlignIndirect(RetTy); if (!isAggregateTypeForABI(RetTy)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() && isDarwinPCS() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } uint64_t Size = getContext().getTypeSize(RetTy); if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) return ABIArgInfo::getIgnore(); const Type *Base = nullptr; uint64_t Members = 0; if (isHomogeneousAggregate(RetTy, Base, Members)) // Homogeneous Floating-point Aggregates (HFAs) are returned directly. return ABIArgInfo::getDirect(); // Aggregates <= 16 bytes are returned directly in registers or on the stack. if (Size <= 128) { // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of // same size and alignment. if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(RetTy, getContext(), getVMContext()); } unsigned Alignment = getContext().getTypeAlign(RetTy); Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. // For aggregates with 16-byte alignment, we use i128. if (Alignment < 128 && Size == 128) { llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); } return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); } return getNaturalAlignIndirect(RetTy); } /// isIllegalVectorType - check whether the vector type is legal for AArch64. bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { if (const VectorType *VT = Ty->getAs()) { // Check whether VT is legal. unsigned NumElements = VT->getNumElements(); uint64_t Size = getContext().getTypeSize(VT); // NumElements should be power of 2. if (!llvm::isPowerOf2_32(NumElements)) return true; return Size != 64 && (Size != 128 || NumElements == 1); } return false; } bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, unsigned elts) const { if (!llvm::isPowerOf2_32(elts)) return false; if (totalSize.getQuantity() != 8 && (totalSize.getQuantity() != 16 || elts == 1)) return false; return true; } bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { // Homogeneous aggregates for AAPCS64 must have base types of a floating // point type or a short-vector type. This is the same as the 32-bit ABI, // but with the difference that any floating-point type is allowed, // including __fp16. if (const BuiltinType *BT = Ty->getAs()) { if (BT->isFloatingPoint()) return true; } else if (const VectorType *VT = Ty->getAs()) { unsigned VecSize = getContext().getTypeSize(VT); if (VecSize == 64 || VecSize == 128) return true; } return false; } bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const { return Members <= 4; } Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF) const { ABIArgInfo AI = classifyArgumentType(Ty); bool IsIndirect = AI.isIndirect(); llvm::Type *BaseTy = CGF.ConvertType(Ty); if (IsIndirect) BaseTy = llvm::PointerType::getUnqual(BaseTy); else if (AI.getCoerceToType()) BaseTy = AI.getCoerceToType(); unsigned NumRegs = 1; if (llvm::ArrayType *ArrTy = dyn_cast(BaseTy)) { BaseTy = ArrTy->getElementType(); NumRegs = ArrTy->getNumElements(); } bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); // The AArch64 va_list type and handling is specified in the Procedure Call // Standard, section B.4: // // struct { // void *__stack; // void *__gr_top; // void *__vr_top; // int __gr_offs; // int __vr_offs; // }; llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); auto TyInfo = getContext().getTypeInfoInChars(Ty); CharUnits TyAlign = TyInfo.second; Address reg_offs_p = Address::invalid(); llvm::Value *reg_offs = nullptr; int reg_top_index; CharUnits reg_top_offset; int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity(); if (!IsFPR) { // 3 is the field number of __gr_offs reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24), "gr_offs_p"); reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); reg_top_index = 1; // field number for __gr_top reg_top_offset = CharUnits::fromQuantity(8); RegSize = llvm::alignTo(RegSize, 8); } else { // 4 is the field number of __vr_offs. reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28), "vr_offs_p"); reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); reg_top_index = 2; // field number for __vr_top reg_top_offset = CharUnits::fromQuantity(16); RegSize = 16 * NumRegs; } //======================================= // Find out where argument was passed //======================================= // If reg_offs >= 0 we're already using the stack for this type of // argument. We don't want to keep updating reg_offs (in case it overflows, // though anyone passing 2GB of arguments, each at most 16 bytes, deserves // whatever they get). llvm::Value *UsingStack = nullptr; UsingStack = CGF.Builder.CreateICmpSGE( reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); // Otherwise, at least some kind of argument could go in these registers, the // question is whether this particular type is too big. CGF.EmitBlock(MaybeRegBlock); // Integer arguments may need to correct register alignment (for example a // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we // align __gr_offs to calculate the potential address. if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { int Align = TyAlign.getQuantity(); reg_offs = CGF.Builder.CreateAdd( reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), "align_regoffs"); reg_offs = CGF.Builder.CreateAnd( reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), "aligned_regoffs"); } // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. // The fact that this is done unconditionally reflects the fact that // allocating an argument to the stack also uses up all the remaining // registers of the appropriate kind. llvm::Value *NewOffset = nullptr; NewOffset = CGF.Builder.CreateAdd( reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); CGF.Builder.CreateStore(NewOffset, reg_offs_p); // Now we're in a position to decide whether this argument really was in // registers or not. llvm::Value *InRegs = nullptr; InRegs = CGF.Builder.CreateICmpSLE( NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); //======================================= // Argument was in registers //======================================= // Now we emit the code for if the argument was originally passed in // registers. First start the appropriate block: CGF.EmitBlock(InRegBlock); llvm::Value *reg_top = nullptr; Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, reg_top_offset, "reg_top_p"); reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), CharUnits::fromQuantity(IsFPR ? 16 : 8)); Address RegAddr = Address::invalid(); llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); if (IsIndirect) { // If it's been passed indirectly (actually a struct), whatever we find from // stored registers or on the stack will actually be a struct **. MemTy = llvm::PointerType::getUnqual(MemTy); } const Type *Base = nullptr; uint64_t NumMembers = 0; bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); if (IsHFA && NumMembers > 1) { // Homogeneous aggregates passed in registers will have their elements split // and stored 16-bytes apart regardless of size (they're notionally in qN, // qN+1, ...). We reload and store into a temporary local variable // contiguously. assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); Address Tmp = CGF.CreateTempAlloca(HFATy, std::max(TyAlign, BaseTyInfo.second)); // On big-endian platforms, the value will be right-aligned in its slot. int Offset = 0; if (CGF.CGM.getDataLayout().isBigEndian() && BaseTyInfo.first.getQuantity() < 16) Offset = 16 - BaseTyInfo.first.getQuantity(); for (unsigned i = 0; i < NumMembers; ++i) { CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); Address LoadAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first); llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); CGF.Builder.CreateStore(Elem, StoreAddr); } RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); } else { // Otherwise the object is contiguous in memory. // It might be right-aligned in its slot. CharUnits SlotSize = BaseAddr.getAlignment(); if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && (IsHFA || !isAggregateTypeForABI(Ty)) && TyInfo.first < SlotSize) { CharUnits Offset = SlotSize - TyInfo.first; BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); } RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); } CGF.EmitBranch(ContBlock); //======================================= // Argument was on the stack //======================================= CGF.EmitBlock(OnStackBlock); Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(), "stack_p"); llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); // Again, stack arguments may need realignment. In this case both integer and // floating-point ones might be affected. if (!IsIndirect && TyAlign.getQuantity() > 8) { int Align = TyAlign.getQuantity(); OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); OnStackPtr = CGF.Builder.CreateAdd( OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), "align_stack"); OnStackPtr = CGF.Builder.CreateAnd( OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), "align_stack"); OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); } Address OnStackAddr(OnStackPtr, std::max(CharUnits::fromQuantity(8), TyAlign)); // All stack slots are multiples of 8 bytes. CharUnits StackSlotSize = CharUnits::fromQuantity(8); CharUnits StackSize; if (IsIndirect) StackSize = StackSlotSize; else StackSize = TyInfo.first.alignTo(StackSlotSize); llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); // Write the new value of __stack for the next call to va_arg CGF.Builder.CreateStore(NewStack, stack_p); if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && TyInfo.first < StackSlotSize) { CharUnits Offset = StackSlotSize - TyInfo.first; OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); } OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); CGF.EmitBranch(ContBlock); //======================================= // Tidy up //======================================= CGF.EmitBlock(ContBlock); Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr, OnStackBlock, "vaargs.addr"); if (IsIndirect) return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), TyInfo.second); return ResAddr; } Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF) const { // The backend's lowering doesn't support va_arg for aggregates or // illegal vector types. Lower VAArg here for these cases and use // the LLVM va_arg instruction for everything else. if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); CharUnits SlotSize = CharUnits::fromQuantity(8); // Empty records are ignored for parameter passing purposes. if (isEmptyRecord(getContext(), Ty, true)) { Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); return Addr; } // The size of the actual thing passed, which might end up just // being a pointer for indirect types. auto TyInfo = getContext().getTypeInfoInChars(Ty); // Arguments bigger than 16 bytes which aren't homogeneous // aggregates should be passed indirectly. bool IsIndirect = false; if (TyInfo.first.getQuantity() > 16) { const Type *Base = nullptr; uint64_t Members = 0; IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); } return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, SlotSize, /*AllowHigherAlign*/ true); } Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, CGF.getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(8), /*allowHigherAlign*/ false); } //===----------------------------------------------------------------------===// // ARM ABI Implementation //===----------------------------------------------------------------------===// namespace { class ARMABIInfo : public SwiftABIInfo { public: enum ABIKind { APCS = 0, AAPCS = 1, AAPCS_VFP = 2, AAPCS16_VFP = 3, }; private: ABIKind Kind; public: ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : SwiftABIInfo(CGT), Kind(_Kind) { setCCs(); } bool isEABI() const { switch (getTarget().getTriple().getEnvironment()) { case llvm::Triple::Android: case llvm::Triple::EABI: case llvm::Triple::EABIHF: case llvm::Triple::GNUEABI: case llvm::Triple::GNUEABIHF: case llvm::Triple::MuslEABI: case llvm::Triple::MuslEABIHF: return true; default: return false; } } bool isEABIHF() const { switch (getTarget().getTriple().getEnvironment()) { case llvm::Triple::EABIHF: case llvm::Triple::GNUEABIHF: case llvm::Triple::MuslEABIHF: return true; default: return false; } } ABIKind getABIKind() const { return Kind; } private: ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const; ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const; ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, uint64_t Members) const; ABIArgInfo coerceIllegalVector(QualType Ty) const; bool isIllegalVectorType(QualType Ty) const; bool isHomogeneousAggregateBaseType(QualType Ty) const override; bool isHomogeneousAggregateSmallEnough(const Type *Ty, uint64_t Members) const override; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; llvm::CallingConv::ID getLLVMDefaultCC() const; llvm::CallingConv::ID getABIDefaultCC() const; void setCCs(); bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return true; } bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, unsigned elts) const override; }; class ARMTargetCodeGenInfo : public TargetCodeGenInfo { public: ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} const ARMABIInfo &getABIInfo() const { return static_cast(TargetCodeGenInfo::getABIInfo()); } int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { return 13; } StringRef getARCRetainAutoreleasedReturnValueMarker() const override { return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override { llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); // 0-15 are the 16 integer registers. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); return false; } unsigned getSizeOfUnwindException() const override { if (getABIInfo().isEABI()) return 88; return TargetCodeGenInfo::getSizeOfUnwindException(); } void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { if (GV->isDeclaration()) return; const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; const ARMInterruptAttr *Attr = FD->getAttr(); if (!Attr) return; const char *Kind; switch (Attr->getInterrupt()) { case ARMInterruptAttr::Generic: Kind = ""; break; case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; case ARMInterruptAttr::SWI: Kind = "SWI"; break; case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; } llvm::Function *Fn = cast(GV); Fn->addFnAttr("interrupt", Kind); ARMABIInfo::ABIKind ABI = cast(getABIInfo()).getABIKind(); if (ABI == ARMABIInfo::APCS) return; // AAPCS guarantees that sp will be 8-byte aligned on any public interface, // however this is not necessarily true on taking any interrupt. Instruct // the backend to perform a realignment as part of the function prologue. llvm::AttrBuilder B; B.addStackAlignmentAttr(8); Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); } }; class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { public: WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) : ARMTargetCodeGenInfo(CGT, K) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override; void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString<24> &Opt) const override { Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); } void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString<32> &Opt) const override { Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; } }; void WindowsARMTargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); if (GV->isDeclaration()) return; addStackProbeTargetAttributes(D, GV, CGM); } } void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { if (!::classifyReturnType(getCXXABI(), FI, *this)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type, FI.isVariadic()); // Always honor user-specified calling convention. if (FI.getCallingConvention() != llvm::CallingConv::C) return; llvm::CallingConv::ID cc = getRuntimeCC(); if (cc != llvm::CallingConv::C) FI.setEffectiveCallingConvention(cc); } /// Return the default calling convention that LLVM will use. llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { // The default calling convention that LLVM will infer. if (isEABIHF() || getTarget().getTriple().isWatchABI()) return llvm::CallingConv::ARM_AAPCS_VFP; else if (isEABI()) return llvm::CallingConv::ARM_AAPCS; else return llvm::CallingConv::ARM_APCS; } /// Return the calling convention that our ABI would like us to use /// as the C calling convention. llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { switch (getABIKind()) { case APCS: return llvm::CallingConv::ARM_APCS; case AAPCS: return llvm::CallingConv::ARM_AAPCS; case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; } llvm_unreachable("bad ABI kind"); } void ARMABIInfo::setCCs() { assert(getRuntimeCC() == llvm::CallingConv::C); // Don't muddy up the IR with a ton of explicit annotations if // they'd just match what LLVM will infer from the triple. llvm::CallingConv::ID abiCC = getABIDefaultCC(); if (abiCC != getLLVMDefaultCC()) RuntimeCC = abiCC; } ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { uint64_t Size = getContext().getTypeSize(Ty); if (Size <= 32) { llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(ResType); } if (Size == 64 || Size == 128) { llvm::Type *ResType = llvm::VectorType::get( llvm::Type::getInt32Ty(getVMContext()), Size / 32); return ABIArgInfo::getDirect(ResType); } return getNaturalAlignIndirect(Ty, /*ByVal=*/false); } ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, const Type *Base, uint64_t Members) const { assert(Base && "Base class should be set for homogeneous aggregate"); // Base can be a floating-point or a vector. if (const VectorType *VT = Base->getAs()) { // FP16 vectors should be converted to integer vectors if (!getTarget().hasLegalHalfType() && (VT->getElementType()->isFloat16Type() || VT->getElementType()->isHalfType())) { uint64_t Size = getContext().getTypeSize(VT); llvm::Type *NewVecTy = llvm::VectorType::get( llvm::Type::getInt32Ty(getVMContext()), Size / 32); llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); return ABIArgInfo::getDirect(Ty, 0, nullptr, false); } } return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); } ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic) const { // 6.1.2.1 The following argument types are VFP CPRCs: // A single-precision floating-point type (including promoted // half-precision types); A double-precision floating-point type; // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate // with a Base Type of a single- or double-precision floating-point type, // 64-bit containerized vectors or 128-bit containerized vectors with one // to four Elements. bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic; Ty = useFirstFieldIfTransparentUnion(Ty); // Handle illegal vector types here. if (isIllegalVectorType(Ty)) return coerceIllegalVector(Ty); // _Float16 and __fp16 get passed as if it were an int or float, but with // the top 16 bits unspecified. This is not done for OpenCL as it handles the // half type natively, and does not need to interwork with AAPCS code. if ((Ty->isFloat16Type() || Ty->isHalfType()) && !getContext().getLangOpts().NativeHalfArgsAndReturns) { llvm::Type *ResType = IsEffectivelyAAPCS_VFP ? llvm::Type::getFloatTy(getVMContext()) : llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(ResType); } if (!isAggregateTypeForABI(Ty)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) { Ty = EnumTy->getDecl()->getIntegerType(); } return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); } // Ignore empty records. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); if (IsEffectivelyAAPCS_VFP) { // Homogeneous Aggregates need to be expanded when we can fit the aggregate // into VFP registers. const Type *Base = nullptr; uint64_t Members = 0; if (isHomogeneousAggregate(Ty, Base, Members)) return classifyHomogeneousAggregate(Ty, Base, Members); } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { // WatchOS does have homogeneous aggregates. Note that we intentionally use // this convention even for a variadic function: the backend will use GPRs // if needed. const Type *Base = nullptr; uint64_t Members = 0; if (isHomogeneousAggregate(Ty, Base, Members)) { assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); llvm::Type *Ty = llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); return ABIArgInfo::getDirect(Ty, 0, nullptr, false); } } if (getABIKind() == ARMABIInfo::AAPCS16_VFP && getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're // bigger than 128-bits, they get placed in space allocated by the caller, // and a pointer is passed. return ABIArgInfo::getIndirect( CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); } // Support byval for ARM. // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at // most 8-byte. We realign the indirect argument if type alignment is bigger // than ABI alignment. uint64_t ABIAlign = 4; uint64_t TyAlign; if (getABIKind() == ARMABIInfo::AAPCS_VFP || getABIKind() == ARMABIInfo::AAPCS) { TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); } else { TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); } if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), /*ByVal=*/true, /*Realign=*/TyAlign > ABIAlign); } // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of // same size and alignment. if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(Ty, getContext(), getVMContext()); } // Otherwise, pass by coercing to a structure of the appropriate size. llvm::Type* ElemTy; unsigned SizeRegs; // FIXME: Try to match the types of the arguments more accurately where // we can. if (TyAlign <= 4) { ElemTy = llvm::Type::getInt32Ty(getVMContext()); SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; } else { ElemTy = llvm::Type::getInt64Ty(getVMContext()); SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; } return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); } static bool isIntegerLikeType(QualType Ty, ASTContext &Context, llvm::LLVMContext &VMContext) { // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure // is called integer-like if its size is less than or equal to one word, and // the offset of each of its addressable sub-fields is zero. uint64_t Size = Context.getTypeSize(Ty); // Check that the type fits in a word. if (Size > 32) return false; // FIXME: Handle vector types! if (Ty->isVectorType()) return false; // Float types are never treated as "integer like". if (Ty->isRealFloatingType()) return false; // If this is a builtin or pointer type then it is ok. if (Ty->getAs() || Ty->isPointerType()) return true; // Small complex integer types are "integer like". if (const ComplexType *CT = Ty->getAs()) return isIntegerLikeType(CT->getElementType(), Context, VMContext); // Single element and zero sized arrays should be allowed, by the definition // above, but they are not. // Otherwise, it must be a record type. const RecordType *RT = Ty->getAs(); if (!RT) return false; // Ignore records with flexible arrays. const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return false; // Check that all sub-fields are at offset 0, and are themselves "integer // like". const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); bool HadField = false; unsigned idx = 0; for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i, ++idx) { const FieldDecl *FD = *i; // Bit-fields are not addressable, we only need to verify they are "integer // like". We still have to disallow a subsequent non-bitfield, for example: // struct { int : 0; int x } // is non-integer like according to gcc. if (FD->isBitField()) { if (!RD->isUnion()) HadField = true; if (!isIntegerLikeType(FD->getType(), Context, VMContext)) return false; continue; } // Check if this field is at offset 0. if (Layout.getFieldOffset(idx) != 0) return false; if (!isIntegerLikeType(FD->getType(), Context, VMContext)) return false; // Only allow at most one field in a structure. This doesn't match the // wording above, but follows gcc in situations with a field following an // empty structure. if (!RD->isUnion()) { if (HadField) return false; HadField = true; } } return true; } ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic) const { bool IsEffectivelyAAPCS_VFP = (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic; if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); if (const VectorType *VT = RetTy->getAs()) { // Large vector types should be returned via memory. if (getContext().getTypeSize(RetTy) > 128) return getNaturalAlignIndirect(RetTy); // FP16 vectors should be converted to integer vectors if (!getTarget().hasLegalHalfType() && (VT->getElementType()->isFloat16Type() || VT->getElementType()->isHalfType())) return coerceIllegalVector(RetTy); } // _Float16 and __fp16 get returned as if it were an int or float, but with // the top 16 bits unspecified. This is not done for OpenCL as it handles the // half type natively, and does not need to interwork with AAPCS code. if ((RetTy->isFloat16Type() || RetTy->isHalfType()) && !getContext().getLangOpts().NativeHalfArgsAndReturns) { llvm::Type *ResType = IsEffectivelyAAPCS_VFP ? llvm::Type::getFloatTy(getVMContext()) : llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(ResType); } if (!isAggregateTypeForABI(RetTy)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect(); } // Are we following APCS? if (getABIKind() == APCS) { if (isEmptyRecord(getContext(), RetTy, false)) return ABIArgInfo::getIgnore(); // Complex types are all returned as packed integers. // // FIXME: Consider using 2 x vector types if the back end handles them // correctly. if (RetTy->isAnyComplexType()) return ABIArgInfo::getDirect(llvm::IntegerType::get( getVMContext(), getContext().getTypeSize(RetTy))); // Integer like structures are returned in r0. if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { // Return in the smallest viable integer type. uint64_t Size = getContext().getTypeSize(RetTy); if (Size <= 8) return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); if (Size <= 16) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); } // Otherwise return in memory. return getNaturalAlignIndirect(RetTy); } // Otherwise this is an AAPCS variant. if (isEmptyRecord(getContext(), RetTy, true)) return ABIArgInfo::getIgnore(); // Check for homogeneous aggregates with AAPCS-VFP. if (IsEffectivelyAAPCS_VFP) { const Type *Base = nullptr; uint64_t Members = 0; if (isHomogeneousAggregate(RetTy, Base, Members)) return classifyHomogeneousAggregate(RetTy, Base, Members); } // Aggregates <= 4 bytes are returned in r0; other aggregates // are returned indirectly. uint64_t Size = getContext().getTypeSize(RetTy); if (Size <= 32) { // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of // same size and alignment. if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(RetTy, getContext(), getVMContext()); } if (getDataLayout().isBigEndian()) // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); // Return in the smallest viable integer type. if (Size <= 8) return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); if (Size <= 16) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); llvm::Type *CoerceTy = llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); return ABIArgInfo::getDirect(CoerceTy); } return getNaturalAlignIndirect(RetTy); } /// isIllegalVector - check whether Ty is an illegal vector type. bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { if (const VectorType *VT = Ty->getAs ()) { // On targets that don't support FP16, FP16 is expanded into float, and we // don't want the ABI to depend on whether or not FP16 is supported in // hardware. Thus return false to coerce FP16 vectors into integer vectors. if (!getTarget().hasLegalHalfType() && (VT->getElementType()->isFloat16Type() || VT->getElementType()->isHalfType())) return true; if (isAndroid()) { // Android shipped using Clang 3.1, which supported a slightly different // vector ABI. The primary differences were that 3-element vector types // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path // accepts that legacy behavior for Android only. // Check whether VT is legal. unsigned NumElements = VT->getNumElements(); // NumElements should be power of 2 or equal to 3. if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) return true; } else { // Check whether VT is legal. unsigned NumElements = VT->getNumElements(); uint64_t Size = getContext().getTypeSize(VT); // NumElements should be power of 2. if (!llvm::isPowerOf2_32(NumElements)) return true; // Size should be greater than 32 bits. return Size <= 32; } } return false; } bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, llvm::Type *eltTy, unsigned numElts) const { if (!llvm::isPowerOf2_32(numElts)) return false; unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); if (size > 64) return false; if (vectorSize.getQuantity() != 8 && (vectorSize.getQuantity() != 16 || numElts == 1)) return false; return true; } bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { // Homogeneous aggregates for AAPCS-VFP must have base types of float, // double, or 64-bit or 128-bit vectors. if (const BuiltinType *BT = Ty->getAs()) { if (BT->getKind() == BuiltinType::Float || BT->getKind() == BuiltinType::Double || BT->getKind() == BuiltinType::LongDouble) return true; } else if (const VectorType *VT = Ty->getAs()) { unsigned VecSize = getContext().getTypeSize(VT); if (VecSize == 64 || VecSize == 128) return true; } return false; } bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const { return Members <= 4; } Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { CharUnits SlotSize = CharUnits::fromQuantity(4); // Empty records are ignored for parameter passing purposes. if (isEmptyRecord(getContext(), Ty, true)) { Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); return Addr; } auto TyInfo = getContext().getTypeInfoInChars(Ty); CharUnits TyAlignForABI = TyInfo.second; // Use indirect if size of the illegal vector is bigger than 16 bytes. bool IsIndirect = false; const Type *Base = nullptr; uint64_t Members = 0; if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { IsIndirect = true; // ARMv7k passes structs bigger than 16 bytes indirectly, in space // allocated by the caller. } else if (TyInfo.first > CharUnits::fromQuantity(16) && getABIKind() == ARMABIInfo::AAPCS16_VFP && !isHomogeneousAggregate(Ty, Base, Members)) { IsIndirect = true; // Otherwise, bound the type's ABI alignment. // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. // Our callers should be prepared to handle an under-aligned address. } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || getABIKind() == ARMABIInfo::AAPCS) { TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { // ARMv7k allows type alignment up to 16 bytes. TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); } else { TyAlignForABI = CharUnits::fromQuantity(4); } TyInfo.second = TyAlignForABI; return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, SlotSize, /*AllowHigherAlign*/ true); } //===----------------------------------------------------------------------===// // NVPTX ABI Implementation //===----------------------------------------------------------------------===// namespace { class NVPTXABIInfo : public ABIInfo { public: NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType Ty) const; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; }; class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { public: NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const override; bool shouldEmitStaticExternCAliases() const override; private: // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the // resulting MDNode to the nvvm.annotations MDNode. static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand); }; ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); // note: this is different from default ABI if (!RetTy->isScalarType()) return ABIArgInfo::getDirect(); // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // Return aggregates type as indirect by value if (isAggregateTypeForABI(Ty)) return getNaturalAlignIndirect(Ty, /* byval */ true); return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type); // Always honor user-specified calling convention. if (FI.getCallingConvention() != llvm::CallingConv::C) return; FI.setEffectiveCallingConvention(getRuntimeCC()); } Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { llvm_unreachable("NVPTX does not support varargs"); } void NVPTXTargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { if (GV->isDeclaration()) return; const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; llvm::Function *F = cast(GV); // Perform special handling in OpenCL mode if (M.getLangOpts().OpenCL) { // Use OpenCL function attributes to check for kernel functions // By default, all functions are device functions if (FD->hasAttr()) { // OpenCL __kernel functions get kernel metadata // Create !{, metadata !"kernel", i32 1} node addNVVMMetadata(F, "kernel", 1); // And kernel functions are not subject to inlining F->addFnAttr(llvm::Attribute::NoInline); } } // Perform special handling in CUDA mode. if (M.getLangOpts().CUDA) { // CUDA __global__ functions get a kernel metadata entry. Since // __global__ functions cannot be called from the device, we do not // need to set the noinline attribute. if (FD->hasAttr()) { // Create !{, metadata !"kernel", i32 1} node addNVVMMetadata(F, "kernel", 1); } if (CUDALaunchBoundsAttr *Attr = FD->getAttr()) { // Create !{, metadata !"maxntidx", i32 } node llvm::APSInt MaxThreads(32); MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); if (MaxThreads > 0) addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was // not specified in __launch_bounds__ or if the user specified a 0 value, // we don't have to add a PTX directive. if (Attr->getMinBlocks()) { llvm::APSInt MinBlocks(32); MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); if (MinBlocks > 0) // Create !{, metadata !"minctasm", i32 } node addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); } } } } void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand) { llvm::Module *M = F->getParent(); llvm::LLVMContext &Ctx = M->getContext(); // Get "nvvm.annotations" metadata node llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); llvm::Metadata *MDVals[] = { llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name), llvm::ConstantAsMetadata::get( llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; // Append metadata to nvvm.annotations MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); } bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { return false; } } //===----------------------------------------------------------------------===// // SystemZ ABI Implementation //===----------------------------------------------------------------------===// namespace { class SystemZABIInfo : public SwiftABIInfo { bool HasVector; public: SystemZABIInfo(CodeGenTypes &CGT, bool HV) : SwiftABIInfo(CGT), HasVector(HV) {} bool isPromotableIntegerType(QualType Ty) const; bool isCompoundType(QualType Ty) const; bool isVectorArgumentType(QualType Ty) const; bool isFPArgumentType(QualType Ty) const; QualType GetSingleElementType(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType ArgTy) const; void computeInfo(CGFunctionInfo &FI) const override { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type); } Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; bool shouldPassIndirectlyForSwift(ArrayRef scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); } bool isSwiftErrorInRegister() const override { return false; } }; class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { public: SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector) : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {} }; } bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // Promotable integer types are required to be promoted by the ABI. if (Ty->isPromotableIntegerType()) return true; // 32-bit values must also be promoted. if (const BuiltinType *BT = Ty->getAs()) switch (BT->getKind()) { case BuiltinType::Int: case BuiltinType::UInt: return true; default: return false; } return false; } bool SystemZABIInfo::isCompoundType(QualType Ty) const { return (Ty->isAnyComplexType() || Ty->isVectorType() || isAggregateTypeForABI(Ty)); } bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { return (HasVector && Ty->isVectorType() && getContext().getTypeSize(Ty) <= 128); } bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { if (const BuiltinType *BT = Ty->getAs()) switch (BT->getKind()) { case BuiltinType::Float: case BuiltinType::Double: return true; default: return false; } return false; } QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { if (const RecordType *RT = Ty->getAsStructureType()) { const RecordDecl *RD = RT->getDecl(); QualType Found; // If this is a C++ record, check the bases first. if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) for (const auto &I : CXXRD->bases()) { QualType Base = I.getType(); // Empty bases don't affect things either way. if (isEmptyRecord(getContext(), Base, true)) continue; if (!Found.isNull()) return Ty; Found = GetSingleElementType(Base); } // Check the fields. for (const auto *FD : RD->fields()) { // For compatibility with GCC, ignore empty bitfields in C++ mode. // Unlike isSingleElementStruct(), empty structure and array fields // do count. So do anonymous bitfields that aren't zero-sized. if (getContext().getLangOpts().CPlusPlus && FD->isZeroLengthBitField(getContext())) continue; // Unlike isSingleElementStruct(), arrays do not count. // Nested structures still do though. if (!Found.isNull()) return Ty; Found = GetSingleElementType(FD->getType()); } // Unlike isSingleElementStruct(), trailing padding is allowed. // An 8-byte aligned struct s { float f; } is passed as a double. if (!Found.isNull()) return Found; } return Ty; } Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { // Assume that va_list type is correct; should be pointer to LLVM type: // struct { // i64 __gpr; // i64 __fpr; // i8 *__overflow_arg_area; // i8 *__reg_save_area; // }; // Every non-vector argument occupies 8 bytes and is passed by preference // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are // always passed on the stack. Ty = getContext().getCanonicalType(Ty); auto TyInfo = getContext().getTypeInfoInChars(Ty); llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); llvm::Type *DirectTy = ArgTy; ABIArgInfo AI = classifyArgumentType(Ty); bool IsIndirect = AI.isIndirect(); bool InFPRs = false; bool IsVector = false; CharUnits UnpaddedSize; CharUnits DirectAlign; if (IsIndirect) { DirectTy = llvm::PointerType::getUnqual(DirectTy); UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); } else { if (AI.getCoerceToType()) ArgTy = AI.getCoerceToType(); InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy(); IsVector = ArgTy->isVectorTy(); UnpaddedSize = TyInfo.first; DirectAlign = TyInfo.second; } CharUnits PaddedSize = CharUnits::fromQuantity(8); if (IsVector && UnpaddedSize > PaddedSize) PaddedSize = CharUnits::fromQuantity(16); assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); CharUnits Padding = (PaddedSize - UnpaddedSize); llvm::Type *IndexTy = CGF.Int64Ty; llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); if (IsVector) { // Work out the address of a vector argument on the stack. // Vector arguments are always passed in the high bits of a // single (8 byte) or double (16 byte) stack slot. Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr"); Address OverflowArgArea = Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), TyInfo.second); Address MemAddr = CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); // Update overflow_arg_area_ptr pointer llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, "overflow_arg_area"); CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); return MemAddr; } assert(PaddedSize.getQuantity() == 8); unsigned MaxRegs, RegCountField, RegSaveIndex; CharUnits RegPadding; if (InFPRs) { MaxRegs = 4; // Maximum of 4 FPR arguments RegCountField = 1; // __fpr RegSaveIndex = 16; // save offset for f0 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR } else { MaxRegs = 5; // Maximum of 5 GPR arguments RegCountField = 0; // __gpr RegSaveIndex = 2; // save offset for r2 RegPadding = Padding; // values are passed in the low bits of a GPR } Address RegCountPtr = CGF.Builder.CreateStructGEP( VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8), "reg_count_ptr"); llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, "fits_in_regs"); llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); // Emit code to load the value if it was passed in registers. CGF.EmitBlock(InRegBlock); // Work out the address of an argument register. llvm::Value *ScaledRegCount = CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); llvm::Value *RegBase = llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() + RegPadding.getQuantity()); llvm::Value *RegOffset = CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); Address RegSaveAreaPtr = CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24), "reg_save_area_ptr"); llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr"), PaddedSize); Address RegAddr = CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); // Update the register count llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); llvm::Value *NewRegCount = CGF.Builder.CreateAdd(RegCount, One, "reg_count"); CGF.Builder.CreateStore(NewRegCount, RegCountPtr); CGF.EmitBranch(ContBlock); // Emit code to load the value if it was passed in memory. CGF.EmitBlock(InMemBlock); // Work out the address of a stack argument. Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP( VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr"); Address OverflowArgArea = Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), PaddedSize); Address RawMemAddr = CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); Address MemAddr = CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); // Update overflow_arg_area_ptr pointer llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, "overflow_arg_area"); CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); CGF.EmitBranch(ContBlock); // Return the appropriate result. CGF.EmitBlock(ContBlock); Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, "va_arg.addr"); if (IsIndirect) ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), TyInfo.second); return ResAddr; } ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); if (isVectorArgumentType(RetTy)) return ABIArgInfo::getDirect(); if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) return getNaturalAlignIndirect(RetTy); return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { // Handle the generic C++ ABI. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // Integers and enums are extended to full register width. if (isPromotableIntegerType(Ty)) return ABIArgInfo::getExtend(Ty); // Handle vector types and vector-like structure types. Note that // as opposed to float-like structure types, we do not allow any // padding for vector-like structures, so verify the sizes match. uint64_t Size = getContext().getTypeSize(Ty); QualType SingleElementTy = GetSingleElementType(Ty); if (isVectorArgumentType(SingleElementTy) && getContext().getTypeSize(SingleElementTy) == Size) return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. if (Size != 8 && Size != 16 && Size != 32 && Size != 64) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); // Handle small structures. if (const RecordType *RT = Ty->getAs()) { // Structures with flexible arrays have variable length, so really // fail the size test above. const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); // The structure is passed as an unextended integer, a float, or a double. llvm::Type *PassTy; if (isFPArgumentType(SingleElementTy)) { assert(Size == 32 || Size == 64); if (Size == 32) PassTy = llvm::Type::getFloatTy(getVMContext()); else PassTy = llvm::Type::getDoubleTy(getVMContext()); } else PassTy = llvm::IntegerType::get(getVMContext(), Size); return ABIArgInfo::getDirect(PassTy); } // Non-structure compounds are passed indirectly. if (isCompoundType(Ty)) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); return ABIArgInfo::getDirect(nullptr); } //===----------------------------------------------------------------------===// // MSP430 ABI Implementation //===----------------------------------------------------------------------===// namespace { class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { public: MSP430TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const override; }; } void MSP430TargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { if (GV->isDeclaration()) return; if (const FunctionDecl *FD = dyn_cast_or_null(D)) { - if (const MSP430InterruptAttr *attr = FD->getAttr()) { - // Handle 'interrupt' attribute: - llvm::Function *F = cast(GV); + const auto *InterruptAttr = FD->getAttr(); + if (!InterruptAttr) + return; - // Step 1: Set ISR calling convention. - F->setCallingConv(llvm::CallingConv::MSP430_INTR); + // Handle 'interrupt' attribute: + llvm::Function *F = cast(GV); - // Step 2: Add attributes goodness. - F->addFnAttr(llvm::Attribute::NoInline); + // Step 1: Set ISR calling convention. + F->setCallingConv(llvm::CallingConv::MSP430_INTR); - // Step 3: Emit ISR vector alias. - unsigned Num = attr->getNumber() / 2; - llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, - "__isr_" + Twine(Num), F); - } + // Step 2: Add attributes goodness. + F->addFnAttr(llvm::Attribute::NoInline); + F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); } } //===----------------------------------------------------------------------===// // MIPS ABI Implementation. This works for both little-endian and // big-endian variants. //===----------------------------------------------------------------------===// namespace { class MipsABIInfo : public ABIInfo { bool IsO32; unsigned MinABIStackAlignInBytes, StackAlignInBytes; void CoerceToIntArgs(uint64_t TySize, SmallVectorImpl &ArgList) const; llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; public: MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), StackAlignInBytes(IsO32 ? 8 : 16) {} ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; ABIArgInfo extendType(QualType Ty) const; }; class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { unsigned SizeOfUnwindException; public: MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), SizeOfUnwindException(IsO32 ? 24 : 32) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { return 29; } void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; llvm::Function *Fn = cast(GV); if (FD->hasAttr()) Fn->addFnAttr("long-call"); else if (FD->hasAttr()) Fn->addFnAttr("short-call"); // Other attributes do not have a meaning for declarations. if (GV->isDeclaration()) return; if (FD->hasAttr()) { Fn->addFnAttr("mips16"); } else if (FD->hasAttr()) { Fn->addFnAttr("nomips16"); } if (FD->hasAttr()) Fn->addFnAttr("micromips"); else if (FD->hasAttr()) Fn->addFnAttr("nomicromips"); const MipsInterruptAttr *Attr = FD->getAttr(); if (!Attr) return; const char *Kind; switch (Attr->getInterrupt()) { case MipsInterruptAttr::eic: Kind = "eic"; break; case MipsInterruptAttr::sw0: Kind = "sw0"; break; case MipsInterruptAttr::sw1: Kind = "sw1"; break; case MipsInterruptAttr::hw0: Kind = "hw0"; break; case MipsInterruptAttr::hw1: Kind = "hw1"; break; case MipsInterruptAttr::hw2: Kind = "hw2"; break; case MipsInterruptAttr::hw3: Kind = "hw3"; break; case MipsInterruptAttr::hw4: Kind = "hw4"; break; case MipsInterruptAttr::hw5: Kind = "hw5"; break; } Fn->addFnAttr("interrupt", Kind); } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; unsigned getSizeOfUnwindException() const override { return SizeOfUnwindException; } }; } void MipsABIInfo::CoerceToIntArgs( uint64_t TySize, SmallVectorImpl &ArgList) const { llvm::IntegerType *IntTy = llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); // Add (TySize / MinABIStackAlignInBytes) args of IntTy. for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) ArgList.push_back(IntTy); // If necessary, add one more integer type to ArgList. unsigned R = TySize % (MinABIStackAlignInBytes * 8); if (R) ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); } // In N32/64, an aligned double precision floating point field is passed in // a register. llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { SmallVector ArgList, IntArgList; if (IsO32) { CoerceToIntArgs(TySize, ArgList); return llvm::StructType::get(getVMContext(), ArgList); } if (Ty->isComplexType()) return CGT.ConvertType(Ty); const RecordType *RT = Ty->getAs(); // Unions/vectors are passed in integer registers. if (!RT || !RT->isStructureOrClassType()) { CoerceToIntArgs(TySize, ArgList); return llvm::StructType::get(getVMContext(), ArgList); } const RecordDecl *RD = RT->getDecl(); const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); assert(!(TySize % 8) && "Size of structure must be multiple of 8."); uint64_t LastOffset = 0; unsigned idx = 0; llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); // Iterate over fields in the struct/class and check if there are any aligned // double fields. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); i != e; ++i, ++idx) { const QualType Ty = i->getType(); const BuiltinType *BT = Ty->getAs(); if (!BT || BT->getKind() != BuiltinType::Double) continue; uint64_t Offset = Layout.getFieldOffset(idx); if (Offset % 64) // Ignore doubles that are not aligned. continue; // Add ((Offset - LastOffset) / 64) args of type i64. for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) ArgList.push_back(I64); // Add double type. ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); LastOffset = Offset + 64; } CoerceToIntArgs(TySize - LastOffset, IntArgList); ArgList.append(IntArgList.begin(), IntArgList.end()); return llvm::StructType::get(getVMContext(), ArgList); } llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, uint64_t Offset) const { if (OrigOffset + MinABIStackAlignInBytes > Offset) return nullptr; return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); } ABIArgInfo MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { Ty = useFirstFieldIfTransparentUnion(Ty); uint64_t OrigOffset = Offset; uint64_t TySize = getContext().getTypeSize(Ty); uint64_t Align = getContext().getTypeAlign(Ty) / 8; Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), (uint64_t)StackAlignInBytes); unsigned CurrOffset = llvm::alignTo(Offset, Align); Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { // Ignore empty aggregates. if (TySize == 0) return ABIArgInfo::getIgnore(); if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { Offset = OrigOffset + MinABIStackAlignInBytes; return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); } // If we have reached here, aggregates are passed directly by coercing to // another structure type. Padding is inserted if the offset of the // aggregate is unaligned. ABIArgInfo ArgInfo = ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, getPaddingType(OrigOffset, CurrOffset)); ArgInfo.setInReg(true); return ArgInfo; } // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // All integral types are promoted to the GPR width. if (Ty->isIntegralOrEnumerationType()) return extendType(Ty); return ABIArgInfo::getDirect( nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); } llvm::Type* MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { const RecordType *RT = RetTy->getAs(); SmallVector RTList; if (RT && RT->isStructureOrClassType()) { const RecordDecl *RD = RT->getDecl(); const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); unsigned FieldCnt = Layout.getFieldCount(); // N32/64 returns struct/classes in floating point registers if the // following conditions are met: // 1. The size of the struct/class is no larger than 128-bit. // 2. The struct/class has one or two fields all of which are floating // point types. // 3. The offset of the first field is zero (this follows what gcc does). // // Any other composite results are returned in integer registers. // if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); for (; b != e; ++b) { const BuiltinType *BT = b->getType()->getAs(); if (!BT || !BT->isFloatingPoint()) break; RTList.push_back(CGT.ConvertType(b->getType())); } if (b == e) return llvm::StructType::get(getVMContext(), RTList, RD->hasAttr()); RTList.clear(); } } CoerceToIntArgs(Size, RTList); return llvm::StructType::get(getVMContext(), RTList); } ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { uint64_t Size = getContext().getTypeSize(RetTy); if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); // O32 doesn't treat zero-sized structs differently from other structs. // However, N32/N64 ignores zero sized return values. if (!IsO32 && Size == 0) return ABIArgInfo::getIgnore(); if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { if (Size <= 128) { if (RetTy->isAnyComplexType()) return ABIArgInfo::getDirect(); // O32 returns integer vectors in registers and N32/N64 returns all small // aggregates in registers. if (!IsO32 || (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { ABIArgInfo ArgInfo = ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); ArgInfo.setInReg(true); return ArgInfo; } } return getNaturalAlignIndirect(RetTy); } // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); if (RetTy->isPromotableIntegerType()) return ABIArgInfo::getExtend(RetTy); if ((RetTy->isUnsignedIntegerOrEnumerationType() || RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) return ABIArgInfo::getSignExtend(RetTy); return ABIArgInfo::getDirect(); } void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { ABIArgInfo &RetInfo = FI.getReturnInfo(); if (!getCXXABI().classifyReturnType(FI)) RetInfo = classifyReturnType(FI.getReturnType()); // Check if a pointer to an aggregate is passed as a hidden argument. uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type, Offset); } Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType OrigTy) const { QualType Ty = OrigTy; // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. // Pointers are also promoted in the same way but this only matters for N32. unsigned SlotSizeInBits = IsO32 ? 32 : 64; unsigned PtrWidth = getTarget().getPointerWidth(0); bool DidPromote = false; if ((Ty->isIntegerType() && getContext().getIntWidth(Ty) < SlotSizeInBits) || (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { DidPromote = true; Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, Ty->isSignedIntegerType()); } auto TyInfo = getContext().getTypeInfoInChars(Ty); // The alignment of things in the argument area is never larger than // StackAlignInBytes. TyInfo.second = std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); // MinABIStackAlignInBytes is the size of argument slots on the stack. CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); // If there was a promotion, "unpromote" into a temporary. // TODO: can we just use a pointer into a subset of the original slot? if (DidPromote) { Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); // Truncate down to the right width. llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() : CGF.IntPtrTy); llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); if (OrigTy->isPointerType()) V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); CGF.Builder.CreateStore(V, Temp); Addr = Temp; } return Addr; } ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { int TySize = getContext().getTypeSize(Ty); // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) return ABIArgInfo::getSignExtend(Ty); return ABIArgInfo::getExtend(Ty); } bool MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { // This information comes from gcc's implementation, which seems to // as canonical as it gets. // Everything on MIPS is 4 bytes. Double-precision FP registers // are aliased to pairs of single-precision FP registers. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); // 0-31 are the general purpose registers, $0 - $31. // 32-63 are the floating-point registers, $f0 - $f31. // 64 and 65 are the multiply/divide registers, $hi and $lo. // 66 is the (notional, I think) register for signal-handler return. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); // 67-74 are the floating-point status registers, $fcc0 - $fcc7. // They are one bit wide and ignored here. // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. // (coprocessor 1 is the FP unit) // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. // 176-181 are the DSP accumulator registers. AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); return false; } //===----------------------------------------------------------------------===// // AVR ABI Implementation. //===----------------------------------------------------------------------===// namespace { class AVRTargetCodeGenInfo : public TargetCodeGenInfo { public: AVRTargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { } void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { if (GV->isDeclaration()) return; const auto *FD = dyn_cast_or_null(D); if (!FD) return; auto *Fn = cast(GV); if (FD->getAttr()) Fn->addFnAttr("interrupt"); if (FD->getAttr()) Fn->addFnAttr("signal"); } }; } //===----------------------------------------------------------------------===// // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. // Currently subclassed only to implement custom OpenCL C function attribute // handling. //===----------------------------------------------------------------------===// namespace { class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { public: TCETargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const override; }; void TCETargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { if (GV->isDeclaration()) return; const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; llvm::Function *F = cast(GV); if (M.getLangOpts().OpenCL) { if (FD->hasAttr()) { // OpenCL C Kernel functions are not subject to inlining F->addFnAttr(llvm::Attribute::NoInline); const ReqdWorkGroupSizeAttr *Attr = FD->getAttr(); if (Attr) { // Convert the reqd_work_group_size() attributes to metadata. llvm::LLVMContext &Context = F->getContext(); llvm::NamedMDNode *OpenCLMetadata = M.getModule().getOrInsertNamedMetadata( "opencl.kernel_wg_size_info"); SmallVector Operands; Operands.push_back(llvm::ConstantAsMetadata::get(F)); Operands.push_back( llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); Operands.push_back( llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); Operands.push_back( llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); // Add a boolean constant operand for "required" (true) or "hint" // (false) for implementing the work_group_size_hint attr later. // Currently always true as the hint is not yet implemented. Operands.push_back( llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); } } } } } //===----------------------------------------------------------------------===// // Hexagon ABI Implementation //===----------------------------------------------------------------------===// namespace { class HexagonABIInfo : public ABIInfo { public: HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} private: ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyArgumentType(QualType RetTy) const; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; }; class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { public: HexagonTargetCodeGenInfo(CodeGenTypes &CGT) :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { return 29; } }; } void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type); } ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { if (!isAggregateTypeForABI(Ty)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) : ABIArgInfo::getDirect()); } if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // Ignore empty records. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); uint64_t Size = getContext().getTypeSize(Ty); if (Size > 64) return getNaturalAlignIndirect(Ty, /*ByVal=*/true); // Pass in the smallest viable integer type. else if (Size > 32) return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); else if (Size > 16) return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); else if (Size > 8) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); else return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); } ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); // Large vector types should be returned via memory. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) return getNaturalAlignIndirect(RetTy); if (!isAggregateTypeForABI(RetTy)) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = RetTy->getAs()) RetTy = EnumTy->getDecl()->getIntegerType(); return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) : ABIArgInfo::getDirect()); } if (isEmptyRecord(getContext(), RetTy, true)) return ABIArgInfo::getIgnore(); // Aggregates <= 8 bytes are returned in r0; other aggregates // are returned indirectly. uint64_t Size = getContext().getTypeSize(RetTy); if (Size <= 64) { // Return in the smallest viable integer type. if (Size <= 8) return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); if (Size <= 16) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); if (Size <= 32) return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); } return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); } Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { // FIXME: Someone needs to audit that this handle alignment correctly. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(4), /*AllowHigherAlign*/ true); } //===----------------------------------------------------------------------===// // Lanai ABI Implementation //===----------------------------------------------------------------------===// namespace { class LanaiABIInfo : public DefaultABIInfo { public: LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} bool shouldUseInReg(QualType Ty, CCState &State) const; void computeInfo(CGFunctionInfo &FI) const override { CCState State(FI.getCallingConvention()); // Lanai uses 4 registers to pass arguments unless the function has the // regparm attribute set. if (FI.getHasRegParm()) { State.FreeRegs = FI.getRegParm(); } else { State.FreeRegs = 4; } if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &I : FI.arguments()) I.info = classifyArgumentType(I.type, State); } ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; }; } // end anonymous namespace bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { unsigned Size = getContext().getTypeSize(Ty); unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; if (SizeInRegs == 0) return false; if (SizeInRegs > State.FreeRegs) { State.FreeRegs = 0; return false; } State.FreeRegs -= SizeInRegs; return true; } ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, CCState &State) const { if (!ByVal) { if (State.FreeRegs) { --State.FreeRegs; // Non-byval indirects just use one pointer. return getNaturalAlignIndirectInReg(Ty); } return getNaturalAlignIndirect(Ty, false); } // Compute the byval alignment. const unsigned MinABIStackAlignInBytes = 4; unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, /*Realign=*/TypeAlign > MinABIStackAlignInBytes); } ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { // Check with the C++ ABI first. const RecordType *RT = Ty->getAs(); if (RT) { CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); if (RAA == CGCXXABI::RAA_Indirect) { return getIndirectResult(Ty, /*ByVal=*/false, State); } else if (RAA == CGCXXABI::RAA_DirectInMemory) { return getNaturalAlignIndirect(Ty, /*ByRef=*/true); } } if (isAggregateTypeForABI(Ty)) { // Structures with flexible arrays are always indirect. if (RT && RT->getDecl()->hasFlexibleArrayMember()) return getIndirectResult(Ty, /*ByVal=*/true, State); // Ignore empty structs/unions. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); llvm::LLVMContext &LLVMContext = getVMContext(); unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; if (SizeInRegs <= State.FreeRegs) { llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); SmallVector Elements(SizeInRegs, Int32); llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); State.FreeRegs -= SizeInRegs; return ABIArgInfo::getDirectInReg(Result); } else { State.FreeRegs = 0; } return getIndirectResult(Ty, true, State); } // Treat an enum type as its underlying type. if (const auto *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); bool InReg = shouldUseInReg(Ty, State); if (Ty->isPromotableIntegerType()) { if (InReg) return ABIArgInfo::getDirectInReg(); return ABIArgInfo::getExtend(Ty); } if (InReg) return ABIArgInfo::getDirectInReg(); return ABIArgInfo::getDirect(); } namespace { class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { public: LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {} }; } //===----------------------------------------------------------------------===// // AMDGPU ABI Implementation //===----------------------------------------------------------------------===// namespace { class AMDGPUABIInfo final : public DefaultABIInfo { private: static const unsigned MaxNumRegsForArgsRet = 16; unsigned numRegsForType(QualType Ty) const; bool isHomogeneousAggregateBaseType(QualType Ty) const override; bool isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const override; public: explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} ABIArgInfo classifyReturnType(QualType RetTy) const; ABIArgInfo classifyKernelArgumentType(QualType Ty) const; ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; void computeInfo(CGFunctionInfo &FI) const override; }; bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { return true; } bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( const Type *Base, uint64_t Members) const { uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; // Homogeneous Aggregates may occupy at most 16 registers. return Members * NumRegs <= MaxNumRegsForArgsRet; } /// Estimate number of registers the type will use when passed in registers. unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { unsigned NumRegs = 0; if (const VectorType *VT = Ty->getAs()) { // Compute from the number of elements. The reported size is based on the // in-memory size, which includes the padding 4th element for 3-vectors. QualType EltTy = VT->getElementType(); unsigned EltSize = getContext().getTypeSize(EltTy); // 16-bit element vectors should be passed as packed. if (EltSize == 16) return (VT->getNumElements() + 1) / 2; unsigned EltNumRegs = (EltSize + 31) / 32; return EltNumRegs * VT->getNumElements(); } if (const RecordType *RT = Ty->getAs()) { const RecordDecl *RD = RT->getDecl(); assert(!RD->hasFlexibleArrayMember()); for (const FieldDecl *Field : RD->fields()) { QualType FieldTy = Field->getType(); NumRegs += numRegsForType(FieldTy); } return NumRegs; } return (getContext().getTypeSize(Ty) + 31) / 32; } void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { llvm::CallingConv::ID CC = FI.getCallingConvention(); if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); unsigned NumRegsLeft = MaxNumRegsForArgsRet; for (auto &Arg : FI.arguments()) { if (CC == llvm::CallingConv::AMDGPU_KERNEL) { Arg.info = classifyKernelArgumentType(Arg.type); } else { Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); } } } ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { if (isAggregateTypeForABI(RetTy)) { // Records with non-trivial destructors/copy-constructors should not be // returned by value. if (!getRecordArgABI(RetTy, getCXXABI())) { // Ignore empty structs/unions. if (isEmptyRecord(getContext(), RetTy, true)) return ABIArgInfo::getIgnore(); // Lower single-element structs to just return a regular value. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); if (const RecordType *RT = RetTy->getAs()) { const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return DefaultABIInfo::classifyReturnType(RetTy); } // Pack aggregates <= 4 bytes into single VGPR or pair. uint64_t Size = getContext().getTypeSize(RetTy); if (Size <= 16) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); if (Size <= 32) return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); if (Size <= 64) { llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); } if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) return ABIArgInfo::getDirect(); } } // Otherwise just do the default thing. return DefaultABIInfo::classifyReturnType(RetTy); } /// For kernels all parameters are really passed in a special buffer. It doesn't /// make sense to pass anything byval, so everything must be direct. ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { Ty = useFirstFieldIfTransparentUnion(Ty); // TODO: Can we omit empty structs? // Coerce single element structs to its element. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); // If we set CanBeFlattened to true, CodeGen will expand the struct to its // individual elements, which confuses the Clover OpenCL backend; therefore we // have to set it to false here. Other args of getDirect() are just defaults. return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); } ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const { assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); Ty = useFirstFieldIfTransparentUnion(Ty); if (isAggregateTypeForABI(Ty)) { // Records with non-trivial destructors/copy-constructors should not be // passed by value. if (auto RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // Ignore empty structs/unions. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); // Lower single-element structs to just pass a regular value. TODO: We // could do reasonable-size multiple-element structs too, using getExpand(), // though watch out for things like bitfields. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); if (const RecordType *RT = Ty->getAs()) { const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return DefaultABIInfo::classifyArgumentType(Ty); } // Pack aggregates <= 8 bytes into single VGPR or pair. uint64_t Size = getContext().getTypeSize(Ty); if (Size <= 64) { unsigned NumRegs = (Size + 31) / 32; NumRegsLeft -= std::min(NumRegsLeft, NumRegs); if (Size <= 16) return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); if (Size <= 32) return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); // XXX: Should this be i64 instead, and should the limit increase? llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); } if (NumRegsLeft > 0) { unsigned NumRegs = numRegsForType(Ty); if (NumRegsLeft >= NumRegs) { NumRegsLeft -= NumRegs; return ABIArgInfo::getDirect(); } } } // Otherwise just do the default thing. ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); if (!ArgInfo.isIndirect()) { unsigned NumRegs = numRegsForType(Ty); NumRegsLeft -= std::min(NumRegs, NumRegsLeft); } return ArgInfo; } class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { public: AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const override; unsigned getOpenCLKernelCallingConv() const override; llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, llvm::PointerType *T, QualType QT) const override; LangAS getASTAllocaAddressSpace() const override { return getLangASFromTargetAS( getABIInfo().getDataLayout().getAllocaAddrSpace()); } LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const override; llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const override; llvm::Function * createEnqueuedBlockKernel(CodeGenFunction &CGF, llvm::Function *BlockInvokeFunc, llvm::Value *BlockLiteral) const override; bool shouldEmitStaticExternCAliases() const override; void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; }; } void AMDGPUTargetCodeGenInfo::setTargetAttributes( const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { if (GV->isDeclaration()) return; const FunctionDecl *FD = dyn_cast_or_null(D); if (!FD) return; llvm::Function *F = cast(GV); const auto *ReqdWGS = M.getLangOpts().OpenCL ? FD->getAttr() : nullptr; if (M.getLangOpts().OpenCL && FD->hasAttr() && (M.getTriple().getOS() == llvm::Triple::AMDHSA)) F->addFnAttr("amdgpu-implicitarg-num-bytes", "48"); const auto *FlatWGS = FD->getAttr(); if (ReqdWGS || FlatWGS) { unsigned Min = FlatWGS ? FlatWGS->getMin() : 0; unsigned Max = FlatWGS ? FlatWGS->getMax() : 0; if (ReqdWGS && Min == 0 && Max == 0) Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); if (Min != 0) { assert(Min <= Max && "Min must be less than or equal Max"); std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); } else assert(Max == 0 && "Max must be zero"); } if (const auto *Attr = FD->getAttr()) { unsigned Min = Attr->getMin(); unsigned Max = Attr->getMax(); if (Min != 0) { assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); std::string AttrVal = llvm::utostr(Min); if (Max != 0) AttrVal = AttrVal + "," + llvm::utostr(Max); F->addFnAttr("amdgpu-waves-per-eu", AttrVal); } else assert(Max == 0 && "Max must be zero"); } if (const auto *Attr = FD->getAttr()) { unsigned NumSGPR = Attr->getNumSGPR(); if (NumSGPR != 0) F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); } if (const auto *Attr = FD->getAttr()) { uint32_t NumVGPR = Attr->getNumVGPR(); if (NumVGPR != 0) F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); } } unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { return llvm::CallingConv::AMDGPU_KERNEL; } // Currently LLVM assumes null pointers always have value 0, // which results in incorrectly transformed IR. Therefore, instead of // emitting null pointers in private and local address spaces, a null // pointer in generic address space is emitted which is casted to a // pointer in local or private address space. llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, QualType QT) const { if (CGM.getContext().getTargetNullPointerValue(QT) == 0) return llvm::ConstantPointerNull::get(PT); auto &Ctx = CGM.getContext(); auto NPT = llvm::PointerType::get(PT->getElementType(), Ctx.getTargetAddressSpace(LangAS::opencl_generic)); return llvm::ConstantExpr::getAddrSpaceCast( llvm::ConstantPointerNull::get(NPT), PT); } LangAS AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const { assert(!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && "Address space agnostic languages only"); LangAS DefaultGlobalAS = getLangASFromTargetAS( CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); if (!D) return DefaultGlobalAS; LangAS AddrSpace = D->getType().getAddressSpace(); assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); if (AddrSpace != LangAS::Default) return AddrSpace; if (CGM.isTypeConstant(D->getType(), false)) { if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) return ConstAS.getValue(); } return DefaultGlobalAS; } llvm::SyncScope::ID AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const { StringRef Name; switch (S) { case SyncScope::OpenCLWorkGroup: Name = "workgroup"; break; case SyncScope::OpenCLDevice: Name = "agent"; break; case SyncScope::OpenCLAllSVMDevices: Name = ""; break; case SyncScope::OpenCLSubGroup: Name = "subgroup"; } return C.getOrInsertSyncScopeID(Name); } bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { return false; } void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( const FunctionType *&FT) const { FT = getABIInfo().getContext().adjustFunctionType( FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); } //===----------------------------------------------------------------------===// // SPARC v8 ABI Implementation. // Based on the SPARC Compliance Definition version 2.4.1. // // Ensures that complex values are passed in registers. // namespace { class SparcV8ABIInfo : public DefaultABIInfo { public: SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} private: ABIArgInfo classifyReturnType(QualType RetTy) const; void computeInfo(CGFunctionInfo &FI) const override; }; } // end anonymous namespace ABIArgInfo SparcV8ABIInfo::classifyReturnType(QualType Ty) const { if (Ty->isAnyComplexType()) { return ABIArgInfo::getDirect(); } else { return DefaultABIInfo::classifyReturnType(Ty); } } void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); for (auto &Arg : FI.arguments()) Arg.info = classifyArgumentType(Arg.type); } namespace { class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { public: SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {} }; } // end anonymous namespace //===----------------------------------------------------------------------===// // SPARC v9 ABI Implementation. // Based on the SPARC Compliance Definition version 2.4.1. // // Function arguments a mapped to a nominal "parameter array" and promoted to // registers depending on their type. Each argument occupies 8 or 16 bytes in // the array, structs larger than 16 bytes are passed indirectly. // // One case requires special care: // // struct mixed { // int i; // float f; // }; // // When a struct mixed is passed by value, it only occupies 8 bytes in the // parameter array, but the int is passed in an integer register, and the float // is passed in a floating point register. This is represented as two arguments // with the LLVM IR inreg attribute: // // declare void f(i32 inreg %i, float inreg %f) // // The code generator will only allocate 4 bytes from the parameter array for // the inreg arguments. All other arguments are allocated a multiple of 8 // bytes. // namespace { class SparcV9ABIInfo : public ABIInfo { public: SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} private: ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; void computeInfo(CGFunctionInfo &FI) const override; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; // Coercion type builder for structs passed in registers. The coercion type // serves two purposes: // // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' // in registers. // 2. Expose aligned floating point elements as first-level elements, so the // code generator knows to pass them in floating point registers. // // We also compute the InReg flag which indicates that the struct contains // aligned 32-bit floats. // struct CoerceBuilder { llvm::LLVMContext &Context; const llvm::DataLayout &DL; SmallVector Elems; uint64_t Size; bool InReg; CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) : Context(c), DL(dl), Size(0), InReg(false) {} // Pad Elems with integers until Size is ToSize. void pad(uint64_t ToSize) { assert(ToSize >= Size && "Cannot remove elements"); if (ToSize == Size) return; // Finish the current 64-bit word. uint64_t Aligned = llvm::alignTo(Size, 64); if (Aligned > Size && Aligned <= ToSize) { Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); Size = Aligned; } // Add whole 64-bit words. while (Size + 64 <= ToSize) { Elems.push_back(llvm::Type::getInt64Ty(Context)); Size += 64; } // Final in-word padding. if (Size < ToSize) { Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); Size = ToSize; } } // Add a floating point element at Offset. void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { // Unaligned floats are treated as integers. if (Offset % Bits) return; // The InReg flag is only required if there are any floats < 64 bits. if (Bits < 64) InReg = true; pad(Offset); Elems.push_back(Ty); Size = Offset + Bits; } // Add a struct type to the coercion type, starting at Offset (in bits). void addStruct(uint64_t Offset, llvm::StructType *StrTy) { const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { llvm::Type *ElemTy = StrTy->getElementType(i); uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); switch (ElemTy->getTypeID()) { case llvm::Type::StructTyID: addStruct(ElemOffset, cast(ElemTy)); break; case llvm::Type::FloatTyID: addFloat(ElemOffset, ElemTy, 32); break; case llvm::Type::DoubleTyID: addFloat(ElemOffset, ElemTy, 64); break; case llvm::Type::FP128TyID: addFloat(ElemOffset, ElemTy, 128); break; case llvm::Type::PointerTyID: if (ElemOffset % 64 == 0) { pad(ElemOffset); Elems.push_back(ElemTy); Size += 64; } break; default: break; } } } // Check if Ty is a usable substitute for the coercion type. bool isUsableType(llvm::StructType *Ty) const { return llvm::makeArrayRef(Elems) == Ty->elements(); } // Get the coercion type as a literal struct type. llvm::Type *getType() const { if (Elems.size() == 1) return Elems.front(); else return llvm::StructType::get(Context, Elems); } }; }; } // end anonymous namespace ABIArgInfo SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { if (Ty->isVoidType()) return ABIArgInfo::getIgnore(); uint64_t Size = getContext().getTypeSize(Ty); // Anything too big to fit in registers is passed with an explicit indirect // pointer / sret pointer. if (Size > SizeLimit) return getNaturalAlignIndirect(Ty, /*ByVal=*/false); // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // Integer types smaller than a register are extended. if (Size < 64 && Ty->isIntegerType()) return ABIArgInfo::getExtend(Ty); // Other non-aggregates go in registers. if (!isAggregateTypeForABI(Ty)) return ABIArgInfo::getDirect(); // If a C++ object has either a non-trivial copy constructor or a non-trivial // destructor, it is passed with an explicit indirect pointer / sret pointer. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); // This is a small aggregate type that should be passed in registers. // Build a coercion type from the LLVM struct type. llvm::StructType *StrTy = dyn_cast(CGT.ConvertType(Ty)); if (!StrTy) return ABIArgInfo::getDirect(); CoerceBuilder CB(getVMContext(), getDataLayout()); CB.addStruct(0, StrTy); CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); // Try to use the original type for coercion. llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); if (CB.InReg) return ABIArgInfo::getDirectInReg(CoerceTy); else return ABIArgInfo::getDirect(CoerceTy); } Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { ABIArgInfo AI = classifyType(Ty, 16 * 8); llvm::Type *ArgTy = CGT.ConvertType(Ty); if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) AI.setCoerceToType(ArgTy); CharUnits SlotSize = CharUnits::fromQuantity(8); CGBuilderTy &Builder = CGF.Builder; Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); auto TypeInfo = getContext().getTypeInfoInChars(Ty); Address ArgAddr = Address::invalid(); CharUnits Stride; switch (AI.getKind()) { case ABIArgInfo::Expand: case ABIArgInfo::CoerceAndExpand: case ABIArgInfo::InAlloca: llvm_unreachable("Unsupported ABI kind for va_arg"); case ABIArgInfo::Extend: { Stride = SlotSize; CharUnits Offset = SlotSize - TypeInfo.first; ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); break; } case ABIArgInfo::Direct: { auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); ArgAddr = Addr; break; } case ABIArgInfo::Indirect: Stride = SlotSize; ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), TypeInfo.second); break; case ABIArgInfo::Ignore: return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); } // Update VAList. llvm::Value *NextPtr = Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next"); Builder.CreateStore(NextPtr, VAListAddr); return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); } void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); for (auto &I : FI.arguments()) I.info = classifyType(I.type, 16 * 8); } namespace { class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { public: SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { return 14; } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const override; }; } // end anonymous namespace bool SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { // This is calculated from the LLVM and GCC tables and verified // against gcc output. AFAIK all ABIs use the same encoding. CodeGen::CGBuilderTy &Builder = CGF.Builder; llvm::IntegerType *i8 = CGF.Int8Ty; llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); // 0-31: the 8-byte general-purpose registers AssignToArrayRange(Builder, Address, Eight8, 0, 31); // 32-63: f0-31, the 4-byte floating-point registers AssignToArrayRange(Builder, Address, Four8, 32, 63); // Y = 64 // PSR = 65 // WIM = 66 // TBR = 67 // PC = 68 // NPC = 69 // FSR = 70 // CSR = 71 AssignToArrayRange(Builder, Address, Eight8, 64, 71); // 72-87: d0-15, the 8-byte floating-point registers AssignToArrayRange(Builder, Address, Eight8, 72, 87); return false; } // ARC ABI implementation. namespace { class ARCABIInfo : public DefaultABIInfo { public: using DefaultABIInfo::DefaultABIInfo; private: Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { if (!State.FreeRegs) return; if (Info.isIndirect() && Info.getInReg()) State.FreeRegs--; else if (Info.isDirect() && Info.getInReg()) { unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; if (sz < State.FreeRegs) State.FreeRegs -= sz; else State.FreeRegs = 0; } } void computeInfo(CGFunctionInfo &FI) const override { CCState State(FI.getCallingConvention()); // ARC uses 8 registers to pass arguments. State.FreeRegs = 8; if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); updateState(FI.getReturnInfo(), FI.getReturnType(), State); for (auto &I : FI.arguments()) { I.info = classifyArgumentType(I.type, State.FreeRegs); updateState(I.info, I.type, State); } } ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; ABIArgInfo getIndirectByValue(QualType Ty) const; ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; ABIArgInfo classifyReturnType(QualType RetTy) const; }; class ARCTargetCodeGenInfo : public TargetCodeGenInfo { public: ARCTargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new ARCABIInfo(CGT)) {} }; ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : getNaturalAlignIndirect(Ty, false); } ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { // Compute the byval alignment. const unsigned MinABIStackAlignInBytes = 4; unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, TypeAlign > MinABIStackAlignInBytes); } Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, getContext().getTypeInfoInChars(Ty), CharUnits::fromQuantity(4), true); } ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, uint8_t FreeRegs) const { // Handle the generic C++ ABI. const RecordType *RT = Ty->getAs(); if (RT) { CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); if (RAA == CGCXXABI::RAA_Indirect) return getIndirectByRef(Ty, FreeRegs > 0); if (RAA == CGCXXABI::RAA_DirectInMemory) return getIndirectByValue(Ty); } // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; if (isAggregateTypeForABI(Ty)) { // Structures with flexible arrays are always indirect. if (RT && RT->getDecl()->hasFlexibleArrayMember()) return getIndirectByValue(Ty); // Ignore empty structs/unions. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); llvm::LLVMContext &LLVMContext = getVMContext(); llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); SmallVector Elements(SizeInRegs, Int32); llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); return FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg(Result) : ABIArgInfo::getDirect(Result, 0, nullptr, false); } return Ty->isPromotableIntegerType() ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : ABIArgInfo::getExtend(Ty)) : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : ABIArgInfo::getDirect()); } ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isAnyComplexType()) return ABIArgInfo::getDirectInReg(); // Arguments of size > 4 registers are indirect. auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; if (RetSize > 4) return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); return DefaultABIInfo::classifyReturnType(RetTy); } } // End anonymous namespace. //===----------------------------------------------------------------------===// // XCore ABI Implementation //===----------------------------------------------------------------------===// namespace { /// A SmallStringEnc instance is used to build up the TypeString by passing /// it by reference between functions that append to it. typedef llvm::SmallString<128> SmallStringEnc; /// TypeStringCache caches the meta encodings of Types. /// /// The reason for caching TypeStrings is two fold: /// 1. To cache a type's encoding for later uses; /// 2. As a means to break recursive member type inclusion. /// /// A cache Entry can have a Status of: /// NonRecursive: The type encoding is not recursive; /// Recursive: The type encoding is recursive; /// Incomplete: An incomplete TypeString; /// IncompleteUsed: An incomplete TypeString that has been used in a /// Recursive type encoding. /// /// A NonRecursive entry will have all of its sub-members expanded as fully /// as possible. Whilst it may contain types which are recursive, the type /// itself is not recursive and thus its encoding may be safely used whenever /// the type is encountered. /// /// A Recursive entry will have all of its sub-members expanded as fully as /// possible. The type itself is recursive and it may contain other types which /// are recursive. The Recursive encoding must not be used during the expansion /// of a recursive type's recursive branch. For simplicity the code uses /// IncompleteCount to reject all usage of Recursive encodings for member types. /// /// An Incomplete entry is always a RecordType and only encodes its /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and /// are placed into the cache during type expansion as a means to identify and /// handle recursive inclusion of types as sub-members. If there is recursion /// the entry becomes IncompleteUsed. /// /// During the expansion of a RecordType's members: /// /// If the cache contains a NonRecursive encoding for the member type, the /// cached encoding is used; /// /// If the cache contains a Recursive encoding for the member type, the /// cached encoding is 'Swapped' out, as it may be incorrect, and... /// /// If the member is a RecordType, an Incomplete encoding is placed into the /// cache to break potential recursive inclusion of itself as a sub-member; /// /// Once a member RecordType has been expanded, its temporary incomplete /// entry is removed from the cache. If a Recursive encoding was swapped out /// it is swapped back in; /// /// If an incomplete entry is used to expand a sub-member, the incomplete /// entry is marked as IncompleteUsed. The cache keeps count of how many /// IncompleteUsed entries it currently contains in IncompleteUsedCount; /// /// If a member's encoding is found to be a NonRecursive or Recursive viz: /// IncompleteUsedCount==0, the member's encoding is added to the cache. /// Else the member is part of a recursive type and thus the recursion has /// been exited too soon for the encoding to be correct for the member. /// class TypeStringCache { enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; struct Entry { std::string Str; // The encoded TypeString for the type. enum Status State; // Information about the encoding in 'Str'. std::string Swapped; // A temporary place holder for a Recursive encoding // during the expansion of RecordType's members. }; std::map Map; unsigned IncompleteCount; // Number of Incomplete entries in the Map. unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. public: TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); bool removeIncomplete(const IdentifierInfo *ID); void addIfComplete(const IdentifierInfo *ID, StringRef Str, bool IsRecursive); StringRef lookupStr(const IdentifierInfo *ID); }; /// TypeString encodings for enum & union fields must be order. /// FieldEncoding is a helper for this ordering process. class FieldEncoding { bool HasName; std::string Enc; public: FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} StringRef str() { return Enc; } bool operator<(const FieldEncoding &rhs) const { if (HasName != rhs.HasName) return HasName; return Enc < rhs.Enc; } }; class XCoreABIInfo : public DefaultABIInfo { public: XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; }; class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { mutable TypeStringCache TSC; public: XCoreTargetCodeGenInfo(CodeGenTypes &CGT) :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const override; }; } // End anonymous namespace. // TODO: this implementation is likely now redundant with the default // EmitVAArg. Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { CGBuilderTy &Builder = CGF.Builder; // Get the VAList. CharUnits SlotSize = CharUnits::fromQuantity(4); Address AP(Builder.CreateLoad(VAListAddr), SlotSize); // Handle the argument. ABIArgInfo AI = classifyArgumentType(Ty); CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); llvm::Type *ArgTy = CGT.ConvertType(Ty); if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) AI.setCoerceToType(ArgTy); llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); Address Val = Address::invalid(); CharUnits ArgSize = CharUnits::Zero(); switch (AI.getKind()) { case ABIArgInfo::Expand: case ABIArgInfo::CoerceAndExpand: case ABIArgInfo::InAlloca: llvm_unreachable("Unsupported ABI kind for va_arg"); case ABIArgInfo::Ignore: Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); ArgSize = CharUnits::Zero(); break; case ABIArgInfo::Extend: case ABIArgInfo::Direct: Val = Builder.CreateBitCast(AP, ArgPtrTy); ArgSize = CharUnits::fromQuantity( getDataLayout().getTypeAllocSize(AI.getCoerceToType())); ArgSize = ArgSize.alignTo(SlotSize); break; case ABIArgInfo::Indirect: Val = Builder.CreateElementBitCast(AP, ArgPtrTy); Val = Address(Builder.CreateLoad(Val), TypeAlign); ArgSize = SlotSize; break; } // Increment the VAList. if (!ArgSize.isZero()) { llvm::Value *APN = Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize); Builder.CreateStore(APN, VAListAddr); } return Val; } /// During the expansion of a RecordType, an incomplete TypeString is placed /// into the cache as a means to identify and break recursion. /// If there is a Recursive encoding in the cache, it is swapped out and will /// be reinserted by removeIncomplete(). /// All other types of encoding should have been used rather than arriving here. void TypeStringCache::addIncomplete(const IdentifierInfo *ID, std::string StubEnc) { if (!ID) return; Entry &E = Map[ID]; assert( (E.Str.empty() || E.State == Recursive) && "Incorrectly use of addIncomplete"); assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); E.Swapped.swap(E.Str); // swap out the Recursive E.Str.swap(StubEnc); E.State = Incomplete; ++IncompleteCount; } /// Once the RecordType has been expanded, the temporary incomplete TypeString /// must be removed from the cache. /// If a Recursive was swapped out by addIncomplete(), it will be replaced. /// Returns true if the RecordType was defined recursively. bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { if (!ID) return false; auto I = Map.find(ID); assert(I != Map.end() && "Entry not present"); Entry &E = I->second; assert( (E.State == Incomplete || E.State == IncompleteUsed) && "Entry must be an incomplete type"); bool IsRecursive = false; if (E.State == IncompleteUsed) { // We made use of our Incomplete encoding, thus we are recursive. IsRecursive = true; --IncompleteUsedCount; } if (E.Swapped.empty()) Map.erase(I); else { // Swap the Recursive back. E.Swapped.swap(E.Str); E.Swapped.clear(); E.State = Recursive; } --IncompleteCount; return IsRecursive; } /// Add the encoded TypeString to the cache only if it is NonRecursive or /// Recursive (viz: all sub-members were expanded as fully as possible). void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, bool IsRecursive) { if (!ID || IncompleteUsedCount) return; // No key or it is is an incomplete sub-type so don't add. Entry &E = Map[ID]; if (IsRecursive && !E.Str.empty()) { assert(E.State==Recursive && E.Str.size() == Str.size() && "This is not the same Recursive entry"); // The parent container was not recursive after all, so we could have used // this Recursive sub-member entry after all, but we assumed the worse when // we started viz: IncompleteCount!=0. return; } assert(E.Str.empty() && "Entry already present"); E.Str = Str.str(); E.State = IsRecursive? Recursive : NonRecursive; } /// Return a cached TypeString encoding for the ID. If there isn't one, or we /// are recursively expanding a type (IncompleteCount != 0) and the cached /// encoding is Recursive, return an empty StringRef. StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { if (!ID) return StringRef(); // We have no key. auto I = Map.find(ID); if (I == Map.end()) return StringRef(); // We have no encoding. Entry &E = I->second; if (E.State == Recursive && IncompleteCount) return StringRef(); // We don't use Recursive encodings for member types. if (E.State == Incomplete) { // The incomplete type is being used to break out of recursion. E.State = IncompleteUsed; ++IncompleteUsedCount; } return E.Str; } /// The XCore ABI includes a type information section that communicates symbol /// type information to the linker. The linker uses this information to verify /// safety/correctness of things such as array bound and pointers et al. /// The ABI only requires C (and XC) language modules to emit TypeStrings. /// This type information (TypeString) is emitted into meta data for all global /// symbols: definitions, declarations, functions & variables. /// /// The TypeString carries type, qualifier, name, size & value details. /// Please see 'Tools Development Guide' section 2.16.2 for format details: /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf /// The output is tested by test/CodeGen/xcore-stringtype.c. /// static bool getTypeString(SmallStringEnc &Enc, const Decl *D, CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { SmallStringEnc Enc; if (getTypeString(Enc, D, CGM, TSC)) { llvm::LLVMContext &Ctx = CGM.getModule().getContext(); llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Enc.str())}; llvm::NamedMDNode *MD = CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); } } //===----------------------------------------------------------------------===// // SPIR ABI Implementation //===----------------------------------------------------------------------===// namespace { class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { public: SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} unsigned getOpenCLKernelCallingConv() const override; }; } // End anonymous namespace. namespace clang { namespace CodeGen { void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { DefaultABIInfo SPIRABI(CGM.getTypes()); SPIRABI.computeInfo(FI); } } } unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { return llvm::CallingConv::SPIR_KERNEL; } static bool appendType(SmallStringEnc &Enc, QualType QType, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); /// Helper function for appendRecordType(). /// Builds a SmallVector containing the encoded field types in declaration /// order. static bool extractFieldType(SmallVectorImpl &FE, const RecordDecl *RD, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { for (const auto *Field : RD->fields()) { SmallStringEnc Enc; Enc += "m("; Enc += Field->getName(); Enc += "){"; if (Field->isBitField()) { Enc += "b("; llvm::raw_svector_ostream OS(Enc); OS << Field->getBitWidthValue(CGM.getContext()); Enc += ':'; } if (!appendType(Enc, Field->getType(), CGM, TSC)) return false; if (Field->isBitField()) Enc += ')'; Enc += '}'; FE.emplace_back(!Field->getName().empty(), Enc); } return true; } /// Appends structure and union types to Enc and adds encoding to cache. /// Recursively calls appendType (via extractFieldType) for each field. /// Union types have their fields ordered according to the ABI. static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC, const IdentifierInfo *ID) { // Append the cached TypeString if we have one. StringRef TypeString = TSC.lookupStr(ID); if (!TypeString.empty()) { Enc += TypeString; return true; } // Start to emit an incomplete TypeString. size_t Start = Enc.size(); Enc += (RT->isUnionType()? 'u' : 's'); Enc += '('; if (ID) Enc += ID->getName(); Enc += "){"; // We collect all encoded fields and order as necessary. bool IsRecursive = false; const RecordDecl *RD = RT->getDecl()->getDefinition(); if (RD && !RD->field_empty()) { // An incomplete TypeString stub is placed in the cache for this RecordType // so that recursive calls to this RecordType will use it whilst building a // complete TypeString for this RecordType. SmallVector FE; std::string StubEnc(Enc.substr(Start).str()); StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. TSC.addIncomplete(ID, std::move(StubEnc)); if (!extractFieldType(FE, RD, CGM, TSC)) { (void) TSC.removeIncomplete(ID); return false; } IsRecursive = TSC.removeIncomplete(ID); // The ABI requires unions to be sorted but not structures. // See FieldEncoding::operator< for sort algorithm. if (RT->isUnionType()) llvm::sort(FE); // We can now complete the TypeString. unsigned E = FE.size(); for (unsigned I = 0; I != E; ++I) { if (I) Enc += ','; Enc += FE[I].str(); } } Enc += '}'; TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); return true; } /// Appends enum types to Enc and adds the encoding to the cache. static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, TypeStringCache &TSC, const IdentifierInfo *ID) { // Append the cached TypeString if we have one. StringRef TypeString = TSC.lookupStr(ID); if (!TypeString.empty()) { Enc += TypeString; return true; } size_t Start = Enc.size(); Enc += "e("; if (ID) Enc += ID->getName(); Enc += "){"; // We collect all encoded enumerations and order them alphanumerically. if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { SmallVector FE; for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; ++I) { SmallStringEnc EnumEnc; EnumEnc += "m("; EnumEnc += I->getName(); EnumEnc += "){"; I->getInitVal().toString(EnumEnc); EnumEnc += '}'; FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); } llvm::sort(FE); unsigned E = FE.size(); for (unsigned I = 0; I != E; ++I) { if (I) Enc += ','; Enc += FE[I].str(); } } Enc += '}'; TSC.addIfComplete(ID, Enc.substr(Start), false); return true; } /// Appends type's qualifier to Enc. /// This is done prior to appending the type's encoding. static void appendQualifier(SmallStringEnc &Enc, QualType QT) { // Qualifiers are emitted in alphabetical order. static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; int Lookup = 0; if (QT.isConstQualified()) Lookup += 1<<0; if (QT.isRestrictQualified()) Lookup += 1<<1; if (QT.isVolatileQualified()) Lookup += 1<<2; Enc += Table[Lookup]; } /// Appends built-in types to Enc. static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { const char *EncType; switch (BT->getKind()) { case BuiltinType::Void: EncType = "0"; break; case BuiltinType::Bool: EncType = "b"; break; case BuiltinType::Char_U: EncType = "uc"; break; case BuiltinType::UChar: EncType = "uc"; break; case BuiltinType::SChar: EncType = "sc"; break; case BuiltinType::UShort: EncType = "us"; break; case BuiltinType::Short: EncType = "ss"; break; case BuiltinType::UInt: EncType = "ui"; break; case BuiltinType::Int: EncType = "si"; break; case BuiltinType::ULong: EncType = "ul"; break; case BuiltinType::Long: EncType = "sl"; break; case BuiltinType::ULongLong: EncType = "ull"; break; case BuiltinType::LongLong: EncType = "sll"; break; case BuiltinType::Float: EncType = "ft"; break; case BuiltinType::Double: EncType = "d"; break; case BuiltinType::LongDouble: EncType = "ld"; break; default: return false; } Enc += EncType; return true; } /// Appends a pointer encoding to Enc before calling appendType for the pointee. static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { Enc += "p("; if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) return false; Enc += ')'; return true; } /// Appends array encoding to Enc before calling appendType for the element. static bool appendArrayType(SmallStringEnc &Enc, QualType QT, const ArrayType *AT, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC, StringRef NoSizeEnc) { if (AT->getSizeModifier() != ArrayType::Normal) return false; Enc += "a("; if (const ConstantArrayType *CAT = dyn_cast(AT)) CAT->getSize().toStringUnsigned(Enc); else Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". Enc += ':'; // The Qualifiers should be attached to the type rather than the array. appendQualifier(Enc, QT); if (!appendType(Enc, AT->getElementType(), CGM, TSC)) return false; Enc += ')'; return true; } /// Appends a function encoding to Enc, calling appendType for the return type /// and the arguments. static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { Enc += "f{"; if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) return false; Enc += "}("; if (const FunctionProtoType *FPT = FT->getAs()) { // N.B. we are only interested in the adjusted param types. auto I = FPT->param_type_begin(); auto E = FPT->param_type_end(); if (I != E) { do { if (!appendType(Enc, *I, CGM, TSC)) return false; ++I; if (I != E) Enc += ','; } while (I != E); if (FPT->isVariadic()) Enc += ",va"; } else { if (FPT->isVariadic()) Enc += "va"; else Enc += '0'; } } Enc += ')'; return true; } /// Handles the type's qualifier before dispatching a call to handle specific /// type encodings. static bool appendType(SmallStringEnc &Enc, QualType QType, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { QualType QT = QType.getCanonicalType(); if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) // The Qualifiers should be attached to the type rather than the array. // Thus we don't call appendQualifier() here. return appendArrayType(Enc, QT, AT, CGM, TSC, ""); appendQualifier(Enc, QT); if (const BuiltinType *BT = QT->getAs()) return appendBuiltinType(Enc, BT); if (const PointerType *PT = QT->getAs()) return appendPointerType(Enc, PT, CGM, TSC); if (const EnumType *ET = QT->getAs()) return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); if (const RecordType *RT = QT->getAsStructureType()) return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); if (const RecordType *RT = QT->getAsUnionType()) return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); if (const FunctionType *FT = QT->getAs()) return appendFunctionType(Enc, FT, CGM, TSC); return false; } static bool getTypeString(SmallStringEnc &Enc, const Decl *D, CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { if (!D) return false; if (const FunctionDecl *FD = dyn_cast(D)) { if (FD->getLanguageLinkage() != CLanguageLinkage) return false; return appendType(Enc, FD->getType(), CGM, TSC); } if (const VarDecl *VD = dyn_cast(D)) { if (VD->getLanguageLinkage() != CLanguageLinkage) return false; QualType QT = VD->getType().getCanonicalType(); if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { // Global ArrayTypes are given a size of '*' if the size is unknown. // The Qualifiers should be attached to the type rather than the array. // Thus we don't call appendQualifier() here. return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); } return appendType(Enc, QT, CGM, TSC); } return false; } //===----------------------------------------------------------------------===// // RISCV ABI Implementation //===----------------------------------------------------------------------===// namespace { class RISCVABIInfo : public DefaultABIInfo { private: unsigned XLen; // Size of the integer ('x') registers in bits. static const int NumArgGPRs = 8; public: RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen) : DefaultABIInfo(CGT), XLen(XLen) {} // DefaultABIInfo's classifyReturnType and classifyArgumentType are // non-virtual, but computeInfo is virtual, so we overload it. void computeInfo(CGFunctionInfo &FI) const override; ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft) const; ABIArgInfo classifyReturnType(QualType RetTy) const; Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const override; ABIArgInfo extendType(QualType Ty) const; }; } // end anonymous namespace void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { QualType RetTy = FI.getReturnType(); if (!getCXXABI().classifyReturnType(FI)) FI.getReturnInfo() = classifyReturnType(RetTy); // IsRetIndirect is true if classifyArgumentType indicated the value should // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128 // is passed direct in LLVM IR, relying on the backend lowering code to // rewrite the argument list and pass indirectly on RV32. bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect || getContext().getTypeSize(RetTy) > (2 * XLen); // We must track the number of GPRs used in order to conform to the RISC-V // ABI, as integer scalars passed in registers should have signext/zeroext // when promoted, but are anyext if passed on the stack. As GPR usage is // different for variadic arguments, we must also track whether we are // examining a vararg or not. int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; int NumFixedArgs = FI.getNumRequiredArgs(); int ArgNum = 0; for (auto &ArgInfo : FI.arguments()) { bool IsFixed = ArgNum < NumFixedArgs; ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft); ArgNum++; } } ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft) const { assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); Ty = useFirstFieldIfTransparentUnion(Ty); // Structures with either a non-trivial destructor or a non-trivial // copy constructor are always passed indirectly. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { if (ArgGPRsLeft) ArgGPRsLeft -= 1; return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == CGCXXABI::RAA_DirectInMemory); } // Ignore empty structs/unions. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); uint64_t Size = getContext().getTypeSize(Ty); uint64_t NeededAlign = getContext().getTypeAlign(Ty); bool MustUseStack = false; // Determine the number of GPRs needed to pass the current argument // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" // register pairs, so may consume 3 registers. int NeededArgGPRs = 1; if (!IsFixed && NeededAlign == 2 * XLen) NeededArgGPRs = 2 + (ArgGPRsLeft % 2); else if (Size > XLen && Size <= 2 * XLen) NeededArgGPRs = 2; if (NeededArgGPRs > ArgGPRsLeft) { MustUseStack = true; NeededArgGPRs = ArgGPRsLeft; } ArgGPRsLeft -= NeededArgGPRs; if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { // Treat an enum type as its underlying type. if (const EnumType *EnumTy = Ty->getAs()) Ty = EnumTy->getDecl()->getIntegerType(); // All integral types are promoted to XLen width, unless passed on the // stack. if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { return extendType(Ty); } return ABIArgInfo::getDirect(); } // Aggregates which are <= 2*XLen will be passed in registers if possible, // so coerce to integers. if (Size <= 2 * XLen) { unsigned Alignment = getContext().getTypeAlign(Ty); // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is // required, and a 2-element XLen array if only XLen alignment is required. if (Size <= XLen) { return ABIArgInfo::getDirect( llvm::IntegerType::get(getVMContext(), XLen)); } else if (Alignment == 2 * XLen) { return ABIArgInfo::getDirect( llvm::IntegerType::get(getVMContext(), 2 * XLen)); } else { return ABIArgInfo::getDirect(llvm::ArrayType::get( llvm::IntegerType::get(getVMContext(), XLen), 2)); } } return getNaturalAlignIndirect(Ty, /*ByVal=*/false); } ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { if (RetTy->isVoidType()) return ABIArgInfo::getIgnore(); int ArgGPRsLeft = 2; // The rules for return and argument types are the same, so defer to // classifyArgumentType. return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft); } Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty) const { CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); // Empty records are ignored for parameter passing purposes. if (isEmptyRecord(getContext(), Ty, true)) { Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); return Addr; } std::pair SizeAndAlign = getContext().getTypeInfoInChars(Ty); // Arguments bigger than 2*Xlen bytes are passed indirectly. bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, SlotSize, /*AllowHigherAlign=*/true); } ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { int TySize = getContext().getTypeSize(Ty); // RV64 ABI requires unsigned 32 bit integers to be sign extended. if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) return ABIArgInfo::getSignExtend(Ty); return ABIArgInfo::getExtend(Ty); } namespace { class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { public: RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen) : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {} void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const override { const auto *FD = dyn_cast_or_null(D); if (!FD) return; const auto *Attr = FD->getAttr(); if (!Attr) return; const char *Kind; switch (Attr->getInterrupt()) { case RISCVInterruptAttr::user: Kind = "user"; break; case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; case RISCVInterruptAttr::machine: Kind = "machine"; break; } auto *Fn = cast(GV); Fn->addFnAttr("interrupt", Kind); } }; } // namespace //===----------------------------------------------------------------------===// // Driver code //===----------------------------------------------------------------------===// bool CodeGenModule::supportsCOMDAT() const { return getTriple().supportsCOMDAT(); } const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { if (TheTargetCodeGenInfo) return *TheTargetCodeGenInfo; // Helper to set the unique_ptr while still keeping the return value. auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { this->TheTargetCodeGenInfo.reset(P); return *P; }; const llvm::Triple &Triple = getTarget().getTriple(); switch (Triple.getArch()) { default: return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); case llvm::Triple::le32: return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); case llvm::Triple::mips: case llvm::Triple::mipsel: if (Triple.getOS() == llvm::Triple::NaCl) return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); case llvm::Triple::mips64: case llvm::Triple::mips64el: return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); case llvm::Triple::avr: return SetCGInfo(new AVRTargetCodeGenInfo(Types)); case llvm::Triple::aarch64: case llvm::Triple::aarch64_be: { AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; if (getTarget().getABI() == "darwinpcs") Kind = AArch64ABIInfo::DarwinPCS; else if (Triple.isOSWindows()) return SetCGInfo( new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); } case llvm::Triple::wasm32: case llvm::Triple::wasm64: return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types)); case llvm::Triple::arm: case llvm::Triple::armeb: case llvm::Triple::thumb: case llvm::Triple::thumbeb: { if (Triple.getOS() == llvm::Triple::Win32) { return SetCGInfo( new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); } ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; StringRef ABIStr = getTarget().getABI(); if (ABIStr == "apcs-gnu") Kind = ARMABIInfo::APCS; else if (ABIStr == "aapcs16") Kind = ARMABIInfo::AAPCS16_VFP; else if (CodeGenOpts.FloatABI == "hard" || (CodeGenOpts.FloatABI != "soft" && (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || Triple.getEnvironment() == llvm::Triple::MuslEABIHF || Triple.getEnvironment() == llvm::Triple::EABIHF))) Kind = ARMABIInfo::AAPCS_VFP; return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); } case llvm::Triple::ppc: return SetCGInfo( new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft")); case llvm::Triple::ppc64: if (Triple.isOSBinFormatELF()) { PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; if (getTarget().getABI() == "elfv2") Kind = PPC64_SVR4_ABIInfo::ELFv2; bool HasQPX = getTarget().getABI() == "elfv1-qpx"; bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, IsSoftFloat)); } else return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); case llvm::Triple::ppc64le: { assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") Kind = PPC64_SVR4_ABIInfo::ELFv1; bool HasQPX = getTarget().getABI() == "elfv1-qpx"; bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, IsSoftFloat)); } case llvm::Triple::nvptx: case llvm::Triple::nvptx64: return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); case llvm::Triple::msp430: return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); case llvm::Triple::riscv32: return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32)); case llvm::Triple::riscv64: return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64)); case llvm::Triple::systemz: { bool HasVector = getTarget().getABI() == "vector"; return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector)); } case llvm::Triple::tce: case llvm::Triple::tcele: return SetCGInfo(new TCETargetCodeGenInfo(Types)); case llvm::Triple::x86: { bool IsDarwinVectorABI = Triple.isOSDarwin(); bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); if (Triple.getOS() == llvm::Triple::Win32) { return SetCGInfo(new WinX86_32TargetCodeGenInfo( Types, IsDarwinVectorABI, RetSmallStructInRegABI, IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); } else { return SetCGInfo(new X86_32TargetCodeGenInfo( Types, IsDarwinVectorABI, RetSmallStructInRegABI, IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft")); } } case llvm::Triple::x86_64: { StringRef ABI = getTarget().getABI(); X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); switch (Triple.getOS()) { case llvm::Triple::Win32: return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); case llvm::Triple::PS4: return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel)); default: return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); } } case llvm::Triple::hexagon: return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); case llvm::Triple::lanai: return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); case llvm::Triple::r600: return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); case llvm::Triple::amdgcn: return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); case llvm::Triple::sparc: return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); case llvm::Triple::sparcv9: return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); case llvm::Triple::xcore: return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); case llvm::Triple::arc: return SetCGInfo(new ARCTargetCodeGenInfo(Types)); case llvm::Triple::spir: case llvm::Triple::spir64: return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); } } /// Create an OpenCL kernel for an enqueued block. /// /// The kernel has the same function type as the block invoke function. Its /// name is the name of the block invoke function postfixed with "_kernel". /// It simply calls the block invoke function then returns. llvm::Function * TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, llvm::Function *Invoke, llvm::Value *BlockLiteral) const { auto *InvokeFT = Invoke->getFunctionType(); llvm::SmallVector ArgTys; for (auto &P : InvokeFT->params()) ArgTys.push_back(P); auto &C = CGF.getLLVMContext(); std::string Name = Invoke->getName().str() + "_kernel"; auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, &CGF.CGM.getModule()); auto IP = CGF.Builder.saveIP(); auto *BB = llvm::BasicBlock::Create(C, "entry", F); auto &Builder = CGF.Builder; Builder.SetInsertPoint(BB); llvm::SmallVector Args; for (auto &A : F->args()) Args.push_back(&A); Builder.CreateCall(Invoke, Args); Builder.CreateRetVoid(); Builder.restoreIP(IP); return F; } /// Create an OpenCL kernel for an enqueued block. /// /// The type of the first argument (the block literal) is the struct type /// of the block literal instead of a pointer type. The first argument /// (block literal) is passed directly by value to the kernel. The kernel /// allocates the same type of struct on stack and stores the block literal /// to it and passes its pointer to the block invoke function. The kernel /// has "enqueued-block" function attribute and kernel argument metadata. llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( CodeGenFunction &CGF, llvm::Function *Invoke, llvm::Value *BlockLiteral) const { auto &Builder = CGF.Builder; auto &C = CGF.getLLVMContext(); auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); auto *InvokeFT = Invoke->getFunctionType(); llvm::SmallVector ArgTys; llvm::SmallVector AddressQuals; llvm::SmallVector AccessQuals; llvm::SmallVector ArgTypeNames; llvm::SmallVector ArgBaseTypeNames; llvm::SmallVector ArgTypeQuals; llvm::SmallVector ArgNames; ArgTys.push_back(BlockTy); ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); ArgTypeQuals.push_back(llvm::MDString::get(C, "")); AccessQuals.push_back(llvm::MDString::get(C, "none")); ArgNames.push_back(llvm::MDString::get(C, "block_literal")); for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { ArgTys.push_back(InvokeFT->getParamType(I)); ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); AccessQuals.push_back(llvm::MDString::get(C, "none")); ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); ArgTypeQuals.push_back(llvm::MDString::get(C, "")); ArgNames.push_back( llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); } std::string Name = Invoke->getName().str() + "_kernel"; auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, &CGF.CGM.getModule()); F->addFnAttr("enqueued-block"); auto IP = CGF.Builder.saveIP(); auto *BB = llvm::BasicBlock::Create(C, "entry", F); Builder.SetInsertPoint(BB); unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy); auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); BlockPtr->setAlignment(BlockAlign); Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); llvm::SmallVector Args; Args.push_back(Cast); for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) Args.push_back(I); Builder.CreateCall(Invoke, Args); Builder.CreateRetVoid(); Builder.restoreIP(IP); F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); F->setMetadata("kernel_arg_base_type", llvm::MDNode::get(C, ArgBaseTypeNames)); F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); return F; } Index: vendor/clang/dist-release_80/lib/Sema/SemaDeclAttr.cpp =================================================================== --- vendor/clang/dist-release_80/lib/Sema/SemaDeclAttr.cpp (revision 343192) +++ vendor/clang/dist-release_80/lib/Sema/SemaDeclAttr.cpp (revision 343193) @@ -1,8243 +1,8260 @@ //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements decl-related attribute processing. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/Mangle.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/MathExtras.h" using namespace clang; using namespace sema; namespace AttributeLangSupport { enum LANG { C, Cpp, ObjC }; } // end namespace AttributeLangSupport //===----------------------------------------------------------------------===// // Helper functions //===----------------------------------------------------------------------===// /// isFunctionOrMethod - Return true if the given decl has function /// type (function or function-typed variable) or an Objective-C /// method. static bool isFunctionOrMethod(const Decl *D) { return (D->getFunctionType() != nullptr) || isa(D); } /// Return true if the given decl has function type (function or /// function-typed variable) or an Objective-C method or a block. static bool isFunctionOrMethodOrBlock(const Decl *D) { return isFunctionOrMethod(D) || isa(D); } /// Return true if the given decl has a declarator that should have /// been processed by Sema::GetTypeForDeclarator. static bool hasDeclarator(const Decl *D) { // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. return isa(D) || isa(D) || isa(D) || isa(D); } /// hasFunctionProto - Return true if the given decl has a argument /// information. This decl should have already passed /// isFunctionOrMethod or isFunctionOrMethodOrBlock. static bool hasFunctionProto(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return isa(FnTy); return isa(D) || isa(D); } /// getFunctionOrMethodNumParams - Return number of function or method /// parameters. It is an error to call this on a K&R function (use /// hasFunctionProto first). static unsigned getFunctionOrMethodNumParams(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return cast(FnTy)->getNumParams(); if (const auto *BD = dyn_cast(D)) return BD->getNumParams(); return cast(D)->param_size(); } static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D, unsigned Idx) { if (const auto *FD = dyn_cast(D)) return FD->getParamDecl(Idx); if (const auto *MD = dyn_cast(D)) return MD->getParamDecl(Idx); if (const auto *BD = dyn_cast(D)) return BD->getParamDecl(Idx); return nullptr; } static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { if (const FunctionType *FnTy = D->getFunctionType()) return cast(FnTy)->getParamType(Idx); if (const auto *BD = dyn_cast(D)) return BD->getParamDecl(Idx)->getType(); return cast(D)->parameters()[Idx]->getType(); } static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { if (auto *PVD = getFunctionOrMethodParam(D, Idx)) return PVD->getSourceRange(); return SourceRange(); } static QualType getFunctionOrMethodResultType(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return FnTy->getReturnType(); return cast(D)->getReturnType(); } static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { if (const auto *FD = dyn_cast(D)) return FD->getReturnTypeSourceRange(); if (const auto *MD = dyn_cast(D)) return MD->getReturnTypeSourceRange(); return SourceRange(); } static bool isFunctionOrMethodVariadic(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return cast(FnTy)->isVariadic(); if (const auto *BD = dyn_cast(D)) return BD->isVariadic(); return cast(D)->isVariadic(); } static bool isInstanceMethod(const Decl *D) { if (const auto *MethodDecl = dyn_cast(D)) return MethodDecl->isInstance(); return false; } static inline bool isNSStringType(QualType T, ASTContext &Ctx) { const auto *PT = T->getAs(); if (!PT) return false; ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); if (!Cls) return false; IdentifierInfo* ClsName = Cls->getIdentifier(); // FIXME: Should we walk the chain of classes? return ClsName == &Ctx.Idents.get("NSString") || ClsName == &Ctx.Idents.get("NSMutableString"); } static inline bool isCFStringType(QualType T, ASTContext &Ctx) { const auto *PT = T->getAs(); if (!PT) return false; const auto *RT = PT->getPointeeType()->getAs(); if (!RT) return false; const RecordDecl *RD = RT->getDecl(); if (RD->getTagKind() != TTK_Struct) return false; return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); } static unsigned getNumAttributeArgs(const ParsedAttr &AL) { // FIXME: Include the type in the argument list. return AL.getNumArgs() + AL.hasParsedType(); } template static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL, unsigned Num, unsigned Diag, Compare Comp) { if (Comp(getNumAttributeArgs(AL), Num)) { S.Diag(AL.getLoc(), Diag) << AL << Num; return false; } return true; } /// Check if the attribute has exactly as many args as Num. May /// output an error. static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) { return checkAttributeNumArgsImpl(S, AL, Num, diag::err_attribute_wrong_number_arguments, std::not_equal_to()); } /// Check if the attribute has at least as many args as Num. May /// output an error. static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) { return checkAttributeNumArgsImpl(S, AL, Num, diag::err_attribute_too_few_arguments, std::less()); } /// Check if the attribute has at most as many args as Num. May /// output an error. static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) { return checkAttributeNumArgsImpl(S, AL, Num, diag::err_attribute_too_many_arguments, std::greater()); } /// A helper function to provide Attribute Location for the Attr types /// AND the ParsedAttr. template static typename std::enable_if::value, SourceLocation>::type getAttrLoc(const AttrInfo &AL) { return AL.getLocation(); } static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); } /// If Expr is a valid integer constant, get the value of the integer /// expression and return success or failure. May output an error. /// /// Negative argument is implicitly converted to unsigned, unless /// \p StrictlyUnsigned is true. template static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx = UINT_MAX, bool StrictlyUnsigned = false) { llvm::APSInt I(32); if (Expr->isTypeDependent() || Expr->isValueDependent() || !Expr->isIntegerConstantExpr(I, S.Context)) { if (Idx != UINT_MAX) S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) << AI << Idx << AANT_ArgumentIntegerConstant << Expr->getSourceRange(); else S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type) << AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange(); return false; } if (!I.isIntN(32)) { S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 1; return false; } if (StrictlyUnsigned && I.isSigned() && I.isNegative()) { S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer) << AI << /*non-negative*/ 1; return false; } Val = (uint32_t)I.getZExtValue(); return true; } /// Wrapper around checkUInt32Argument, with an extra check to be sure /// that the result will fit into a regular (signed) int. All args have the same /// purpose as they do in checkUInt32Argument. template static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, int &Val, unsigned Idx = UINT_MAX) { uint32_t UVal; if (!checkUInt32Argument(S, AI, Expr, UVal, Idx)) return false; if (UVal > (uint32_t)std::numeric_limits::max()) { llvm::APSInt I(32); // for toString I = UVal; S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 0; return false; } Val = UVal; return true; } /// Diagnose mutually exclusive attributes when present on a given /// declaration. Returns true if diagnosed. template static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) { if (const auto *A = D->getAttr()) { S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A; S.Diag(A->getLocation(), diag::note_conflicting_attribute); return true; } return false; } template static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) { if (const auto *A = D->getAttr()) { S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL << A; S.Diag(A->getLocation(), diag::note_conflicting_attribute); return true; } return false; } /// Check if IdxExpr is a valid parameter index for a function or /// instance method D. May output an error. /// /// \returns true if IdxExpr is a valid index. template static bool checkFunctionOrMethodParameterIndex( Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) { assert(isFunctionOrMethodOrBlock(D)); // In C++ the implicit 'this' function parameter also counts. // Parameters are counted from one. bool HP = hasFunctionProto(D); bool HasImplicitThisParam = isInstanceMethod(D); bool IV = HP && isFunctionOrMethodVariadic(D); unsigned NumParams = (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; llvm::APSInt IdxInt; if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) << &AI << AttrArgNum << AANT_ArgumentIntegerConstant << IdxExpr->getSourceRange(); return false; } unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX); if (IdxSource < 1 || (!IV && IdxSource > NumParams)) { S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds) << &AI << AttrArgNum << IdxExpr->getSourceRange(); return false; } if (HasImplicitThisParam && !CanIndexImplicitThis) { if (IdxSource == 1) { S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument) << &AI << IdxExpr->getSourceRange(); return false; } } Idx = ParamIdx(IdxSource, D); return true; } /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal. /// If not emit an error and return false. If the argument is an identifier it /// will emit an error with a fixit hint and treat it as if it was a string /// literal. bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation) { // Look for identifiers. If we have one emit a hint to fix it to a literal. if (AL.isArgIdent(ArgNum)) { IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum); Diag(Loc->Loc, diag::err_attribute_argument_type) << AL << AANT_ArgumentString << FixItHint::CreateInsertion(Loc->Loc, "\"") << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); Str = Loc->Ident->getName(); if (ArgLocation) *ArgLocation = Loc->Loc; return true; } // Now check for an actual string literal. Expr *ArgExpr = AL.getArgAsExpr(ArgNum); const auto *Literal = dyn_cast(ArgExpr->IgnoreParenCasts()); if (ArgLocation) *ArgLocation = ArgExpr->getBeginLoc(); if (!Literal || !Literal->isAscii()) { Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentString; return false; } Str = Literal->getString(); return true; } /// Applies the given attribute to the Decl without performing any /// additional semantic checking. template static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR, unsigned SpellingIndex) { D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex)); } template static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) { handleSimpleAttribute(S, D, AL.getRange(), AL.getAttributeSpellingListIndex()); } template static const Sema::SemaDiagnosticBuilder& appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) { return Bldr; } template static const Sema::SemaDiagnosticBuilder& appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg, DiagnosticArgs &&... ExtraArgs) { return appendDiagnostics(Bldr << std::forward(ExtraArg), std::forward(ExtraArgs)...); } /// Add an attribute {@code AttrType} to declaration {@code D}, provided that /// {@code PassesCheck} is true. /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters /// specified in {@code ExtraArgs}. template static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR, unsigned SpellingIndex, bool PassesCheck, unsigned DiagID, DiagnosticArgs&&... ExtraArgs) { if (!PassesCheck) { Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID); appendDiagnostics(DB, std::forward(ExtraArgs)...); return; } handleSimpleAttribute(S, D, SR, SpellingIndex); } template static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL, bool PassesCheck, unsigned DiagID, DiagnosticArgs&&... ExtraArgs) { return handleSimpleAttributeOrDiagnose( S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck, DiagID, std::forward(ExtraArgs)...); } template static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, const ParsedAttr &AL) { handleSimpleAttribute(S, D, AL); } /// Applies the given attribute to the Decl so long as the Decl doesn't /// already have one of the given incompatible attributes. template static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL)) return; handleSimpleAttributeWithExclusions(S, D, AL); } /// Check if the passed-in expression is of type int or bool. static bool isIntOrBool(Expr *Exp) { QualType QT = Exp->getType(); return QT->isBooleanType() || QT->isIntegerType(); } // Check to see if the type is a smart pointer of some kind. We assume // it's a smart pointer if it defines both operator-> and operator*. static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record, OverloadedOperatorKind Op) { DeclContextLookupResult Result = Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op)); return !Result.empty(); }; const RecordDecl *Record = RT->getDecl(); bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star); bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow); if (foundStarOperator && foundArrowOperator) return true; const CXXRecordDecl *CXXRecord = dyn_cast(Record); if (!CXXRecord) return false; for (auto BaseSpecifier : CXXRecord->bases()) { if (!foundStarOperator) foundStarOperator = IsOverloadedOperatorPresent( BaseSpecifier.getType()->getAsRecordDecl(), OO_Star); if (!foundArrowOperator) foundArrowOperator = IsOverloadedOperatorPresent( BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow); } if (foundStarOperator && foundArrowOperator) return true; return false; } /// Check if passed in Decl is a pointer type. /// Note that this function may produce an error message. /// \return true if the Decl is a pointer type; false otherwise static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, const ParsedAttr &AL) { const auto *VD = cast(D); QualType QT = VD->getType(); if (QT->isAnyPointerType()) return true; if (const auto *RT = QT->getAs()) { // If it's an incomplete type, it could be a smart pointer; skip it. // (We don't want to force template instantiation if we can avoid it, // since that would alter the order in which templates are instantiated.) if (RT->isIncompleteType()) return true; if (threadSafetyCheckIsSmartPointer(S, RT)) return true; } S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT; return false; } /// Checks that the passed in QualType either is of RecordType or points /// to RecordType. Returns the relevant RecordType, null if it does not exit. static const RecordType *getRecordType(QualType QT) { if (const auto *RT = QT->getAs()) return RT; // Now check if we point to record type. if (const auto *PT = QT->getAs()) return PT->getPointeeType()->getAs(); return nullptr; } template static bool checkRecordDeclForAttr(const RecordDecl *RD) { // Check if the record itself has the attribute. if (RD->hasAttr()) return true; // Else check if any base classes have the attribute. if (const auto *CRD = dyn_cast(RD)) { CXXBasePaths BPaths(false, false); if (CRD->lookupInBases( [](const CXXBaseSpecifier *BS, CXXBasePath &) { const auto &Ty = *BS->getType(); // If it's type-dependent, we assume it could have the attribute. if (Ty.isDependentType()) return true; return Ty.getAs()->getDecl()->hasAttr(); }, BPaths, true)) return true; } return false; } static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { const RecordType *RT = getRecordType(Ty); if (!RT) return false; // Don't check for the capability if the class hasn't been defined yet. if (RT->isIncompleteType()) return true; // Allow smart pointers to be used as capability objects. // FIXME -- Check the type that the smart pointer points to. if (threadSafetyCheckIsSmartPointer(S, RT)) return true; return checkRecordDeclForAttr(RT->getDecl()); } static bool checkTypedefTypeForCapability(QualType Ty) { const auto *TD = Ty->getAs(); if (!TD) return false; TypedefNameDecl *TN = TD->getDecl(); if (!TN) return false; return TN->hasAttr(); } static bool typeHasCapability(Sema &S, QualType Ty) { if (checkTypedefTypeForCapability(Ty)) return true; if (checkRecordTypeForCapability(S, Ty)) return true; return false; } static bool isCapabilityExpr(Sema &S, const Expr *Ex) { // Capability expressions are simple expressions involving the boolean logic // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once // a DeclRefExpr is found, its type should be checked to determine whether it // is a capability or not. if (const auto *E = dyn_cast(Ex)) return isCapabilityExpr(S, E->getSubExpr()); else if (const auto *E = dyn_cast(Ex)) return isCapabilityExpr(S, E->getSubExpr()); else if (const auto *E = dyn_cast(Ex)) { if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf || E->getOpcode() == UO_Deref) return isCapabilityExpr(S, E->getSubExpr()); return false; } else if (const auto *E = dyn_cast(Ex)) { if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) return isCapabilityExpr(S, E->getLHS()) && isCapabilityExpr(S, E->getRHS()); return false; } return typeHasCapability(S, Ex->getType()); } /// Checks that all attribute arguments, starting from Sidx, resolve to /// a capability object. /// \param Sidx The attribute argument index to start checking with. /// \param ParamIdxOk Whether an argument can be indexing into a function /// parameter list. static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, const ParsedAttr &AL, SmallVectorImpl &Args, unsigned Sidx = 0, bool ParamIdxOk = false) { if (Sidx == AL.getNumArgs()) { // If we don't have any capability arguments, the attribute implicitly // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're // a non-static method, and that the class is a (scoped) capability. const auto *MD = dyn_cast(D); if (MD && !MD->isStatic()) { const CXXRecordDecl *RD = MD->getParent(); // FIXME -- need to check this again on template instantiation if (!checkRecordDeclForAttr(RD) && !checkRecordDeclForAttr(RD)) S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_capability_member) << AL << MD->getParent(); } else { S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member) << AL; } } for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) { Expr *ArgExp = AL.getArgAsExpr(Idx); if (ArgExp->isTypeDependent()) { // FIXME -- need to check this again on template instantiation Args.push_back(ArgExp); continue; } if (const auto *StrLit = dyn_cast(ArgExp)) { if (StrLit->getLength() == 0 || (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { // Pass empty strings to the analyzer without warnings. // Treat "*" as the universal lock. Args.push_back(ArgExp); continue; } // We allow constant strings to be used as a placeholder for expressions // that are not valid C++ syntax, but warn that they are ignored. S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL; Args.push_back(ArgExp); continue; } QualType ArgTy = ArgExp->getType(); // A pointer to member expression of the form &MyClass::mu is treated // specially -- we need to look at the type of the member. if (const auto *UOp = dyn_cast(ArgExp)) if (UOp->getOpcode() == UO_AddrOf) if (const auto *DRE = dyn_cast(UOp->getSubExpr())) if (DRE->getDecl()->isCXXInstanceMember()) ArgTy = DRE->getDecl()->getType(); // First see if we can just cast to record type, or pointer to record type. const RecordType *RT = getRecordType(ArgTy); // Now check if we index into a record type function param. if(!RT && ParamIdxOk) { const auto *FD = dyn_cast(D); const auto *IL = dyn_cast(ArgExp); if(FD && IL) { unsigned int NumParams = FD->getNumParams(); llvm::APInt ArgValue = IL->getValue(); uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range) << AL << Idx + 1 << NumParams; continue; } ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); } } // If the type does not have a capability, see if the components of the // expression have capabilities. This allows for writing C code where the // capability may be on the type, and the expression is a capability // boolean logic expression. Eg) requires_capability(A || B && !C) if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable) << AL << ArgTy; Args.push_back(ArgExp); } } //===----------------------------------------------------------------------===// // Attribute Implementations //===----------------------------------------------------------------------===// static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!threadSafetyCheckIsPointer(S, D, AL)) return; D->addAttr(::new (S.Context) PtGuardedVarAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, Expr *&Arg) { SmallVector Args; // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, AL, Args); unsigned Size = Args.size(); if (Size != 1) return false; Arg = Args[0]; return true; } static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *Arg = nullptr; if (!checkGuardedByAttrCommon(S, D, AL, Arg)) return; D->addAttr(::new (S.Context) GuardedByAttr( AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex())); } static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *Arg = nullptr; if (!checkGuardedByAttrCommon(S, D, AL, Arg)) return; if (!threadSafetyCheckIsPointer(S, D, AL)) return; D->addAttr(::new (S.Context) PtGuardedByAttr( AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex())); } static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, SmallVectorImpl &Args) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return false; // Check that this attribute only applies to lockable types. QualType QT = cast(D)->getType(); if (!QT->isDependentType() && !typeHasCapability(S, QT)) { S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL; return false; } // Check that all arguments are lockable objects. checkAttrArgsAreCapabilityObjs(S, D, AL, Args); if (Args.empty()) return false; return true; } static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) AcquiredAfterAttr( AL.getRange(), S.Context, StartArg, Args.size(), AL.getAttributeSpellingListIndex())); } static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) AcquiredBeforeAttr( AL.getRange(), S.Context, StartArg, Args.size(), AL.getAttributeSpellingListIndex())); } static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, SmallVectorImpl &Args) { // zero or more arguments ok // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true); return true; } static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; unsigned Size = Args.size(); Expr **StartArg = Size == 0 ? nullptr : &Args[0]; D->addAttr(::new (S.Context) AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size, AL.getAttributeSpellingListIndex())); } static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; unsigned Size = Args.size(); Expr **StartArg = Size == 0 ? nullptr : &Args[0]; D->addAttr(::new (S.Context) AssertExclusiveLockAttr( AL.getRange(), S.Context, StartArg, Size, AL.getAttributeSpellingListIndex())); } /// Checks to be sure that the given parameter number is in bounds, and /// is an integral type. Will emit appropriate diagnostics if this returns /// false. /// /// AttrArgNo is used to actually retrieve the argument, so it's base-0. template static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, const AttrInfo &AI, unsigned AttrArgNo) { assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument"); Expr *AttrArg = AI.getArgAsExpr(AttrArgNo); ParamIdx Idx; if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg, Idx)) return false; const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex()); if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) { SourceLocation SrcLoc = AttrArg->getBeginLoc(); S.Diag(SrcLoc, diag::err_attribute_integers_only) << AI << Param->getSourceRange(); return false; } return true; } static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1) || !checkAttributeAtMostNumArgs(S, AL, 2)) return; const auto *FD = cast(D); if (!FD->getReturnType()->isPointerType()) { S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL; return; } const Expr *SizeExpr = AL.getArgAsExpr(0); int SizeArgNoVal; // Parameter indices are 1-indexed, hence Index=1 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1)) return; if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0)) return; ParamIdx SizeArgNo(SizeArgNoVal, D); ParamIdx NumberArgNo; if (AL.getNumArgs() == 2) { const Expr *NumberExpr = AL.getArgAsExpr(1); int Val; // Parameter indices are 1-based, hence Index=2 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2)) return; if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1)) return; NumberArgNo = ParamIdx(Val, D); } D->addAttr(::new (S.Context) AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo, AL.getAttributeSpellingListIndex())); } static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, SmallVectorImpl &Args) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return false; if (!isIntOrBool(AL.getArgAsExpr(0))) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIntOrBool; return false; } // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1); return true; } static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) SharedTrylockFunctionAttr( AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // check that the argument is lockable object SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); unsigned Size = Args.size(); if (Size == 0) return; D->addAttr(::new (S.Context) LockReturnedAttr(AL.getRange(), S.Context, Args[0], AL.getAttributeSpellingListIndex())); } static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; // check that all arguments are lockable objects SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); unsigned Size = Args.size(); if (Size == 0) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size, AL.getAttributeSpellingListIndex())); } static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL, Expr *&Cond, StringRef &Msg) { Cond = AL.getArgAsExpr(0); if (!Cond->isTypeDependent()) { ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); if (Converted.isInvalid()) return false; Cond = Converted.get(); } if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg)) return false; if (Msg.empty()) Msg = ""; SmallVector Diags; if (isa(D) && !Cond->isValueDependent() && !Expr::isPotentialConstantExprUnevaluated(Cond, cast(D), Diags)) { S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL; for (const PartialDiagnosticAt &PDiag : Diags) S.Diag(PDiag.first, PDiag.second); return false; } return true; } static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.Diag(AL.getLoc(), diag::ext_clang_enable_if); Expr *Cond; StringRef Msg; if (checkFunctionConditionAttr(S, D, AL, Cond, Msg)) D->addAttr(::new (S.Context) EnableIfAttr(AL.getRange(), S.Context, Cond, Msg, AL.getAttributeSpellingListIndex())); } namespace { /// Determines if a given Expr references any of the given function's /// ParmVarDecls, or the function's implicit `this` parameter (if applicable). class ArgumentDependenceChecker : public RecursiveASTVisitor { #ifndef NDEBUG const CXXRecordDecl *ClassType; #endif llvm::SmallPtrSet Parms; bool Result; public: ArgumentDependenceChecker(const FunctionDecl *FD) { #ifndef NDEBUG if (const auto *MD = dyn_cast(FD)) ClassType = MD->getParent(); else ClassType = nullptr; #endif Parms.insert(FD->param_begin(), FD->param_end()); } bool referencesArgs(Expr *E) { Result = false; TraverseStmt(E); return Result; } bool VisitCXXThisExpr(CXXThisExpr *E) { assert(E->getType()->getPointeeCXXRecordDecl() == ClassType && "`this` doesn't refer to the enclosing class?"); Result = true; return false; } bool VisitDeclRefExpr(DeclRefExpr *DRE) { if (const auto *PVD = dyn_cast(DRE->getDecl())) if (Parms.count(PVD)) { Result = true; return false; } return true; } }; } static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if); Expr *Cond; StringRef Msg; if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg)) return; StringRef DiagTypeStr; if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr)) return; DiagnoseIfAttr::DiagnosticType DiagType; if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) { S.Diag(AL.getArgAsExpr(2)->getBeginLoc(), diag::err_diagnose_if_invalid_diagnostic_type); return; } bool ArgDependent = false; if (const auto *FD = dyn_cast(D)) ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond); D->addAttr(::new (S.Context) DiagnoseIfAttr( AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast(D), AL.getAttributeSpellingListIndex())); } static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (D->hasAttr()) { S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL; return; } Expr *E = AL.getArgAsExpr(0); uint32_t Type; if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1)) return; // pass_object_size's argument is passed in as the second argument of // __builtin_object_size. So, it has the same constraints as that second // argument; namely, it must be in the range [0, 3]. if (Type > 3) { S.Diag(E->getBeginLoc(), diag::err_attribute_argument_outof_range) << AL << 0 << 3 << E->getSourceRange(); return; } // pass_object_size is only supported on constant pointer parameters; as a // kindness to users, we allow the parameter to be non-const for declarations. // At this point, we have no clue if `D` belongs to a function declaration or // definition, so we defer the constness check until later. if (!cast(D)->getType()->isPointerType()) { S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1; return; } D->addAttr(::new (S.Context) PassObjectSizeAttr( AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex())); } static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ConsumableAttr::ConsumedState DefaultState; if (AL.isArgIdent(0)) { IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), DefaultState)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; return; } } else { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) ConsumableAttr(AL.getRange(), S.Context, DefaultState, AL.getAttributeSpellingListIndex())); } static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, const ParsedAttr &AL) { QualType ThisType = MD->getThisType()->getPointeeType(); if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { if (!RD->hasAttr()) { S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD->getNameAsString(); return false; } } return true; } static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; if (!checkForConsumableClass(S, cast(D), AL)) return; SmallVector States; for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) { CallableWhenAttr::ConsumedState CallableState; StringRef StateString; SourceLocation Loc; if (AL.isArgIdent(ArgIndex)) { IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex); StateString = Ident->Ident->getName(); Loc = Ident->Loc; } else { if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc)) return; } if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, CallableState)) { S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString; return; } States.push_back(CallableState); } D->addAttr(::new (S.Context) CallableWhenAttr(AL.getRange(), S.Context, States.data(), States.size(), AL.getAttributeSpellingListIndex())); } static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ParamTypestateAttr::ConsumedState ParamState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef StateString = Ident->Ident->getName(); if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, ParamState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL << StateString; return; } } else { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. //QualType ReturnType = cast(D)->getType(); //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // //if (!RD || !RD->hasAttr()) { // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; //} D->addAttr(::new (S.Context) ParamTypestateAttr(AL.getRange(), S.Context, ParamState, AL.getAttributeSpellingListIndex())); } static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ReturnTypestateAttr::ConsumedState ReturnState; if (AL.isArgIdent(0)) { IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), ReturnState)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; return; } } else { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. //QualType ReturnType; // //if (const ParmVarDecl *Param = dyn_cast(D)) { // ReturnType = Param->getType(); // //} else if (const CXXConstructorDecl *Constructor = // dyn_cast(D)) { // ReturnType = Constructor->getThisType()->getPointeeType(); // //} else { // // ReturnType = cast(D)->getCallResultType(); //} // //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // //if (!RD || !RD->hasAttr()) { // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; //} D->addAttr(::new (S.Context) ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState, AL.getAttributeSpellingListIndex())); } static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast(D), AL)) return; SetTypestateAttr::ConsumedState NewState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL << Param; return; } } else { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) SetTypestateAttr(AL.getRange(), S.Context, NewState, AL.getAttributeSpellingListIndex())); } static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast(D), AL)) return; TestTypestateAttr::ConsumedState TestState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL << Param; return; } } else { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) TestTypestateAttr(AL.getRange(), S.Context, TestState, AL.getAttributeSpellingListIndex())); } static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Remember this typedef decl, we will need it later for diagnostics. S.ExtVectorDecls.push_back(cast(D)); } static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (auto *TD = dyn_cast(D)) TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); else if (auto *FD = dyn_cast(D)) { bool BitfieldByteAligned = (!FD->getType()->isDependentType() && !FD->getType()->isIncompleteType() && FD->isBitField() && S.Context.getTypeAlign(FD->getType()) <= 8); if (S.getASTContext().getTargetInfo().getTriple().isPS4()) { if (BitfieldByteAligned) // The PS4 target needs to maintain ABI backwards compatibility. S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type) << AL << FD->getType(); else FD->addAttr(::new (S.Context) PackedAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } else { // Report warning about changed offset in the newer compiler versions. if (BitfieldByteAligned) S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield); FD->addAttr(::new (S.Context) PackedAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } } else S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; } static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) { // The IBOutlet/IBOutletCollection attributes only apply to instance // variables or properties of Objective-C classes. The outlet must also // have an object reference type. if (const auto *VD = dyn_cast(D)) { if (!VD->getType()->getAs()) { S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) << AL << VD->getType() << 0; return false; } } else if (const auto *PD = dyn_cast(D)) { if (!PD->getType()->getAs()) { S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) << AL << PD->getType() << 1; return false; } } else { S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL; return false; } return true; } static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkIBOutletCommon(S, D, AL)) return; D->addAttr(::new (S.Context) IBOutletAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) { // The iboutletcollection attribute can have zero or one arguments. if (AL.getNumArgs() > 1) { S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; return; } if (!checkIBOutletCommon(S, D, AL)) return; ParsedType PT; if (AL.hasParsedType()) PT = AL.getTypeArg(); else { PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(), S.getScopeForContext(D->getDeclContext()->getParent())); if (!PT) { S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; return; } } TypeSourceInfo *QTLoc = nullptr; QualType QT = S.GetTypeFromParser(PT, &QTLoc); if (!QTLoc) QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc()); // Diagnose use of non-object type in iboutletcollection attribute. // FIXME. Gnu attribute extension ignores use of builtin types in // attributes. So, __attribute__((iboutletcollection(char))) will be // treated as __attribute__((iboutletcollection())). if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { S.Diag(AL.getLoc(), QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype : diag::err_iboutletcollection_type) << QT; return; } D->addAttr(::new (S.Context) IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc, AL.getAttributeSpellingListIndex())); } bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { if (RefOkay) { if (T->isReferenceType()) return true; } else { T = T.getNonReferenceType(); } // The nonnull attribute, and other similar attributes, can be applied to a // transparent union that contains a pointer type. if (const RecordType *UT = T->getAsUnionType()) { if (UT && UT->getDecl()->hasAttr()) { RecordDecl *UD = UT->getDecl(); for (const auto *I : UD->fields()) { QualType QT = I->getType(); if (QT->isAnyPointerType() || QT->isBlockPointerType()) return true; } } } return T->isAnyPointerType() || T->isBlockPointerType(); } static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL, SourceRange AttrParmRange, SourceRange TypeRange, bool isReturnValue = false) { if (!S.isValidPointerAttrType(T)) { if (isReturnValue) S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL << AttrParmRange << TypeRange; else S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) << AL << AttrParmRange << TypeRange << 0; return false; } return true; } static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector NonNullArgs; for (unsigned I = 0; I < AL.getNumArgs(); ++I) { Expr *Ex = AL.getArgAsExpr(I); ParamIdx Idx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx)) return; // Is the function argument a pointer type? if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) && !attrNonNullArgCheck( S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL, Ex->getSourceRange(), getFunctionOrMethodParamRange(D, Idx.getASTIndex()))) continue; NonNullArgs.push_back(Idx); } // If no arguments were specified to __attribute__((nonnull)) then all pointer // arguments have a nonnull attribute; warn if there aren't any. Skip this // check if the attribute came from a macro expansion or a template // instantiation. if (NonNullArgs.empty() && AL.getLoc().isFileID() && !S.inTemplateInstantiation()) { bool AnyPointers = isFunctionOrMethodVariadic(D); for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E && !AnyPointers; ++I) { QualType T = getFunctionOrMethodParamType(D, I); if (T->isDependentType() || S.isValidPointerAttrType(T)) AnyPointers = true; } if (!AnyPointers) S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers); } ParamIdx *Start = NonNullArgs.data(); unsigned Size = NonNullArgs.size(); llvm::array_pod_sort(Start, Start + Size); D->addAttr(::new (S.Context) NonNullAttr(AL.getRange(), S.Context, Start, Size, AL.getAttributeSpellingListIndex())); } static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, const ParsedAttr &AL) { if (AL.getNumArgs() > 0) { if (D->getFunctionType()) { handleNonNullAttr(S, D, AL); } else { S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args) << D->getSourceRange(); } return; } // Is the argument a pointer type? if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(), D->getSourceRange())) return; D->addAttr(::new (S.Context) NonNullAttr(AL.getRange(), S.Context, nullptr, 0, AL.getAttributeSpellingListIndex())); } static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) { QualType ResultType = getFunctionOrMethodResultType(D); SourceRange SR = getFunctionOrMethodResultSourceRange(D); if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR, /* isReturnValue */ true)) return; D->addAttr(::new (S.Context) ReturnsNonNullAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (D->isInvalidDecl()) return; // noescape only applies to pointer types. QualType T = cast(D)->getType(); if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) { S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) << AL << AL.getRange() << 0; return; } D->addAttr(::new (S.Context) NoEscapeAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *E = AL.getArgAsExpr(0), *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr; S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE, AL.getAttributeSpellingListIndex()); } static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0), AL.getAttributeSpellingListIndex()); } void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex) { QualType ResultType = getFunctionOrMethodResultType(D); SourceRange SR = getFunctionOrMethodResultSourceRange(D); AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) << &TmpAttr << AttrRange << SR; return; } if (!E->isValueDependent()) { llvm::APSInt I(64); if (!E->isIntegerConstantExpr(I, Context)) { if (OE) Diag(AttrLoc, diag::err_attribute_argument_n_type) << &TmpAttr << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); else Diag(AttrLoc, diag::err_attribute_argument_type) << &TmpAttr << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } if (!I.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } } if (OE) { if (!OE->isValueDependent()) { llvm::APSInt I(64); if (!OE->isIntegerConstantExpr(I, Context)) { Diag(AttrLoc, diag::err_attribute_argument_n_type) << &TmpAttr << 2 << AANT_ArgumentIntegerConstant << OE->getSourceRange(); return; } } } D->addAttr(::new (Context) AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); } void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, unsigned SpellingListIndex) { QualType ResultType = getFunctionOrMethodResultType(D); AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); if (!ResultType->isDependentType() && !isValidPointerAttrType(ResultType, /* RefOkay */ true)) { Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D); return; } ParamIdx Idx; const auto *FuncDecl = cast(D); if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr, /*AttrArgNo=*/1, ParamExpr, Idx)) return; QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) { Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only) << &TmpAttr << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange(); return; } D->addAttr(::new (Context) AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex)); } /// Normalize the attribute, __foo__ becomes foo. /// Returns true if normalization was applied. static bool normalizeName(StringRef &AttrName) { if (AttrName.size() > 4 && AttrName.startswith("__") && AttrName.endswith("__")) { AttrName = AttrName.drop_front(2).drop_back(2); return true; } return false; } static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // This attribute must be applied to a function declaration. The first // argument to the attribute must be an identifier, the name of the resource, // for example: malloc. The following arguments must be argument indexes, the // arguments must be of integer type for Returns, otherwise of pointer type. // The difference between Holds and Takes is that a pointer may still be used // after being held. free() should be __attribute((ownership_takes)), whereas // a list append function may well be __attribute((ownership_holds)). if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIdentifier; return; } // Figure out our Kind. OwnershipAttr::OwnershipKind K = OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, AL.getAttributeSpellingListIndex()).getOwnKind(); // Check arguments. switch (K) { case OwnershipAttr::Takes: case OwnershipAttr::Holds: if (AL.getNumArgs() < 2) { S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2; return; } break; case OwnershipAttr::Returns: if (AL.getNumArgs() > 2) { S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; return; } break; } IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; StringRef ModuleName = Module->getName(); if (normalizeName(ModuleName)) { Module = &S.PP.getIdentifierTable().get(ModuleName); } SmallVector OwnershipArgs; for (unsigned i = 1; i < AL.getNumArgs(); ++i) { Expr *Ex = AL.getArgAsExpr(i); ParamIdx Idx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) return; // Is the function argument a pointer type? QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex()); int Err = -1; // No error switch (K) { case OwnershipAttr::Takes: case OwnershipAttr::Holds: if (!T->isAnyPointerType() && !T->isBlockPointerType()) Err = 0; break; case OwnershipAttr::Returns: if (!T->isIntegerType()) Err = 1; break; } if (-1 != Err) { S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err << Ex->getSourceRange(); return; } // Check we don't have a conflict with another ownership attribute. for (const auto *I : D->specific_attrs()) { // Cannot have two ownership attributes of different kinds for the same // index. if (I->getOwnKind() != K && I->args_end() != std::find(I->args_begin(), I->args_end(), Idx)) { S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I; return; } else if (K == OwnershipAttr::Returns && I->getOwnKind() == OwnershipAttr::Returns) { // A returns attribute conflicts with any other returns attribute using // a different index. if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) << I->args_begin()->getSourceIndex(); if (I->args_size()) S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) << Idx.getSourceIndex() << Ex->getSourceRange(); return; } } } OwnershipArgs.push_back(Idx); } ParamIdx *Start = OwnershipArgs.data(); unsigned Size = OwnershipArgs.size(); llvm::array_pod_sort(Start, Start + Size); D->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size, AL.getAttributeSpellingListIndex())); } static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Check the attribute arguments. if (AL.getNumArgs() > 1) { S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; return; } // gcc rejects // class c { // static int a __attribute__((weakref ("v2"))); // static int b() __attribute__((weakref ("f3"))); // }; // and ignores the attributes of // void f(void) { // static int a __attribute__((weakref ("v2"))); // } // we reject them const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); if (!Ctx->isFileContext()) { S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context) << cast(D); return; } // The GCC manual says // // At present, a declaration to which `weakref' is attached can only // be `static'. // // It also says // // Without a TARGET, // given as an argument to `weakref' or to `alias', `weakref' is // equivalent to `weak'. // // gcc 4.4.1 will accept // int a7 __attribute__((weakref)); // as // int a7 __attribute__((weak)); // This looks like a bug in gcc. We reject that for now. We should revisit // it if this behaviour is actually used. // GCC rejects // static ((alias ("y"), weakref)). // Should we? How to check that weakref is before or after alias? // FIXME: it would be good for us to keep the WeakRefAttr as-written instead // of transforming it into an AliasAttr. The WeakRefAttr never uses the // StringRef parameter it was given anyway. StringRef Str; if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str)) // GCC will accept anything as the argument of weakref. Should we // check for an existing decl? D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); D->addAttr(::new (S.Context) WeakRefAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef Str; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) return; // Aliases should be on declarations, not definitions. const auto *FD = cast(D); if (FD->isThisDeclarationADefinition()) { S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1; return; } D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef Str; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) return; if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin); return; } if (S.Context.getTargetInfo().getTriple().isNVPTX()) { S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx); } // Aliases should be on declarations, not definitions. if (const auto *FD = dyn_cast(D)) { if (FD->isThisDeclarationADefinition()) { S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0; return; } } else { const auto *VD = cast(D); if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0; return; } } // Mark target used to prevent unneeded-internal-declaration warnings. if (!S.LangOpts.CPlusPlus) { // FIXME: demangle Str for C++, as the attribute refers to the mangled // linkage name, not the pre-mangled identifier. const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc()); LookupResult LR(S, target, Sema::LookupOrdinaryName); if (S.LookupQualifiedName(LR, S.getCurLexicalContext())) for (NamedDecl *ND : LR) ND->markUsed(S.Context); } D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef Model; SourceLocation LiteralLoc; // Check that it is a string. if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc)) return; // Check that the value. if (Model != "global-dynamic" && Model != "local-dynamic" && Model != "initial-exec" && Model != "local-exec") { S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); return; } D->addAttr(::new (S.Context) TLSModelAttr(AL.getRange(), S.Context, Model, AL.getAttributeSpellingListIndex())); } static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) { QualType ResultType = getFunctionOrMethodResultType(D); if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { D->addAttr(::new (S.Context) RestrictAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; } S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL << getFunctionOrMethodResultSourceRange(D); } static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) { FunctionDecl *FD = cast(D); if (const auto *MD = dyn_cast(D)) { if (MD->getParent()->isLambda()) { S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL; return; } } if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; SmallVector CPUs; for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) { if (!AL.isArgIdent(ArgNo)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo); StringRef CPUName = CPUArg->Ident->getName().trim(); if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) { S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value) << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch); return; } const TargetInfo &Target = S.Context.getTargetInfo(); if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) { return Target.CPUSpecificManglingCharacter(CPUName) == Target.CPUSpecificManglingCharacter(Cur->getName()); })) { S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries); return; } CPUs.push_back(CPUArg->Ident); } FD->setIsMultiVersion(true); if (AL.getKind() == ParsedAttr::AT_CPUSpecific) D->addAttr(::new (S.Context) CPUSpecificAttr( AL.getRange(), S.Context, CPUs.data(), CPUs.size(), AL.getAttributeSpellingListIndex())); else D->addAttr(::new (S.Context) CPUDispatchAttr( AL.getRange(), S.Context, CPUs.data(), CPUs.size(), AL.getAttributeSpellingListIndex())); } static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (S.LangOpts.CPlusPlus) { S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) << AL << AttributeLangSupport::Cpp; return; } if (CommonAttr *CA = S.mergeCommonAttr(D, AL)) D->addAttr(CA); } static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL)) return; if (AL.isDeclspecAttribute()) { const auto &Triple = S.getASTContext().getTargetInfo().getTriple(); const auto &Arch = Triple.getArch(); if (Arch != llvm::Triple::x86 && (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) { S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch) << AL << Triple.getArchName(); return; } } D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { if (hasDeclarator(D)) return; if (!isa(D)) { S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type) << Attrs << ExpectedFunctionOrMethod; return; } D->addAttr(::new (S.Context) NoReturnAttr( Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { if (!S.getLangOpts().CFProtectionBranch) S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored); else handleSimpleAttribute(S, D, Attrs); } bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) { if (!checkAttributeNumArgs(*this, Attrs, 0)) { Attrs.setInvalid(); return true; } return false; } bool Sema::CheckAttrTarget(const ParsedAttr &AL) { // Check whether the attribute is valid on the current target. if (!AL.existsInTarget(Context.getTargetInfo())) { Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL; AL.setInvalid(); return true; } return false; } static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // The checking path for 'noreturn' and 'analyzer_noreturn' are different // because 'analyzer_noreturn' does not impact the type. if (!isFunctionOrMethodOrBlock(D)) { ValueDecl *VD = dyn_cast(D); if (!VD || (!VD->getType()->isBlockPointerType() && !VD->getType()->isFunctionPointerType())) { S.Diag(AL.getLoc(), AL.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type : diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunctionMethodOrBlock; return; } } D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } // PS3 PPU-specific. static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { /* Returning a Vector Class in Registers According to the PPU ABI specifications, a class with a single member of vector type is returned in memory when used as the return value of a function. This results in inefficient code when implementing vector classes. To return the value in a single vector register, add the vecreturn attribute to the class definition. This attribute is also applicable to struct types. Example: struct Vector { __vector float xyzw; } __attribute__((vecreturn)); Vector Add(Vector lhs, Vector rhs) { Vector result; result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); return result; // This will be returned in a register } */ if (VecReturnAttr *A = D->getAttr()) { S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A; return; } const auto *R = cast(D); int count = 0; if (!isa(R)) { S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); return; } if (!cast(R)->isPOD()) { S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record); return; } for (const auto *I : R->fields()) { if ((count == 1) || !I->getType()->isVectorType()) { S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); return; } count++; } D->addAttr(::new (S.Context) VecReturnAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, const ParsedAttr &AL) { if (isa(D)) { // [[carries_dependency]] can only be applied to a parameter if it is a // parameter of a function declaration or lambda. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { S.Diag(AL.getLoc(), diag::err_carries_dependency_param_not_function_decl); return; } } D->addAttr(::new (S.Context) CarriesDependencyAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName(); // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; D->addAttr(::new (S.Context) UnusedAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t priority = ConstructorAttr::DefaultPriority; if (AL.getNumArgs() && !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) return; D->addAttr(::new (S.Context) ConstructorAttr(AL.getRange(), S.Context, priority, AL.getAttributeSpellingListIndex())); } static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t priority = DestructorAttr::DefaultPriority; if (AL.getNumArgs() && !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) return; D->addAttr(::new (S.Context) DestructorAttr(AL.getRange(), S.Context, priority, AL.getAttributeSpellingListIndex())); } template static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) { // Handle the case where the attribute has a text message. StringRef Str; if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str)) return; D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!cast(D)->isThisDeclarationADefinition()) { S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition) << AL << AL.getRange(); return; } D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static bool checkAvailabilityAttr(Sema &S, SourceRange Range, IdentifierInfo *Platform, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted) { StringRef PlatformName = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); if (PlatformName.empty()) PlatformName = Platform->getName(); // Ensure that Introduced <= Deprecated <= Obsoleted (although not all // of these steps are needed). if (!Introduced.empty() && !Deprecated.empty() && !(Introduced <= Deprecated)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 1 << PlatformName << Deprecated.getAsString() << 0 << Introduced.getAsString(); return true; } if (!Introduced.empty() && !Obsoleted.empty() && !(Introduced <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 2 << PlatformName << Obsoleted.getAsString() << 0 << Introduced.getAsString(); return true; } if (!Deprecated.empty() && !Obsoleted.empty() && !(Deprecated <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 2 << PlatformName << Obsoleted.getAsString() << 1 << Deprecated.getAsString(); return true; } return false; } /// Check whether the two versions match. /// /// If either version tuple is empty, then they are assumed to match. If /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, bool BeforeIsOkay) { if (X.empty() || Y.empty()) return true; if (X == Y) return true; if (BeforeIsOkay && X < Y) return true; return false; } AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, unsigned AttrSpellingListIndex) { VersionTuple MergedIntroduced = Introduced; VersionTuple MergedDeprecated = Deprecated; VersionTuple MergedObsoleted = Obsoleted; bool FoundAny = false; bool OverrideOrImpl = false; switch (AMK) { case AMK_None: case AMK_Redeclaration: OverrideOrImpl = false; break; case AMK_Override: case AMK_ProtocolImplementation: OverrideOrImpl = true; break; } if (D->hasAttrs()) { AttrVec &Attrs = D->getAttrs(); for (unsigned i = 0, e = Attrs.size(); i != e;) { const auto *OldAA = dyn_cast(Attrs[i]); if (!OldAA) { ++i; continue; } IdentifierInfo *OldPlatform = OldAA->getPlatform(); if (OldPlatform != Platform) { ++i; continue; } // If there is an existing availability attribute for this platform that // is explicit and the new one is implicit use the explicit one and // discard the new implicit attribute. if (!OldAA->isImplicit() && Implicit) { return nullptr; } // If there is an existing attribute for this platform that is implicit // and the new attribute is explicit then erase the old one and // continue processing the attributes. if (!Implicit && OldAA->isImplicit()) { Attrs.erase(Attrs.begin() + i); --e; continue; } FoundAny = true; VersionTuple OldIntroduced = OldAA->getIntroduced(); VersionTuple OldDeprecated = OldAA->getDeprecated(); VersionTuple OldObsoleted = OldAA->getObsoleted(); bool OldIsUnavailable = OldAA->getUnavailable(); if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || !(OldIsUnavailable == IsUnavailable || (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { if (OverrideOrImpl) { int Which = -1; VersionTuple FirstVersion; VersionTuple SecondVersion; if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { Which = 0; FirstVersion = OldIntroduced; SecondVersion = Introduced; } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { Which = 1; FirstVersion = Deprecated; SecondVersion = OldDeprecated; } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { Which = 2; FirstVersion = Obsoleted; SecondVersion = OldObsoleted; } if (Which == -1) { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override_unavail) << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) << (AMK == AMK_Override); } else { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override) << Which << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) << FirstVersion.getAsString() << SecondVersion.getAsString() << (AMK == AMK_Override); } if (AMK == AMK_Override) Diag(Range.getBegin(), diag::note_overridden_method); else Diag(Range.getBegin(), diag::note_protocol_method); } else { Diag(OldAA->getLocation(), diag::warn_mismatched_availability); Diag(Range.getBegin(), diag::note_previous_attribute); } Attrs.erase(Attrs.begin() + i); --e; continue; } VersionTuple MergedIntroduced2 = MergedIntroduced; VersionTuple MergedDeprecated2 = MergedDeprecated; VersionTuple MergedObsoleted2 = MergedObsoleted; if (MergedIntroduced2.empty()) MergedIntroduced2 = OldIntroduced; if (MergedDeprecated2.empty()) MergedDeprecated2 = OldDeprecated; if (MergedObsoleted2.empty()) MergedObsoleted2 = OldObsoleted; if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, MergedIntroduced2, MergedDeprecated2, MergedObsoleted2)) { Attrs.erase(Attrs.begin() + i); --e; continue; } MergedIntroduced = MergedIntroduced2; MergedDeprecated = MergedDeprecated2; MergedObsoleted = MergedObsoleted2; ++i; } } if (FoundAny && MergedIntroduced == Introduced && MergedDeprecated == Deprecated && MergedObsoleted == Obsoleted) return nullptr; // Only create a new attribute if !OverrideOrImpl, but we want to do // the checking. if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, MergedDeprecated, MergedObsoleted) && !OverrideOrImpl) { auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable, Message, IsStrict, Replacement, AttrSpellingListIndex); Avail->setImplicit(Implicit); return Avail; } return nullptr; } static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeNumArgs(S, AL, 1)) return; IdentifierLoc *Platform = AL.getArgAsIdent(0); unsigned Index = AL.getAttributeSpellingListIndex(); IdentifierInfo *II = Platform->Ident; if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Platform->Ident; auto *ND = dyn_cast(D); if (!ND) // We warned about this already, so just return. return; AvailabilityChange Introduced = AL.getAvailabilityIntroduced(); AvailabilityChange Deprecated = AL.getAvailabilityDeprecated(); AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted(); bool IsUnavailable = AL.getUnavailableLoc().isValid(); bool IsStrict = AL.getStrictLoc().isValid(); StringRef Str; if (const auto *SE = dyn_cast_or_null(AL.getMessageExpr())) Str = SE->getString(); StringRef Replacement; if (const auto *SE = dyn_cast_or_null(AL.getReplacementExpr())) Replacement = SE->getString(); if (II->isStr("swift")) { if (Introduced.isValid() || Obsoleted.isValid() || (!IsUnavailable && !Deprecated.isValid())) { S.Diag(AL.getLoc(), diag::warn_availability_swift_unavailable_deprecated_only); return; } } AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II, false/*Implicit*/, Introduced.Version, Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning // matches before the start of the watchOS platform. if (S.Context.getTargetInfo().getTriple().isWatchOS()) { IdentifierInfo *NewII = nullptr; if (II->getName() == "ios") NewII = &S.Context.Idents.get("watchos"); else if (II->getName() == "ios_app_extension") NewII = &S.Context.Idents.get("watchos_app_extension"); if (NewII) { auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { if (Version.empty()) return Version; auto Major = Version.getMajor(); auto NewMajor = Major >= 9 ? Major - 7 : 0; if (NewMajor >= 2) { if (Version.getMinor().hasValue()) { if (Version.getSubminor().hasValue()) return VersionTuple(NewMajor, Version.getMinor().getValue(), Version.getSubminor().getValue()); else return VersionTuple(NewMajor, Version.getMinor().getValue()); } } return VersionTuple(2, 0); }; auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), NewII, true/*Implicit*/, NewIntroduced, NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); } } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning // matches before the start of the tvOS platform. IdentifierInfo *NewII = nullptr; if (II->getName() == "ios") NewII = &S.Context.Idents.get("tvos"); else if (II->getName() == "ios_app_extension") NewII = &S.Context.Idents.get("tvos_app_extension"); if (NewII) { AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), NewII, true/*Implicit*/, Introduced.Version, Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); } } } static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; assert(checkAttributeAtMostNumArgs(S, AL, 3) && "Invalid number of arguments in an external_source_symbol attribute"); StringRef Language; if (const auto *SE = dyn_cast_or_null(AL.getArgAsExpr(0))) Language = SE->getString(); StringRef DefinedIn; if (const auto *SE = dyn_cast_or_null(AL.getArgAsExpr(1))) DefinedIn = SE->getString(); bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr; D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration, AL.getAttributeSpellingListIndex())); } template static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, typename T::VisibilityType value, unsigned attrSpellingListIndex) { T *existingAttr = D->getAttr(); if (existingAttr) { typename T::VisibilityType existingValue = existingAttr->getVisibility(); if (existingValue == value) return nullptr; S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); S.Diag(range.getBegin(), diag::note_previous_attribute); D->dropAttr(); } return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); } VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex) { return ::mergeVisibilityAttr(*this, D, Range, Vis, AttrSpellingListIndex); } TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex) { return ::mergeVisibilityAttr(*this, D, Range, Vis, AttrSpellingListIndex); } static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, bool isTypeVisibility) { // Visibility attributes don't mean anything on a typedef. if (isa(D)) { S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL; return; } // 'type_visibility' can only go on a type or namespace. if (isTypeVisibility && !(isa(D) || isa(D) || isa(D))) { S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) << AL << ExpectedTypeOrNamespace; return; } // Check that the argument is a string literal. StringRef TypeStr; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc)) return; VisibilityAttr::VisibilityType type; if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL << TypeStr; return; } // Complain about attempts to use protected visibility on targets // (like Darwin) that don't support it. if (type == VisibilityAttr::Protected && !S.Context.getTargetInfo().hasProtectedVisibility()) { S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility); type = VisibilityAttr::Default; } unsigned Index = AL.getAttributeSpellingListIndex(); Attr *newAttr; if (isTypeVisibility) { newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(), (TypeVisibilityAttr::VisibilityType) type, Index); } else { newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index); } if (newAttr) D->addAttr(newAttr); } static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) { const auto *M = cast(D); if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIdentifier; return; } IdentifierLoc *IL = AL.getArgAsIdent(0); ObjCMethodFamilyAttr::FamilyKind F; if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; return; } if (F == ObjCMethodFamilyAttr::OMF_init && !M->getReturnType()->isObjCObjectPointerType()) { S.Diag(M->getLocation(), diag::err_init_method_bad_return_type) << M->getReturnType(); // Ignore the attribute. return; } D->addAttr(new (S.Context) ObjCMethodFamilyAttr( AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex())); } static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { if (const auto *TD = dyn_cast(D)) { QualType T = TD->getUnderlyingType(); if (!T->isCARCBridgableType()) { S.Diag(TD->getLocation(), diag::err_nsobject_attribute); return; } } else if (const auto *PD = dyn_cast(D)) { QualType T = PD->getType(); if (!T->isCARCBridgableType()) { S.Diag(PD->getLocation(), diag::err_nsobject_attribute); return; } } else { // It is okay to include this attribute on properties, e.g.: // // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); // // In this case it follows tradition and suppresses an error in the above // case. S.Diag(D->getLocation(), diag::warn_nsobject_attribute); } D->addAttr(::new (S.Context) ObjCNSObjectAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) { if (const auto *TD = dyn_cast(D)) { QualType T = TD->getUnderlyingType(); if (!T->isObjCObjectPointerType()) { S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); return; } } else { S.Diag(D->getLocation(), diag::warn_independentclass_attribute); return; } D->addAttr(::new (S.Context) ObjCIndependentClassAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIdentifier; return; } IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; BlocksAttr::BlockType type; if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; return; } D->addAttr(::new (S.Context) BlocksAttr(AL.getRange(), S.Context, type, AL.getAttributeSpellingListIndex())); } static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; if (AL.getNumArgs() > 0) { Expr *E = AL.getArgAsExpr(0); llvm::APSInt Idx(32); if (E->isTypeDependent() || E->isValueDependent() || !E->isIntegerConstantExpr(Idx, S.Context)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } if (Idx.isSigned() && Idx.isNegative()) { S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) << E->getSourceRange(); return; } sentinel = Idx.getZExtValue(); } unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; if (AL.getNumArgs() > 1) { Expr *E = AL.getArgAsExpr(1); llvm::APSInt Idx(32); if (E->isTypeDependent() || E->isValueDependent() || !E->isIntegerConstantExpr(Idx, S.Context)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } nullPos = Idx.getZExtValue(); if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { // FIXME: This error message could be improved, it would be nice // to say what the bounds actually are. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) << E->getSourceRange(); return; } } if (const auto *FD = dyn_cast(D)) { const FunctionType *FT = FD->getType()->castAs(); if (isa(FT)) { S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments); return; } if (!cast(FT)->isVariadic()) { S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; return; } } else if (const auto *MD = dyn_cast(D)) { if (!MD->isVariadic()) { S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; return; } } else if (const auto *BD = dyn_cast(D)) { if (!BD->isVariadic()) { S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; return; } } else if (const auto *V = dyn_cast(D)) { QualType Ty = V->getType(); if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { const FunctionType *FT = Ty->isFunctionPointerType() ? D->getFunctionType() : Ty->getAs()->getPointeeType()->getAs(); if (!cast(FT)->isVariadic()) { int m = Ty->isFunctionPointerType() ? 0 : 1; S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; return; } } else { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunctionMethodOrBlock; return; } } else { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunctionMethodOrBlock; return; } D->addAttr(::new (S.Context) SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos, AL.getAttributeSpellingListIndex())); } static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { if (D->getFunctionType() && D->getFunctionType()->getReturnType()->isVoidType()) { S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0; return; } if (const auto *MD = dyn_cast(D)) if (MD->getReturnType()->isVoidType()) { S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1; return; } // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() && !AL.getScopeName()) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; D->addAttr(::new (S.Context) WarnUnusedResultAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // weak_import only applies to variable & function declarations. bool isDef = false; if (!D->canBeWeakImported(isDef)) { if (isDef) S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) << "weak_import"; else if (isa(D) || isa(D) || (S.Context.getTargetInfo().getTriple().isOSDarwin() && (isa(D) || isa(D)))) { // Nothing to warn about here. } else S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedVariableOrFunction; return; } D->addAttr(::new (S.Context) WeakImportAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } // Handles reqd_work_group_size and work_group_size_hint. template static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t WGSize[3]; for (unsigned i = 0; i < 3; ++i) { const Expr *E = AL.getArgAsExpr(i); if (!checkUInt32Argument(S, AL, E, WGSize[i], i, /*StrictlyUnsigned=*/true)) return; if (WGSize[i] == 0) { S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) << AL << E->getSourceRange(); return; } } WorkGroupAttr *Existing = D->getAttr(); if (Existing && !(Existing->getXDim() == WGSize[0] && Existing->getYDim() == WGSize[1] && Existing->getZDim() == WGSize[2])) S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context, WGSize[0], WGSize[1], WGSize[2], AL.getAttributeSpellingListIndex())); } // Handles intel_reqd_sub_group_size. static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t SGSize; const Expr *E = AL.getArgAsExpr(0); if (!checkUInt32Argument(S, AL, E, SGSize)) return; if (SGSize == 0) { S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) << AL << E->getSourceRange(); return; } OpenCLIntelReqdSubGroupSizeAttr *Existing = D->getAttr(); if (Existing && Existing->getSubGroupSize() != SGSize) S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr( AL.getRange(), S.Context, SGSize, AL.getAttributeSpellingListIndex())); } static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.hasParsedType()) { S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; return; } TypeSourceInfo *ParmTSI = nullptr; QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI); assert(ParmTSI && "no type source info for attribute argument"); if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && (ParmType->isBooleanType() || !ParmType->isIntegralType(S.getASTContext()))) { S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint) << ParmType; return; } if (VecTypeHintAttr *A = D->getAttr()) { if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; return; } } D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context, ParmTSI, AL.getAttributeSpellingListIndex())); } SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex) { // Explicit or partial specializations do not inherit // the section attribute from the primary template. if (const auto *FD = dyn_cast(D)) { if (AttrSpellingListIndex == SectionAttr::Declspec_allocate && FD->isFunctionTemplateSpecialization()) return nullptr; } if (SectionAttr *ExistingAttr = D->getAttr()) { if (ExistingAttr->getName() == Name) return nullptr; Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) << 1 /*section*/; Diag(Range.getBegin(), diag::note_previous_attribute); return nullptr; } return ::new (Context) SectionAttr(Range, Context, Name, AttrSpellingListIndex); } bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); if (!Error.empty()) { Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error << 1 /*'section'*/; return false; } return true; } static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Make sure that there is a string literal as the sections's single // argument. StringRef Str; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) return; if (!S.checkSectionName(LiteralLoc, Str)) return; // If the target wants to validate the section specifier, make it happen. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); if (!Error.empty()) { S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; return; } unsigned Index = AL.getAttributeSpellingListIndex(); SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index); if (NewAttr) D->addAttr(NewAttr); } static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) { std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName); if (!Error.empty()) { S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error << 0 /*'code-seg'*/; return false; } return true; } CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex) { // Explicit or partial specializations do not inherit // the code_seg attribute from the primary template. if (const auto *FD = dyn_cast(D)) { if (FD->isFunctionTemplateSpecialization()) return nullptr; } if (const auto *ExistingAttr = D->getAttr()) { if (ExistingAttr->getName() == Name) return nullptr; Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) << 0 /*codeseg*/; Diag(Range.getBegin(), diag::note_previous_attribute); return nullptr; } return ::new (Context) CodeSegAttr(Range, Context, Name, AttrSpellingListIndex); } static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef Str; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) return; if (!checkCodeSegName(S, LiteralLoc, Str)) return; if (const auto *ExistingAttr = D->getAttr()) { if (!ExistingAttr->isImplicit()) { S.Diag(AL.getLoc(), ExistingAttr->getName() == Str ? diag::warn_duplicate_codeseg_attribute : diag::err_conflicting_codeseg_attribute); return; } D->dropAttr(); } if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str, AL.getAttributeSpellingListIndex())) D->addAttr(CSA); } // Check for things we'd like to warn about. Multiversioning issues are // handled later in the process, once we know how many exist. bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { enum FirstParam { Unsupported, Duplicate }; enum SecondParam { None, Architecture }; for (auto Str : {"tune=", "fpmath="}) if (AttrStr.find(Str) != StringRef::npos) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << None << Str; TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); if (!ParsedAttrs.Architecture.empty() && !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << Architecture << ParsedAttrs.Architecture; if (ParsedAttrs.DuplicateArchitecture) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Duplicate << None << "arch="; for (const auto &Feature : ParsedAttrs.Features) { auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << None << CurFeature; } return false; } static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef Str; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) || S.checkTargetAttr(LiteralLoc, Str)) return; unsigned Index = AL.getAttributeSpellingListIndex(); TargetAttr *NewAttr = ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index); D->addAttr(NewAttr); } static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *E = AL.getArgAsExpr(0); uint32_t VecWidth; if (!checkUInt32Argument(S, AL, E, VecWidth)) { AL.setInvalid(); return; } MinVectorWidthAttr *Existing = D->getAttr(); if (Existing && Existing->getVectorWidth() != VecWidth) { S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; return; } D->addAttr(::new (S.Context) MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth, AL.getAttributeSpellingListIndex())); } static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *E = AL.getArgAsExpr(0); SourceLocation Loc = E->getExprLoc(); FunctionDecl *FD = nullptr; DeclarationNameInfo NI; // gcc only allows for simple identifiers. Since we support more than gcc, we // will warn the user. if (auto *DRE = dyn_cast(E)) { if (DRE->hasQualifier()) S.Diag(Loc, diag::warn_cleanup_ext); FD = dyn_cast(DRE->getDecl()); NI = DRE->getNameInfo(); if (!FD) { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 << NI.getName(); return; } } else if (auto *ULE = dyn_cast(E)) { if (ULE->hasExplicitTemplateArgs()) S.Diag(Loc, diag::warn_cleanup_ext); FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); NI = ULE->getNameInfo(); if (!FD) { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 << NI.getName(); if (ULE->getType() == S.Context.OverloadTy) S.NoteAllOverloadCandidates(ULE); return; } } else { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; return; } if (FD->getNumParams() != 1) { S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) << NI.getName(); return; } // We're currently more strict than GCC about what function types we accept. // If this ever proves to be a problem it should be easy to fix. QualType Ty = S.Context.getPointerType(cast(D)->getType()); QualType ParamTy = FD->getParamDecl(0)->getType(); if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), ParamTy, Ty) != Sema::Compatible) { S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) << NI.getName() << ParamTy << Ty; return; } D->addAttr(::new (S.Context) CleanupAttr(AL.getRange(), S.Context, FD, AL.getAttributeSpellingListIndex())); } static void handleEnumExtensibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 0 << AANT_ArgumentIdentifier; return; } EnumExtensibilityAttr::Kind ExtensibilityKind; IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), ExtensibilityKind)) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; return; } D->addAttr(::new (S.Context) EnumExtensibilityAttr( AL.getRange(), S.Context, ExtensibilityKind, AL.getAttributeSpellingListIndex())); } /// Handle __attribute__((format_arg((idx)))) attribute based on /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) { Expr *IdxExpr = AL.getArgAsExpr(0); ParamIdx Idx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx)) return; // Make sure the format string is really a string. QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); bool NotNSStringTy = !isNSStringType(Ty, S.Context); if (NotNSStringTy && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType())) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) << "a string type" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); return; } Ty = getFunctionOrMethodResultType(D); if (!isNSStringType(Ty, S.Context) && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType())) { S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) << (NotNSStringTy ? "string type" : "NSString") << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); return; } D->addAttr(::new (S.Context) FormatArgAttr( AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex())); } enum FormatAttrKind { CFStringFormat, NSStringFormat, StrftimeFormat, SupportedFormat, IgnoredFormat, InvalidFormat }; /// getFormatAttrKind - Map from format attribute names to supported format /// types. static FormatAttrKind getFormatAttrKind(StringRef Format) { return llvm::StringSwitch(Format) // Check for formats that get handled specially. .Case("NSString", NSStringFormat) .Case("CFString", CFStringFormat) .Case("strftime", StrftimeFormat) // Otherwise, check for supported formats. .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) .Case("kprintf", SupportedFormat) // OpenBSD. .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. .Case("os_trace", SupportedFormat) .Case("os_log", SupportedFormat) .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) .Default(InvalidFormat); } /// Handle __attribute__((init_priority(priority))) attributes based on /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!S.getLangOpts().CPlusPlus) { S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; return; } if (S.getCurFunctionOrMethodDecl()) { S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); AL.setInvalid(); return; } QualType T = cast(D)->getType(); if (S.Context.getAsArrayType(T)) T = S.Context.getBaseElementType(T); if (!T->getAs()) { S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); AL.setInvalid(); return; } Expr *E = AL.getArgAsExpr(0); uint32_t prioritynum; if (!checkUInt32Argument(S, AL, E, prioritynum)) { AL.setInvalid(); return; } if (prioritynum < 101 || prioritynum > 65535) { S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range) << E->getSourceRange() << AL << 101 << 65535; AL.setInvalid(); return; } D->addAttr(::new (S.Context) InitPriorityAttr(AL.getRange(), S.Context, prioritynum, AL.getAttributeSpellingListIndex())); } FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex) { // Check whether we already have an equivalent format attribute. for (auto *F : D->specific_attrs()) { if (F->getType() == Format && F->getFormatIdx() == FormatIdx && F->getFirstArg() == FirstArg) { // If we don't have a valid location for this attribute, adopt the // location. if (F->getLocation().isInvalid()) F->setRange(Range); return nullptr; } } return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, FirstArg, AttrSpellingListIndex); } /// Handle __attribute__((format(type,idx,firstarg))) attributes based on /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIdentifier; return; } // In C++ the implicit 'this' function parameter also counts, and they are // counted from one. bool HasImplicitThisParam = isInstanceMethod(D); unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; StringRef Format = II->getName(); if (normalizeName(Format)) { // If we've modified the string name, we need a new identifier for it. II = &S.Context.Idents.get(Format); } // Check for supported formats. FormatAttrKind Kind = getFormatAttrKind(Format); if (Kind == IgnoredFormat) return; if (Kind == InvalidFormat) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II->getName(); return; } // checks for the 2nd argument Expr *IdxExpr = AL.getArgAsExpr(1); uint32_t Idx; if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2)) return; if (Idx < 1 || Idx > NumArgs) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) << AL << 2 << IdxExpr->getSourceRange(); return; } // FIXME: Do we need to bounds check? unsigned ArgIdx = Idx - 1; if (HasImplicitThisParam) { if (ArgIdx == 0) { S.Diag(AL.getLoc(), diag::err_format_attribute_implicit_this_format_string) << IdxExpr->getSourceRange(); return; } ArgIdx--; } // make sure the format string is really a string QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); if (Kind == CFStringFormat) { if (!isCFStringType(Ty, S.Context)) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) << "a CFString" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (Kind == NSStringFormat) { // FIXME: do we need to check if the type is NSString*? What are the // semantics? if (!isNSStringType(Ty, S.Context)) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) << "an NSString" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (!Ty->isPointerType() || !Ty->getAs()->getPointeeType()->isCharType()) { S.Diag(AL.getLoc(), diag::err_format_attribute_not) << "a string type" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } // check the 3rd argument Expr *FirstArgExpr = AL.getArgAsExpr(2); uint32_t FirstArg; if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3)) return; // check if the function is variadic if the 3rd argument non-zero if (FirstArg != 0) { if (isFunctionOrMethodVariadic(D)) { ++NumArgs; // +1 for ... } else { S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); return; } } // strftime requires FirstArg to be 0 because it doesn't read from any // variable the input is just the current time + the format string. if (Kind == StrftimeFormat) { if (FirstArg != 0) { S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) << FirstArgExpr->getSourceRange(); return; } // if 0 it disables parameter checking (to use with e.g. va_list) } else if (FirstArg != 0 && FirstArg != NumArgs) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) << AL << 3 << FirstArgExpr->getSourceRange(); return; } FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II, Idx, FirstArg, AL.getAttributeSpellingListIndex()); if (NewAttr) D->addAttr(NewAttr); } static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Try to find the underlying union declaration. RecordDecl *RD = nullptr; const auto *TD = dyn_cast(D); if (TD && TD->getUnderlyingType()->isUnionType()) RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); else RD = dyn_cast(D); if (!RD || !RD->isUnion()) { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedUnion; return; } if (!RD->isCompleteDefinition()) { if (!RD->isBeingDefined()) S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_not_definition); return; } RecordDecl::field_iterator Field = RD->field_begin(), FieldEnd = RD->field_end(); if (Field == FieldEnd) { S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); return; } FieldDecl *FirstField = *Field; QualType FirstType = FirstField->getType(); if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { S.Diag(FirstField->getLocation(), diag::warn_transparent_union_attribute_floating) << FirstType->isVectorType() << FirstType; return; } if (FirstType->isIncompleteType()) return; uint64_t FirstSize = S.Context.getTypeSize(FirstType); uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); for (; Field != FieldEnd; ++Field) { QualType FieldType = Field->getType(); if (FieldType->isIncompleteType()) return; // FIXME: this isn't fully correct; we also need to test whether the // members of the union would all have the same calling convention as the // first member of the union. Checking just the size and alignment isn't // sufficient (consider structs passed on the stack instead of in registers // as an example). if (S.Context.getTypeSize(FieldType) != FirstSize || S.Context.getTypeAlign(FieldType) > FirstAlign) { // Warn if we drop the attribute. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) : S.Context.getTypeAlign(FieldType); S.Diag(Field->getLocation(), diag::warn_transparent_union_attribute_field_size_align) << isSize << Field->getDeclName() << FieldBits; unsigned FirstBits = isSize? FirstSize : FirstAlign; S.Diag(FirstField->getLocation(), diag::note_transparent_union_first_field_size_align) << isSize << FirstBits; return; } } RD->addAttr(::new (S.Context) TransparentUnionAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Make sure that there is a string literal as the annotation's single // argument. StringRef Str; if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) return; // Don't duplicate annotations that are already set. for (const auto *I : D->specific_attrs()) { if (I->getAnnotation() == Str) return; } D->addAttr(::new (S.Context) AnnotateAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); } static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0), AL.getAttributeSpellingListIndex()); } void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex) { AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); QualType T; if (const auto *TD = dyn_cast(D)) T = TD->getUnderlyingType(); else if (const auto *VD = dyn_cast(D)) T = VD->getType(); else llvm_unreachable("Unknown decl type for align_value"); if (!T->isDependentType() && !T->isAnyPointerType() && !T->isReferenceType() && !T->isMemberPointerType()) { Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); return; } if (!E->isValueDependent()) { llvm::APSInt Alignment; ExprResult ICE = VerifyIntegerConstantExpression(E, &Alignment, diag::err_align_value_attribute_argument_not_int, /*AllowFold*/ false); if (ICE.isInvalid()) return; if (!Alignment.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } D->addAttr(::new (Context) AlignValueAttr(AttrRange, Context, ICE.get(), SpellingListIndex)); return; } // Save dependent expressions in the AST to be instantiated. D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); } static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // check the attribute arguments. if (AL.getNumArgs() > 1) { S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; return; } if (AL.getNumArgs() == 0) { D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context, true, nullptr, AL.getAttributeSpellingListIndex())); return; } Expr *E = AL.getArgAsExpr(0); if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) { S.Diag(AL.getEllipsisLoc(), diag::err_pack_expansion_without_parameter_packs); return; } if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) return; S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(), AL.isPackExpansion()); } void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion) { AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. if (TmpAttr.isAlignas()) { // C++11 [dcl.align]p1: // An alignment-specifier may be applied to a variable or to a class // data member, but it shall not be applied to a bit-field, a function // parameter, the formal parameter of a catch clause, or a variable // declared with the register storage class specifier. An // alignment-specifier may also be applied to the declaration of a class // or enumeration type. // C11 6.7.5/2: // An alignment attribute shall not be specified in a declaration of // a typedef, or a bit-field, or a function, or a parameter, or an // object declared with the register storage-class specifier. int DiagKind = -1; if (isa(D)) { DiagKind = 0; } else if (const auto *VD = dyn_cast(D)) { if (VD->getStorageClass() == SC_Register) DiagKind = 1; if (VD->isExceptionVariable()) DiagKind = 2; } else if (const auto *FD = dyn_cast(D)) { if (FD->isBitField()) DiagKind = 3; } else if (!isa(D)) { Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr << (TmpAttr.isC11() ? ExpectedVariableOrField : ExpectedVariableFieldOrTag); return; } if (DiagKind != -1) { Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) << &TmpAttr << DiagKind; return; } } if (E->isValueDependent()) { // We can't support a dependent alignment on a non-dependent type, // because we have no way to model that a type is "alignment-dependent" // but not dependent in any other way. if (const auto *TND = dyn_cast(D)) { if (!TND->getUnderlyingType()->isDependentType()) { Diag(AttrLoc, diag::err_alignment_dependent_typedef_name) << E->getSourceRange(); return; } } // Save dependent expressions in the AST to be instantiated. AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); return; } // FIXME: Cache the number on the AL object? llvm::APSInt Alignment; ExprResult ICE = VerifyIntegerConstantExpression(E, &Alignment, diag::err_aligned_attribute_argument_not_int, /*AllowFold*/ false); if (ICE.isInvalid()) return; uint64_t AlignVal = Alignment.getZExtValue(); // C++11 [dcl.align]p2: // -- if the constant expression evaluates to zero, the alignment // specifier shall have no effect // C11 6.7.5p6: // An alignment specification of zero has no effect. if (!(TmpAttr.isAlignas() && !Alignment)) { if (!llvm::isPowerOf2_64(AlignVal)) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } } // Alignment calculations can wrap around if it's greater than 2**28. unsigned MaxValidAlignment = Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 : 268435456; if (AlignVal > MaxValidAlignment) { Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment << E->getSourceRange(); return; } if (Context.getTargetInfo().isTLSSupported()) { unsigned MaxTLSAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) .getQuantity(); const auto *VD = dyn_cast(D); if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && VD->getTLSKind() != VarDecl::TLS_None) { Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) << (unsigned)AlignVal << VD << MaxTLSAlign; return; } } AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, ICE.get(), SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, unsigned SpellingListIndex, bool IsPackExpansion) { // FIXME: Cache the number on the AL object if non-dependent? // FIXME: Perform checking of type validity AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } void Sema::CheckAlignasUnderalignment(Decl *D) { assert(D->hasAttrs() && "no attributes on decl"); QualType UnderlyingTy, DiagTy; if (const auto *VD = dyn_cast(D)) { UnderlyingTy = DiagTy = VD->getType(); } else { UnderlyingTy = DiagTy = Context.getTagDeclType(cast(D)); if (const auto *ED = dyn_cast(D)) UnderlyingTy = ED->getIntegerType(); } if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) return; // C++11 [dcl.align]p5, C11 6.7.5/4: // The combined effect of all alignment attributes in a declaration shall // not specify an alignment that is less strict than the alignment that // would otherwise be required for the entity being declared. AlignedAttr *AlignasAttr = nullptr; unsigned Align = 0; for (auto *I : D->specific_attrs()) { if (I->isAlignmentDependent()) return; if (I->isAlignas()) AlignasAttr = I; Align = std::max(Align, I->getAlignment(Context)); } if (AlignasAttr && Align) { CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); if (NaturalAlign > RequestedAlign) Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) << DiagTy << (unsigned)NaturalAlign.getQuantity(); } } bool Sema::checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling) { assert(RD->hasDefinition() && "RD has no definition!"); // We may not have seen base specifiers or any virtual methods yet. We will // have to wait until the record is defined to catch any mismatches. if (!RD->getDefinition()->isCompleteDefinition()) return false; // The unspecified model never matches what a definition could need. if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) return false; if (BestCase) { if (RD->calculateInheritanceModel() == SemanticSpelling) return false; } else { if (RD->calculateInheritanceModel() <= SemanticSpelling) return false; } Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) << 0 /*definition*/; Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD->getNameAsString(); return true; } /// parseModeAttrArg - Parses attribute mode string and returns parsed type /// attribute. static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, bool &IntegerMode, bool &ComplexMode) { IntegerMode = true; ComplexMode = false; switch (Str.size()) { case 2: switch (Str[0]) { case 'Q': DestWidth = 8; break; case 'H': DestWidth = 16; break; case 'S': DestWidth = 32; break; case 'D': DestWidth = 64; break; case 'X': DestWidth = 96; break; case 'T': DestWidth = 128; break; } if (Str[1] == 'F') { IntegerMode = false; } else if (Str[1] == 'C') { IntegerMode = false; ComplexMode = true; } else if (Str[1] != 'I') { DestWidth = 0; } break; case 4: // FIXME: glibc uses 'word' to define register_t; this is narrower than a // pointer on PIC16 and other embedded platforms. if (Str == "word") DestWidth = S.Context.getTargetInfo().getRegisterWidth(); else if (Str == "byte") DestWidth = S.Context.getTargetInfo().getCharWidth(); break; case 7: if (Str == "pointer") DestWidth = S.Context.getTargetInfo().getPointerWidth(0); break; case 11: if (Str == "unwind_word") DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); break; } } /// handleModeAttr - This attribute modifies the width of a decl with primitive /// type. /// /// Despite what would be logical, the mode attribute is a decl attribute, not a /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be /// HImode, not an intermediate pointer. static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // This attribute isn't documented, but glibc uses it. It changes // the width of an int or unsigned int to the specified size. if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIdentifier; return; } IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident; S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex()); } void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation) { StringRef Str = Name->getName(); normalizeName(Str); SourceLocation AttrLoc = AttrRange.getBegin(); unsigned DestWidth = 0; bool IntegerMode = true; bool ComplexMode = false; llvm::APInt VectorSize(64, 0); if (Str.size() >= 4 && Str[0] == 'V') { // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). size_t StrSize = Str.size(); size_t VectorStringLength = 0; while ((VectorStringLength + 1) < StrSize && isdigit(Str[VectorStringLength + 1])) ++VectorStringLength; if (VectorStringLength && !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && VectorSize.isPowerOf2()) { parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, IntegerMode, ComplexMode); // Avoid duplicate warning from template instantiation. if (!InInstantiation) Diag(AttrLoc, diag::warn_vector_mode_deprecated); } else { VectorSize = 0; } } if (!VectorSize) parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t // and friends, at least with glibc. // FIXME: Make sure floating-point mappings are accurate // FIXME: Support XF and TF types if (!DestWidth) { Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; return; } QualType OldTy; if (const auto *TD = dyn_cast(D)) OldTy = TD->getUnderlyingType(); else if (const auto *ED = dyn_cast(D)) { // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. // Try to get type from enum declaration, default to int. OldTy = ED->getIntegerType(); if (OldTy.isNull()) OldTy = Context.IntTy; } else OldTy = cast(D)->getType(); if (OldTy->isDependentType()) { D->addAttr(::new (Context) ModeAttr(AttrRange, Context, Name, SpellingListIndex)); return; } // Base type can also be a vector type (see PR17453). // Distinguish between base type and base element type. QualType OldElemTy = OldTy; if (const auto *VT = OldTy->getAs()) OldElemTy = VT->getElementType(); // GCC allows 'mode' attribute on enumeration types (even incomplete), except // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. if ((isa(D) || OldElemTy->getAs()) && VectorSize.getBoolValue()) { Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; return; } bool IntegralOrAnyEnumType = OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs(); if (!OldElemTy->getAs() && !OldElemTy->isComplexType() && !IntegralOrAnyEnumType) Diag(AttrLoc, diag::err_mode_not_primitive); else if (IntegerMode) { if (!IntegralOrAnyEnumType) Diag(AttrLoc, diag::err_mode_wrong_type); } else if (ComplexMode) { if (!OldElemTy->isComplexType()) Diag(AttrLoc, diag::err_mode_wrong_type); } else { if (!OldElemTy->isFloatingType()) Diag(AttrLoc, diag::err_mode_wrong_type); } QualType NewElemTy; if (IntegerMode) NewElemTy = Context.getIntTypeForBitwidth(DestWidth, OldElemTy->isSignedIntegerType()); else NewElemTy = Context.getRealTypeForBitwidth(DestWidth); if (NewElemTy.isNull()) { Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; return; } if (ComplexMode) { NewElemTy = Context.getComplexType(NewElemTy); } QualType NewTy = NewElemTy; if (VectorSize.getBoolValue()) { NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), VectorType::GenericVector); } else if (const auto *OldVT = OldTy->getAs()) { // Complex machine mode does not support base vector types. if (ComplexMode) { Diag(AttrLoc, diag::err_complex_mode_vector_type); return; } unsigned NumElements = Context.getTypeSize(OldElemTy) * OldVT->getNumElements() / Context.getTypeSize(NewElemTy); NewTy = Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); } if (NewTy.isNull()) { Diag(AttrLoc, diag::err_mode_wrong_type); return; } // Install the new type. if (auto *TD = dyn_cast(D)) TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); else if (auto *ED = dyn_cast(D)) ED->setIntegerType(NewTy); else cast(D)->setType(NewTy); D->addAttr(::new (Context) ModeAttr(AttrRange, Context, Name, SpellingListIndex)); } static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) { D->addAttr(::new (S.Context) NoDebugAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex) { if (OptimizeNoneAttr *Optnone = D->getAttr()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; Diag(Optnone->getLocation(), diag::note_conflicting_attribute); return nullptr; } if (D->hasAttr()) return nullptr; return ::new (Context) AlwaysInlineAttr(Range, Context, AttrSpellingListIndex); } CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(*this, D, AL)) return nullptr; return ::new (Context) CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex()); } CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) { if (checkAttrMutualExclusion(*this, D, AL)) return nullptr; return ::new (Context) CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex()); } InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL) { if (const auto *VD = dyn_cast(D)) { // Attribute applies to Var but not any subclass of it (like ParmVar, // ImplicitParm or VarTemplateSpecialization). if (VD->getKind() != Decl::Var) { Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : ExpectedVariableOrFunction); return nullptr; } // Attribute does not apply to non-static local variables. if (VD->hasLocalStorage()) { Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); return nullptr; } } if (checkAttrMutualExclusion(*this, D, AL)) return nullptr; return ::new (Context) InternalLinkageAttr( AL.getRange(), Context, AL.getAttributeSpellingListIndex()); } InternalLinkageAttr * Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) { if (const auto *VD = dyn_cast(D)) { // Attribute applies to Var but not any subclass of it (like ParmVar, // ImplicitParm or VarTemplateSpecialization). if (VD->getKind() != Decl::Var) { Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type) << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : ExpectedVariableOrFunction); return nullptr; } // Attribute does not apply to non-static local variables. if (VD->hasLocalStorage()) { Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); return nullptr; } } if (checkAttrMutualExclusion(*this, D, AL)) return nullptr; return ::new (Context) InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex()); } MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (OptimizeNoneAttr *Optnone = D->getAttr()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; Diag(Optnone->getLocation(), diag::note_conflicting_attribute); return nullptr; } if (D->hasAttr()) return nullptr; return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); } OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (AlwaysInlineAttr *Inline = D->getAttr()) { Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; Diag(Range.getBegin(), diag::note_conflicting_attribute); D->dropAttr(); } if (MinSizeAttr *MinSize = D->getAttr()) { Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; Diag(Range.getBegin(), diag::note_conflicting_attribute); D->dropAttr(); } if (D->hasAttr()) return nullptr; return ::new (Context) OptimizeNoneAttr(Range, Context, AttrSpellingListIndex); } static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL)) return; if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( D, AL.getRange(), AL.getName(), AL.getAttributeSpellingListIndex())) D->addAttr(Inline); } static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( D, AL.getRange(), AL.getAttributeSpellingListIndex())) D->addAttr(MinSize); } static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( D, AL.getRange(), AL.getAttributeSpellingListIndex())) D->addAttr(Optnone); } static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL)) return; const auto *VD = cast(D); if (!VD->hasGlobalStorage()) { S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant); return; } D->addAttr(::new (S.Context) CUDAConstantAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL)) return; const auto *VD = cast(D); // extern __shared__ is only allowed on arrays with no length (e.g. // "int x[]"). if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() && !isa(VD->getType())) { S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD; return; } if (S.getLangOpts().CUDA && VD->hasLocalStorage() && S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared) << S.CurrentCUDATarget()) return; D->addAttr(::new (S.Context) CUDASharedAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (checkAttrMutualExclusion(S, D, AL) || checkAttrMutualExclusion(S, D, AL)) { return; } const auto *FD = cast(D); if (!FD->getReturnType()->isVoidType()) { SourceRange RTRange = FD->getReturnTypeSourceRange(); S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) << FD->getType() << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") : FixItHint()); return; } if (const auto *Method = dyn_cast(FD)) { if (Method->isInstance()) { S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method) << Method; return; } S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method; } // Only warn for "inline" when compiling for host, to cut down on noise. if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD; D->addAttr(::new (S.Context) CUDAGlobalAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { const auto *Fn = cast(D); if (!Fn->isInlineSpecified()) { S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); return; } D->addAttr(::new (S.Context) GNUInlineAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (hasDeclarator(D)) return; // Diagnostic is emitted elsewhere: here we store the (valid) AL // in the Decl node for syntactic reasoning, e.g., pretty-printing. CallingConv CC; if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) return; if (!isa(D)) { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunctionOrMethod; return; } switch (AL.getKind()) { case ParsedAttr::AT_FastCall: D->addAttr(::new (S.Context) FastCallAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_StdCall: D->addAttr(::new (S.Context) StdCallAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_ThisCall: D->addAttr(::new (S.Context) ThisCallAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_CDecl: D->addAttr(::new (S.Context) CDeclAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_Pascal: D->addAttr(::new (S.Context) PascalAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_SwiftCall: D->addAttr(::new (S.Context) SwiftCallAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_VectorCall: D->addAttr(::new (S.Context) VectorCallAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_MSABI: D->addAttr(::new (S.Context) MSABIAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_SysVABI: D->addAttr(::new (S.Context) SysVABIAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_RegCall: D->addAttr(::new (S.Context) RegCallAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_Pcs: { PcsAttr::PCSType PCS; switch (CC) { case CC_AAPCS: PCS = PcsAttr::AAPCS; break; case CC_AAPCS_VFP: PCS = PcsAttr::AAPCS_VFP; break; default: llvm_unreachable("unexpected calling convention in pcs attribute"); } D->addAttr(::new (S.Context) PcsAttr(AL.getRange(), S.Context, PCS, AL.getAttributeSpellingListIndex())); return; } case ParsedAttr::AT_AArch64VectorPcs: D->addAttr(::new(S.Context) AArch64VectorPcsAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_IntelOclBicc: D->addAttr(::new (S.Context) IntelOclBiccAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_PreserveMost: D->addAttr(::new (S.Context) PreserveMostAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; case ParsedAttr::AT_PreserveAll: D->addAttr(::new (S.Context) PreserveAllAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); return; default: llvm_unreachable("unexpected attribute kind"); } } static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; std::vector DiagnosticIdentifiers; for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { StringRef RuleName; if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr)) return; // FIXME: Warn if the rule name is unknown. This is tricky because only // clang-tidy knows about available rules. DiagnosticIdentifiers.push_back(RuleName); } D->addAttr(::new (S.Context) SuppressAttr( AL.getRange(), S.Context, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex())); } bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC, const FunctionDecl *FD) { if (Attrs.isInvalid()) return true; if (Attrs.hasProcessingCache()) { CC = (CallingConv) Attrs.getProcessingCache(); return false; } unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0; if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) { Attrs.setInvalid(); return true; } // TODO: diagnose uses of these conventions on the wrong target. switch (Attrs.getKind()) { case ParsedAttr::AT_CDecl: CC = CC_C; break; case ParsedAttr::AT_FastCall: CC = CC_X86FastCall; break; case ParsedAttr::AT_StdCall: CC = CC_X86StdCall; break; case ParsedAttr::AT_ThisCall: CC = CC_X86ThisCall; break; case ParsedAttr::AT_Pascal: CC = CC_X86Pascal; break; case ParsedAttr::AT_SwiftCall: CC = CC_Swift; break; case ParsedAttr::AT_VectorCall: CC = CC_X86VectorCall; break; case ParsedAttr::AT_AArch64VectorPcs: CC = CC_AArch64VectorCall; break; case ParsedAttr::AT_RegCall: CC = CC_X86RegCall; break; case ParsedAttr::AT_MSABI: CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : CC_Win64; break; case ParsedAttr::AT_SysVABI: CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : CC_C; break; case ParsedAttr::AT_Pcs: { StringRef StrRef; if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { Attrs.setInvalid(); return true; } if (StrRef == "aapcs") { CC = CC_AAPCS; break; } else if (StrRef == "aapcs-vfp") { CC = CC_AAPCS_VFP; break; } Attrs.setInvalid(); Diag(Attrs.getLoc(), diag::err_invalid_pcs); return true; } case ParsedAttr::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; case ParsedAttr::AT_PreserveMost: CC = CC_PreserveMost; break; case ParsedAttr::AT_PreserveAll: CC = CC_PreserveAll; break; default: llvm_unreachable("unexpected attribute kind"); } const TargetInfo &TI = Context.getTargetInfo(); TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); if (A != TargetInfo::CCCR_OK) { if (A == TargetInfo::CCCR_Warning) Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs; // This convention is not valid for the target. Use the default function or // method calling convention. bool IsCXXMethod = false, IsVariadic = false; if (FD) { IsCXXMethod = FD->isCXXInstanceMember(); IsVariadic = FD->isVariadic(); } CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); } Attrs.setProcessingCache((unsigned) CC); return false; } /// Pointer-like types in the default address space. static bool isValidSwiftContextType(QualType Ty) { if (!Ty->hasPointerRepresentation()) return Ty->isDependentType(); return Ty->getPointeeType().getAddressSpace() == LangAS::Default; } /// Pointers and references in the default address space. static bool isValidSwiftIndirectResultType(QualType Ty) { if (const auto *PtrType = Ty->getAs()) { Ty = PtrType->getPointeeType(); } else if (const auto *RefType = Ty->getAs()) { Ty = RefType->getPointeeType(); } else { return Ty->isDependentType(); } return Ty.getAddressSpace() == LangAS::Default; } /// Pointers and references to pointers in the default address space. static bool isValidSwiftErrorResultType(QualType Ty) { if (const auto *PtrType = Ty->getAs()) { Ty = PtrType->getPointeeType(); } else if (const auto *RefType = Ty->getAs()) { Ty = RefType->getPointeeType(); } else { return Ty->isDependentType(); } if (!Ty.getQualifiers().empty()) return false; return isValidSwiftContextType(Ty); } static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs, ParameterABI Abi) { S.AddParameterABIAttr(Attrs.getRange(), D, Abi, Attrs.getAttributeSpellingListIndex()); } void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, unsigned spellingIndex) { QualType type = cast(D)->getType(); if (auto existingAttr = D->getAttr()) { if (existingAttr->getABI() != abi) { Diag(range.getBegin(), diag::err_attributes_are_not_compatible) << getParameterABISpelling(abi) << existingAttr; Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); return; } } switch (abi) { case ParameterABI::Ordinary: llvm_unreachable("explicit attribute for ordinary parameter ABI?"); case ParameterABI::SwiftContext: if (!isValidSwiftContextType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; } D->addAttr(::new (Context) SwiftContextAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftErrorResult: if (!isValidSwiftErrorResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; } D->addAttr(::new (Context) SwiftErrorResultAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftIndirectResult: if (!isValidSwiftIndirectResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer*/ 0 << type; } D->addAttr(::new (Context) SwiftIndirectResultAttr(range, Context, spellingIndex)); return; } llvm_unreachable("bad parameter ABI attribute"); } /// Checks a regparm attribute, returning true if it is ill-formed and /// otherwise setting numParams to the appropriate value. bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) { if (AL.isInvalid()) return true; if (!checkAttributeNumArgs(*this, AL, 1)) { AL.setInvalid(); return true; } uint32_t NP; Expr *NumParamsExpr = AL.getArgAsExpr(0); if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) { AL.setInvalid(); return true; } if (Context.getTargetInfo().getRegParmMax() == 0) { Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) << NumParamsExpr->getSourceRange(); AL.setInvalid(); return true; } numParams = NP; if (numParams > Context.getTargetInfo().getRegParmMax()) { Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); AL.setInvalid(); return true; } return false; } // Checks whether an argument of launch_bounds attribute is // acceptable, performs implicit conversion to Rvalue, and returns // non-nullptr Expr result on success. Otherwise, it returns nullptr // and may output an error. static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, const CUDALaunchBoundsAttr &AL, const unsigned Idx) { if (S.DiagnoseUnexpandedParameterPack(E)) return nullptr; // Accept template arguments for now as they depend on something else. // We'll get to check them when they eventually get instantiated. if (E->isValueDependent()) return E; llvm::APSInt I(64); if (!E->isIntegerConstantExpr(I, S.Context)) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); return nullptr; } // Make sure we can fit it in 32 bits. if (!I.isIntN(32)) { S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 1; return nullptr; } if (I < 0) S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) << &AL << Idx << E->getSourceRange(); // We may need to perform implicit conversion of the argument. InitializedEntity Entity = InitializedEntity::InitializeParameter( S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); assert(!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."); return ValArg.getAs(); } void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex) { CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex); MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); if (MaxThreads == nullptr) return; if (MinBlocks) { MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); if (MinBlocks == nullptr) return; } D->addAttr(::new (Context) CUDALaunchBoundsAttr( AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); } static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1) || !checkAttributeAtMostNumArgs(S, AL, 2)) return; S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0), AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr, AL.getAttributeSpellingListIndex()); } static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier; return; } ParamIdx ArgumentIdx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1), ArgumentIdx)) return; ParamIdx TypeTagIdx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2), TypeTagIdx)) return; bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag"; if (IsPointer) { // Ensure that buffer has a pointer type. unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex(); if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) || !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType()) S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0; } D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr( AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex())); } static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL << 1 << AANT_ArgumentIdentifier; return; } if (!checkAttributeNumArgs(S, AL, 1)) return; if (!isa(D)) { S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) << AL << ExpectedVariable; return; } IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident; TypeSourceInfo *MatchingCTypeLoc = nullptr; S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); assert(MatchingCTypeLoc && "no type source info for attribute argument"); D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(), AL.getMustBeNull(), AL.getAttributeSpellingListIndex())); } static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ParamIdx ArgCount; if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0), ArgCount, true /* CanIndexImplicitThis */)) return; // ArgCount isn't a parameter index [0;n), it's a count [1;n] D->addAttr(::new (S.Context) XRayLogArgsAttr( AL.getRange(), S.Context, ArgCount.getSourceIndex(), AL.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// // Checker-specific attribute handlers. //===----------------------------------------------------------------------===// static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) { return QT->isDependentType() || QT->isObjCRetainableType(); } static bool isValidSubjectOfNSAttribute(QualType QT) { return QT->isDependentType() || QT->isObjCObjectPointerType() || QT->isObjCNSObjectType(); } static bool isValidSubjectOfCFAttribute(QualType QT) { return QT->isDependentType() || QT->isPointerType() || isValidSubjectOfNSAttribute(QT); } static bool isValidSubjectOfOSAttribute(QualType QT) { if (QT->isDependentType()) return true; QualType PT = QT->getPointeeType(); return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr; } void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, RetainOwnershipKind K, bool IsTemplateInstantiation) { ValueDecl *VD = cast(D); switch (K) { case RetainOwnershipKind::OS: handleSimpleAttributeOrDiagnose( *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()), diag::warn_ns_attribute_wrong_parameter_type, /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1); return; case RetainOwnershipKind::NS: handleSimpleAttributeOrDiagnose( *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()), // These attributes are normally just advisory, but in ARC, ns_consumed // is significant. Allow non-dependent code to contain inappropriate // attributes even in ARC, but require template instantiations to be // set up correctly. ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount) ? diag::err_ns_attribute_wrong_parameter_type : diag::warn_ns_attribute_wrong_parameter_type), /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0); return; case RetainOwnershipKind::CF: handleSimpleAttributeOrDiagnose( *this, VD, SR, SpellingIndex, isValidSubjectOfCFAttribute(VD->getType()), diag::warn_ns_attribute_wrong_parameter_type, /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1); return; } } static Sema::RetainOwnershipKind parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) { switch (AL.getKind()) { case ParsedAttr::AT_CFConsumed: case ParsedAttr::AT_CFReturnsRetained: case ParsedAttr::AT_CFReturnsNotRetained: return Sema::RetainOwnershipKind::CF; case ParsedAttr::AT_OSConsumesThis: case ParsedAttr::AT_OSConsumed: case ParsedAttr::AT_OSReturnsRetained: case ParsedAttr::AT_OSReturnsNotRetained: case ParsedAttr::AT_OSReturnsRetainedOnZero: case ParsedAttr::AT_OSReturnsRetainedOnNonZero: return Sema::RetainOwnershipKind::OS; case ParsedAttr::AT_NSConsumesSelf: case ParsedAttr::AT_NSConsumed: case ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NSReturnsNotRetained: case ParsedAttr::AT_NSReturnsAutoreleased: return Sema::RetainOwnershipKind::NS; default: llvm_unreachable("Wrong argument supplied"); } } bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) { if (isValidSubjectOfNSReturnsRetainedAttribute(QT)) return false; Diag(Loc, diag::warn_ns_attribute_wrong_return_type) << "'ns_returns_retained'" << 0 << 0; return true; } /// \return whether the parameter is a pointer to OSObject pointer. static bool isValidOSObjectOutParameter(const Decl *D) { const auto *PVD = dyn_cast(D); if (!PVD) return false; QualType QT = PVD->getType(); QualType PT = QT->getPointeeType(); return !PT.isNull() && isValidSubjectOfOSAttribute(PT); } static void handleXReturnsXRetainedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { QualType ReturnType; Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL); if (const auto *MD = dyn_cast(D)) { ReturnType = MD->getReturnType(); } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) { return; // ignore: was handled as a type attribute } else if (const auto *PD = dyn_cast(D)) { ReturnType = PD->getType(); } else if (const auto *FD = dyn_cast(D)) { ReturnType = FD->getReturnType(); } else if (const auto *Param = dyn_cast(D)) { // Attributes on parameters are used for out-parameters, // passed as pointers-to-pointers. unsigned DiagID = K == Sema::RetainOwnershipKind::CF ? /*pointer-to-CF-pointer*/2 : /*pointer-to-OSObject-pointer*/3; ReturnType = Param->getType()->getPointeeType(); if (ReturnType.isNull()) { S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) << AL << DiagID << AL.getRange(); return; } } else if (AL.isUsedAsTypeAttr()) { return; } else { AttributeDeclKind ExpectedDeclKind; switch (AL.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NSReturnsAutoreleased: case ParsedAttr::AT_NSReturnsNotRetained: ExpectedDeclKind = ExpectedFunctionOrMethod; break; case ParsedAttr::AT_OSReturnsRetained: case ParsedAttr::AT_OSReturnsNotRetained: case ParsedAttr::AT_CFReturnsRetained: case ParsedAttr::AT_CFReturnsNotRetained: ExpectedDeclKind = ExpectedFunctionMethodOrParameter; break; } S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type) << AL.getRange() << AL << ExpectedDeclKind; return; } bool TypeOK; bool Cf; unsigned ParmDiagID = 2; // Pointer-to-CF-pointer switch (AL.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case ParsedAttr::AT_NSReturnsRetained: TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); Cf = false; break; case ParsedAttr::AT_NSReturnsAutoreleased: case ParsedAttr::AT_NSReturnsNotRetained: TypeOK = isValidSubjectOfNSAttribute(ReturnType); Cf = false; break; case ParsedAttr::AT_CFReturnsRetained: case ParsedAttr::AT_CFReturnsNotRetained: TypeOK = isValidSubjectOfCFAttribute(ReturnType); Cf = true; break; case ParsedAttr::AT_OSReturnsRetained: case ParsedAttr::AT_OSReturnsNotRetained: TypeOK = isValidSubjectOfOSAttribute(ReturnType); Cf = true; ParmDiagID = 3; // Pointer-to-OSObject-pointer break; } if (!TypeOK) { if (AL.isUsedAsTypeAttr()) return; if (isa(D)) { S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) << AL << ParmDiagID << AL.getRange(); } else { // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. enum : unsigned { Function, Method, Property } SubjectKind = Function; if (isa(D)) SubjectKind = Method; else if (isa(D)) SubjectKind = Property; S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) << AL << SubjectKind << Cf << AL.getRange(); } return; } switch (AL.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case ParsedAttr::AT_NSReturnsAutoreleased: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_CFReturnsNotRetained: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_NSReturnsNotRetained: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_CFReturnsRetained: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_NSReturnsRetained: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_OSReturnsRetained: handleSimpleAttribute(S, D, AL); return; case ParsedAttr::AT_OSReturnsNotRetained: handleSimpleAttribute(S, D, AL); return; }; } static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { const int EP_ObjCMethod = 1; const int EP_ObjCProperty = 2; SourceLocation loc = Attrs.getLoc(); QualType resultType; if (isa(D)) resultType = cast(D)->getReturnType(); else resultType = cast(D)->getType(); if (!resultType->isReferenceType() && (!resultType->isPointerType() || resultType->isObjCRetainableType())) { S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) << SourceRange(loc) << Attrs << (isa(D) ? EP_ObjCMethod : EP_ObjCProperty) << /*non-retainable pointer*/ 2; // Drop the attribute. return; } D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { const auto *Method = cast(D); const DeclContext *DC = Method->getDeclContext(); if (const auto *PDecl = dyn_cast_or_null(DC)) { S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs << 0; S.Diag(PDecl->getLocation(), diag::note_protocol_decl); return; } if (Method->getMethodFamily() == OMF_dealloc) { S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs << 1; return; } D->addAttr(::new (S.Context) ObjCRequiresSuperAttr( Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; if (!Parm) { S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; return; } // Typedefs only allow objc_bridge(id) and have some additional checking. if (const auto *TD = dyn_cast(D)) { if (!Parm->Ident->isStr("id")) { S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL; return; } // Only allow 'cv void *'. QualType T = TD->getUnderlyingType(); if (!T->isVoidPointerType()) { S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); return; } } D->addAttr(::new (S.Context) ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); } static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, const ParsedAttr &AL) { IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; if (!Parm) { S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; return; } D->addAttr(::new (S.Context) ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); } static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { IdentifierInfo *RelatedClass = AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr; if (!RelatedClass) { S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; return; } IdentifierInfo *ClassMethod = AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; IdentifierInfo *InstanceMethod = AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass, ClassMethod, InstanceMethod, AL.getAttributeSpellingListIndex())); } static void handleObjCDesignatedInitializer(Sema &S, Decl *D, const ParsedAttr &AL) { ObjCInterfaceDecl *IFace; if (auto *CatDecl = dyn_cast(D->getDeclContext())) IFace = CatDecl->getClassInterface(); else IFace = cast(D->getDeclContext()); if (!IFace) return; IFace->setHasDesignatedInitializers(); D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef MetaDataName; if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) return; D->addAttr(::new (S.Context) ObjCRuntimeNameAttr(AL.getRange(), S.Context, MetaDataName, AL.getAttributeSpellingListIndex())); } // When a user wants to use objc_boxable with a union or struct // but they don't have access to the declaration (legacy/third-party code) // then they can 'enable' this feature with a typedef: // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) { bool notify = false; auto *RD = dyn_cast(D); if (RD && RD->getDefinition()) { RD = RD->getDefinition(); notify = true; } if (RD) { ObjCBoxableAttr *BoxableAttr = ::new (S.Context) ObjCBoxableAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()); RD->addAttr(BoxableAttr); if (notify) { // we need to notify ASTReader/ASTWriter about // modification of existing declaration if (ASTMutationListener *L = S.getASTMutationListener()) L->AddedAttributeToRecord(BoxableAttr, RD); } } } static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (hasDeclarator(D)) return; S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type) << AL.getRange() << AL << ExpectedVariable; } static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { const auto *VD = cast(D); QualType QT = VD->getType(); if (!QT->isDependentType() && !QT->isObjCLifetimeType()) { S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) << QT; return; } Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime(); // If we have no lifetime yet, check the lifetime we're presumably // going to infer. if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType()) Lifetime = QT->getObjCARCImplicitLifetime(); switch (Lifetime) { case Qualifiers::OCL_None: assert(QT->isDependentType() && "didn't infer lifetime for non-dependent type?"); break; case Qualifiers::OCL_Weak: // meaningful case Qualifiers::OCL_Strong: // meaningful break; case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless) << (Lifetime == Qualifiers::OCL_Autoreleasing); break; } D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// // Microsoft specific attribute handlers. //===----------------------------------------------------------------------===// UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid) { if (const auto *UA = D->getAttr()) { if (UA->getGuid().equals_lower(Uuid)) return nullptr; Diag(UA->getLocation(), diag::err_mismatched_uuid); Diag(Range.getBegin(), diag::note_previous_uuid); D->dropAttr(); } return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex); } static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!S.LangOpts.CPlusPlus) { S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) << AL << AttributeLangSupport::C; return; } StringRef StrRef; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc)) return; // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') StrRef = StrRef.drop_front().drop_back(); // Validate GUID length. if (StrRef.size() != 36) { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } for (unsigned i = 0; i < 36; ++i) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (StrRef[i] != '-') { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } } else if (!isHexDigit(StrRef[i])) { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } } // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's // the only thing in the [] list, the [] too), and add an insertion of // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas // separating attributes nor of the [ and the ] are in the AST. // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" // on cfe-dev. if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated); UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(), StrRef); if (UA) D->addAttr(UA); } static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!S.LangOpts.CPlusPlus) { S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) << AL << AttributeLangSupport::C; return; } MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( D, AL.getRange(), /*BestCase=*/true, AL.getAttributeSpellingListIndex(), (MSInheritanceAttr::Spelling)AL.getSemanticSpelling()); if (IA) { D->addAttr(IA); S.Consumer.AssignInheritanceModel(cast(D)); } } static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) { const auto *VD = cast(D); if (!S.Context.getTargetInfo().isTLSSupported()) { S.Diag(AL.getLoc(), diag::err_thread_unsupported); return; } if (VD->getTSCSpec() != TSCS_unspecified) { S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable); return; } if (VD->hasLocalStorage()) { S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; return; } D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Tags; for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { StringRef Tag; if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) return; Tags.push_back(Tag); } if (const auto *NS = dyn_cast(D)) { if (!NS->isInline()) { S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; return; } if (NS->isAnonymousNamespace()) { S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; return; } if (AL.getNumArgs() == 0) Tags.push_back(NS->getName()); } else if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; // Store tags sorted and without duplicates. llvm::sort(Tags); Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); D->addAttr(::new (S.Context) AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(), AL.getAttributeSpellingListIndex())); } static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Check the attribute arguments. if (AL.getNumArgs() > 1) { S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; return; } StringRef Str; SourceLocation ArgLoc; if (AL.getNumArgs() == 0) Str = ""; else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) return; ARMInterruptAttr::InterruptType Kind; if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str << ArgLoc; return; } unsigned Index = AL.getAttributeSpellingListIndex(); D->addAttr(::new (S.Context) ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index)); } static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { + // MSP430 'interrupt' attribute is applied to + // a function with no parameters and void return type. + if (!isFunctionOrMethod(D)) { + S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) + << "'interrupt'" << ExpectedFunctionOrMethod; + return; + } + + if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { + S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute) + << 0; + return; + } + + if (!getFunctionOrMethodResultType(D)->isVoidType()) { + S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute) + << 1; + return; + } + + // The attribute takes one integer argument. if (!checkAttributeNumArgs(S, AL, 1)) return; if (!AL.isArgExpr(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIntegerConstant; return; } - // FIXME: Check for decl - it should be void ()(void). - Expr *NumParamsExpr = static_cast(AL.getArgAsExpr(0)); llvm::APSInt NumParams(32); if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL << AANT_ArgumentIntegerConstant << NumParamsExpr->getSourceRange(); return; } - + // The argument should be in range 0..63. unsigned Num = NumParams.getLimitedValue(255); - if ((Num & 1) || Num > 30) { + if (Num > 63) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) << AL << (int)NumParams.getSExtValue() << NumParamsExpr->getSourceRange(); return; } D->addAttr(::new (S.Context) MSP430InterruptAttr(AL.getLoc(), S.Context, Num, AL.getAttributeSpellingListIndex())); D->addAttr(UsedAttr::CreateImplicit(S.Context)); } static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Only one optional argument permitted. if (AL.getNumArgs() > 1) { S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; return; } StringRef Str; SourceLocation ArgLoc; if (AL.getNumArgs() == 0) Str = ""; else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) return; // Semantic checks for a function with the 'interrupt' attribute for MIPS: // a) Must be a function. // b) Must have no parameters. // c) Must have the 'void' return type. // d) Cannot have the 'mips16' attribute, as that instruction set // lacks the 'eret' instruction. // e) The attribute itself must either have no argument or one of the // valid interrupt types, see [MipsInterruptDocs]. if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'interrupt'" << ExpectedFunctionOrMethod; return; } if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) << 0; return; } if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) << 1; return; } if (checkAttrMutualExclusion(S, D, AL)) return; MipsInterruptAttr::InterruptType Kind; if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << "'" + std::string(Str) + "'"; return; } D->addAttr(::new (S.Context) MipsInterruptAttr( AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex())); } static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Semantic checks for a function with the 'interrupt' attribute. // a) Must be a function. // b) Must have the 'void' return type. // c) Must take 1 or 2 arguments. // d) The 1st argument must be a pointer. // e) The 2nd argument (if any) must be an unsigned integer. if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || CXXMethodDecl::isStaticOverloadedOperator( cast(D)->getDeclName().getCXXOverloadedOperator())) { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunctionWithProtoType; return; } // Interrupt handler must have void return type. if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 0; return; } // Interrupt handler must have 1 or 2 parameters. unsigned NumParams = getFunctionOrMethodNumParams(D); if (NumParams < 1 || NumParams > 2) { S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 1; return; } // The first argument must be a pointer. if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 2; return; } // The second argument, if present, must be an unsigned integer. unsigned TypeSize = S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 ? 64 : 32; if (NumParams == 2 && (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); return; } D->addAttr(::new (S.Context) AnyX86InterruptAttr( AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex())); D->addAttr(UsedAttr::CreateImplicit(S.Context)); } static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'interrupt'" << ExpectedFunction; return; } if (!checkAttributeNumArgs(S, AL, 0)) return; handleSimpleAttribute(S, D, AL); } static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'signal'" << ExpectedFunction; return; } if (!checkAttributeNumArgs(S, AL, 0)) return; handleSimpleAttribute(S, D, AL); } static void handleRISCVInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Warn about repeated attributes. if (const auto *A = D->getAttr()) { S.Diag(AL.getRange().getBegin(), diag::warn_riscv_repeated_interrupt_attribute); S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute); return; } // Check the attribute argument. Argument is optional. if (!checkAttributeAtMostNumArgs(S, AL, 1)) return; StringRef Str; SourceLocation ArgLoc; // 'machine'is the default interrupt mode. if (AL.getNumArgs() == 0) Str = "machine"; else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) return; // Semantic checks for a function with the 'interrupt' attribute: // - Must be a function. // - Must have no parameters. // - Must have the 'void' return type. // - The attribute itself must either have no argument or one of the // valid interrupt types, see [RISCVInterruptDocs]. if (D->getFunctionType() == nullptr) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'interrupt'" << ExpectedFunction; return; } if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 0; return; } if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 1; return; } RISCVInterruptAttr::InterruptType Kind; if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str << ArgLoc; return; } D->addAttr(::new (S.Context) RISCVInterruptAttr( AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex())); } static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Dispatch the interrupt attribute based on the current target. switch (S.Context.getTargetInfo().getTriple().getArch()) { case llvm::Triple::msp430: handleMSP430InterruptAttr(S, D, AL); break; case llvm::Triple::mipsel: case llvm::Triple::mips: handleMipsInterruptAttr(S, D, AL); break; case llvm::Triple::x86: case llvm::Triple::x86_64: handleAnyX86InterruptAttr(S, D, AL); break; case llvm::Triple::avr: handleAVRInterruptAttr(S, D, AL); break; case llvm::Triple::riscv32: case llvm::Triple::riscv64: handleRISCVInterruptAttr(S, D, AL); break; default: handleARMInterruptAttr(S, D, AL); break; } } static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t Min = 0; Expr *MinExpr = AL.getArgAsExpr(0); if (!checkUInt32Argument(S, AL, MinExpr, Min)) return; uint32_t Max = 0; Expr *MaxExpr = AL.getArgAsExpr(1); if (!checkUInt32Argument(S, AL, MaxExpr, Max)) return; if (Min == 0 && Max != 0) { S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0; return; } if (Min > Max) { S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1; return; } D->addAttr(::new (S.Context) AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max, AL.getAttributeSpellingListIndex())); } static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t Min = 0; Expr *MinExpr = AL.getArgAsExpr(0); if (!checkUInt32Argument(S, AL, MinExpr, Min)) return; uint32_t Max = 0; if (AL.getNumArgs() == 2) { Expr *MaxExpr = AL.getArgAsExpr(1); if (!checkUInt32Argument(S, AL, MaxExpr, Max)) return; } if (Min == 0 && Max != 0) { S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0; return; } if (Max != 0 && Min > Max) { S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1; return; } D->addAttr(::new (S.Context) AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max, AL.getAttributeSpellingListIndex())); } static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t NumSGPR = 0; Expr *NumSGPRExpr = AL.getArgAsExpr(0); if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) return; D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR, AL.getAttributeSpellingListIndex())); } static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t NumVGPR = 0; Expr *NumVGPRExpr = AL.getArgAsExpr(0); if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) return; D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR, AL.getAttributeSpellingListIndex())); } static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // If we try to apply it to a function pointer, don't warn, but don't // do anything, either. It doesn't matter anyway, because there's nothing // special about calling a force_align_arg_pointer function. const auto *VD = dyn_cast(D); if (VD && VD->getType()->isFunctionPointerType()) return; // Also don't warn on function pointer typedefs. const auto *TD = dyn_cast(D); if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || TD->getUnderlyingType()->isFunctionType())) return; // Attribute can only be applied to function types. if (!isa(D)) { S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL << ExpectedFunction; return; } D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) { uint32_t Version; Expr *VersionExpr = static_cast(AL.getArgAsExpr(0)); if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version)) return; // TODO: Investigate what happens with the next major version of MSVC. if (Version != LangOptions::MSVC2015 / 100) { S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) << AL << Version << VersionExpr->getSourceRange(); return; } // The attribute expects a "major" version number like 19, but new versions of // MSVC have moved to updating the "minor", or less significant numbers, so we // have to multiply by 100 now. Version *= 100; D->addAttr(::new (S.Context) LayoutVersionAttr(AL.getRange(), S.Context, Version, AL.getAttributeSpellingListIndex())); } DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (D->hasAttr()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; return nullptr; } if (D->hasAttr()) return nullptr; return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); } DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (DLLImportAttr *Import = D->getAttr()) { Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; D->dropAttr(); } if (D->hasAttr()) return nullptr; return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); } static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) { if (isa(D) && S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A; return; } if (const auto *FD = dyn_cast(D)) { if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport && !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { // MinGW doesn't allow dllimport on inline functions. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) << A; return; } } if (const auto *MD = dyn_cast(D)) { if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && MD->getParent()->isLambda()) { S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A; return; } } unsigned Index = A.getAttributeSpellingListIndex(); Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); if (NewAttr) D->addAttr(NewAttr); } MSInheritanceAttr * Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling) { if (MSInheritanceAttr *IA = D->getAttr()) { if (IA->getSemanticSpelling() == SemanticSpelling) return nullptr; Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) << 1 /*previous declaration*/; Diag(Range.getBegin(), diag::note_previous_ms_inheritance); D->dropAttr(); } auto *RD = cast(D); if (RD->hasDefinition()) { if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, SemanticSpelling)) { return nullptr; } } else { if (isa(RD)) { Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) << 1 /*partial specialization*/; return nullptr; } if (RD->getDescribedClassTemplate()) { Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) << 0 /*primary template*/; return nullptr; } } return ::new (Context) MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); } static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // The capability attributes take a single string parameter for the name of // the capability they represent. The lockable attribute does not take any // parameters. However, semantically, both attributes represent the same // concept, and so they use the same semantic attribute. Eventually, the // lockable attribute will be removed. // // For backward compatibility, any capability which has no specified string // literal will be considered a "mutex." StringRef N("mutex"); SourceLocation LiteralLoc; if (AL.getKind() == ParsedAttr::AT_Capability && !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc)) return; // Currently, there are only two names allowed for a capability: role and // mutex (case insensitive). Diagnose other capability names. if (!N.equals_lower("mutex") && !N.equals_lower("role")) S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N, AL.getAttributeSpellingListIndex())); } static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context, Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleAcquireCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(), S.Context, Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { SmallVector Args; if (!checkTryLockFunAttrCommon(S, D, AL, Args)) return; D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleReleaseCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Check that all arguments are lockable objects. SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true); D->addAttr(::new (S.Context) ReleaseCapabilityAttr( AL.getRange(), S.Context, Args.data(), Args.size(), AL.getAttributeSpellingListIndex())); } static void handleRequiresCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; // check that all arguments are lockable objects SmallVector Args; checkAttrArgsAreCapabilityObjs(S, D, AL, Args); if (Args.empty()) return; RequiresCapabilityAttr *RCA = ::new (S.Context) RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(), Args.size(), AL.getAttributeSpellingListIndex()); D->addAttr(RCA); } static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (const auto *NSD = dyn_cast(D)) { if (NSD->isAnonymousNamespace()) { S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace); // Do not want to attach the attribute to the namespace because that will // cause confusing diagnostic reports for uses of declarations within the // namespace. return; } } // Handle the cases where the attribute has a text message. StringRef Str, Replacement; if (AL.isArgExpr(0) && AL.getArgAsExpr(0) && !S.checkStringLiteralArgumentAttr(AL, 0, Str)) return; // Only support a single optional message for Declspec and CXX11. if (AL.isDeclspecAttribute() || AL.isCXX11Attribute()) checkAttributeAtMostNumArgs(S, AL, 1); else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) && !S.checkStringLiteralArgumentAttr(AL, 1, Replacement)) return; if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope()) S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL; D->addAttr(::new (S.Context) DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement, AL.getAttributeSpellingListIndex())); } static bool isGlobalVar(const Decl *D) { if (const auto *S = dyn_cast(D)) return S->hasGlobalStorage(); return false; } static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; std::vector Sanitizers; for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { StringRef SanitizerName; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc)) return; if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; else if (isGlobalVar(D) && SanitizerName != "address") S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << AL << ExpectedFunctionOrMethod; Sanitizers.push_back(SanitizerName); } D->addAttr(::new (S.Context) NoSanitizeAttr( AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), AL.getAttributeSpellingListIndex())); } static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef AttrName = AL.getName()->getName(); normalizeName(AttrName); StringRef SanitizerName = llvm::StringSwitch(AttrName) .Case("no_address_safety_analysis", "address") .Case("no_sanitize_address", "address") .Case("no_sanitize_thread", "thread") .Case("no_sanitize_memory", "memory"); if (isGlobalVar(D) && SanitizerName != "address") S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << AL << ExpectedFunction; D->addAttr(::new (S.Context) NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1, AL.getAttributeSpellingListIndex())); } static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL)) D->addAttr(Internal); } static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (S.LangOpts.OpenCLVersion != 200) S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) << AL << "2.0" << 0; else S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL << "2.0"; } /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the correct /// number of arguments were passed, etc. static bool handleCommonAttributeFeatures(Sema &S, Decl *D, const ParsedAttr &AL) { // Several attributes carry different semantics than the parsing requires, so // those are opted out of the common argument checks. // // We also bail on unknown and ignored attributes because those are handled // as part of the target-specific handling logic. if (AL.getKind() == ParsedAttr::UnknownAttribute) return false; // Check whether the attribute requires specific language extensions to be // enabled. if (!AL.diagnoseLangOpts(S)) return true; // Check whether the attribute appertains to the given subject. if (!AL.diagnoseAppertainsTo(S, D)) return true; if (AL.hasCustomParsing()) return false; if (AL.getMinArgs() == AL.getMaxArgs()) { // If there are no optional arguments, then checking for the argument count // is trivial. if (!checkAttributeNumArgs(S, AL, AL.getMinArgs())) return true; } else { // There are optional arguments, so checking is slightly more involved. if (AL.getMinArgs() && !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs())) return true; else if (!AL.hasVariadicArg() && AL.getMaxArgs() && !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs())) return true; } if (S.CheckAttrTarget(AL)) return true; return false; } static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (D->isInvalidDecl()) return; // Check if there is only one access qualifier. if (D->hasAttr()) { if (D->getAttr()->getSemanticSpelling() == AL.getSemanticSpelling()) { S.Diag(AL.getLoc(), diag::warn_duplicate_declspec) << AL.getName()->getName() << AL.getRange(); } else { S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers) << D->getSourceRange(); D->setInvalidDecl(true); return; } } // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an // image object can be read and written. // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe // object. Using the read_write (or __read_write) qualifier with the pipe // qualifier is a compilation error. if (const auto *PDecl = dyn_cast(D)) { const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); if (AL.getName()->getName().find("read_write") != StringRef::npos) { if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write) << AL << PDecl->getType() << DeclTy->isImageType(); D->setInvalidDecl(true); return; } } } D->addAttr(::new (S.Context) OpenCLAccessAttr( AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) { if (!cast(D)->hasGlobalStorage()) { S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var) << (A.getKind() == ParsedAttr::AT_AlwaysDestroy); return; } if (A.getKind() == ParsedAttr::AT_AlwaysDestroy) handleSimpleAttributeWithExclusions(S, D, A); else handleSimpleAttributeWithExclusions(S, D, A); } static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { assert(cast(D)->getStorageDuration() == SD_Automatic && "uninitialized is only valid on automatic duration variables"); unsigned Index = AL.getAttributeSpellingListIndex(); D->addAttr(::new (S.Context) UninitializedAttr(AL.getLoc(), S.Context, Index)); } static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD, bool DiagnoseFailure) { QualType Ty = VD->getType(); if (!Ty->isObjCRetainableType()) { if (DiagnoseFailure) { S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) << 0; } return false; } Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime(); // Sema::inferObjCARCLifetime must run after processing decl attributes // (because __block lowers to an attribute), so if the lifetime hasn't been // explicitly specified, infer it locally now. if (LifetimeQual == Qualifiers::OCL_None) LifetimeQual = Ty->getObjCARCImplicitLifetime(); // The attributes only really makes sense for __strong variables; ignore any // attempts to annotate a parameter with any other lifetime qualifier. if (LifetimeQual != Qualifiers::OCL_Strong) { if (DiagnoseFailure) { S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) << 1; } return false; } // Tampering with the type of a VarDecl here is a bit of a hack, but we need // to ensure that the variable is 'const' so that we can error on // modification, which can otherwise over-release. VD->setType(Ty.withConst()); VD->setARCPseudoStrong(true); return true; } static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (auto *VD = dyn_cast(D)) { assert(!isa(VD) && "should be diagnosed automatically"); if (!VD->hasLocalStorage()) { S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) << 0; return; } if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true)) return; handleSimpleAttribute(S, D, AL); return; } // If D is a function-like declaration (method, block, or function), then we // make every parameter psuedo-strong. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) { auto *PVD = const_cast(getFunctionOrMethodParam(D, I)); QualType Ty = PVD->getType(); // If a user wrote a parameter with __strong explicitly, then assume they // want "real" strong semantics for that parameter. This works because if // the parameter was written with __strong, then the strong qualifier will // be non-local. if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) continue; tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false); } handleSimpleAttribute(S, D, AL); } //===----------------------------------------------------------------------===// // Top Level Sema Entry Points //===----------------------------------------------------------------------===// /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if /// the attribute applies to decls. If the attribute is a type attribute, just /// silently ignore it if a GNU attribute. static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL, bool IncludeCXX11Attributes) { if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) return; // Ignore C++11 attributes on declarator chunks: they appertain to the type // instead. if (AL.isCXX11Attribute() && !IncludeCXX11Attributes) return; // Unknown attributes are automatically warned on. Target-specific attributes // which do not apply to the current target architecture are treated as // though they were unknown attributes. if (AL.getKind() == ParsedAttr::UnknownAttribute || !AL.existsInTarget(S.Context.getTargetInfo())) { S.Diag(AL.getLoc(), AL.isDeclspecAttribute() ? (unsigned)diag::warn_unhandled_ms_attribute_ignored : (unsigned)diag::warn_unknown_attribute_ignored) << AL; return; } if (handleCommonAttributeFeatures(S, D, AL)) return; switch (AL.getKind()) { default: if (!AL.isStmtAttr()) { // Type attributes are handled elsewhere; silently move on. assert(AL.isTypeAttr() && "Non-type attribute not handled"); break; } S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl) << AL << D->getLocation(); break; case ParsedAttr::AT_Interrupt: handleInterruptAttr(S, D, AL); break; case ParsedAttr::AT_X86ForceAlignArgPointer: handleX86ForceAlignArgPointerAttr(S, D, AL); break; case ParsedAttr::AT_DLLExport: case ParsedAttr::AT_DLLImport: handleDLLAttr(S, D, AL); break; case ParsedAttr::AT_Mips16: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_NoMips16: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_MicroMips: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_NoMicroMips: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_MipsLongCall: handleSimpleAttributeWithExclusions( S, D, AL); break; case ParsedAttr::AT_MipsShortCall: handleSimpleAttributeWithExclusions( S, D, AL); break; case ParsedAttr::AT_AMDGPUFlatWorkGroupSize: handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL); break; case ParsedAttr::AT_AMDGPUWavesPerEU: handleAMDGPUWavesPerEUAttr(S, D, AL); break; case ParsedAttr::AT_AMDGPUNumSGPR: handleAMDGPUNumSGPRAttr(S, D, AL); break; case ParsedAttr::AT_AMDGPUNumVGPR: handleAMDGPUNumVGPRAttr(S, D, AL); break; case ParsedAttr::AT_AVRSignal: handleAVRSignalAttr(S, D, AL); break; case ParsedAttr::AT_IBAction: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_IBOutlet: handleIBOutlet(S, D, AL); break; case ParsedAttr::AT_IBOutletCollection: handleIBOutletCollection(S, D, AL); break; case ParsedAttr::AT_IFunc: handleIFuncAttr(S, D, AL); break; case ParsedAttr::AT_Alias: handleAliasAttr(S, D, AL); break; case ParsedAttr::AT_Aligned: handleAlignedAttr(S, D, AL); break; case ParsedAttr::AT_AlignValue: handleAlignValueAttr(S, D, AL); break; case ParsedAttr::AT_AllocSize: handleAllocSizeAttr(S, D, AL); break; case ParsedAttr::AT_AlwaysInline: handleAlwaysInlineAttr(S, D, AL); break; case ParsedAttr::AT_Artificial: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_AnalyzerNoReturn: handleAnalyzerNoReturnAttr(S, D, AL); break; case ParsedAttr::AT_TLSModel: handleTLSModelAttr(S, D, AL); break; case ParsedAttr::AT_Annotate: handleAnnotateAttr(S, D, AL); break; case ParsedAttr::AT_Availability: handleAvailabilityAttr(S, D, AL); break; case ParsedAttr::AT_CarriesDependency: handleDependencyAttr(S, scope, D, AL); break; case ParsedAttr::AT_CPUDispatch: case ParsedAttr::AT_CPUSpecific: handleCPUSpecificAttr(S, D, AL); break; case ParsedAttr::AT_Common: handleCommonAttr(S, D, AL); break; case ParsedAttr::AT_CUDAConstant: handleConstantAttr(S, D, AL); break; case ParsedAttr::AT_PassObjectSize: handlePassObjectSizeAttr(S, D, AL); break; case ParsedAttr::AT_Constructor: handleConstructorAttr(S, D, AL); break; case ParsedAttr::AT_CXX11NoReturn: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Deprecated: handleDeprecatedAttr(S, D, AL); break; case ParsedAttr::AT_Destructor: handleDestructorAttr(S, D, AL); break; case ParsedAttr::AT_EnableIf: handleEnableIfAttr(S, D, AL); break; case ParsedAttr::AT_DiagnoseIf: handleDiagnoseIfAttr(S, D, AL); break; case ParsedAttr::AT_ExtVectorType: handleExtVectorTypeAttr(S, D, AL); break; case ParsedAttr::AT_ExternalSourceSymbol: handleExternalSourceSymbolAttr(S, D, AL); break; case ParsedAttr::AT_MinSize: handleMinSizeAttr(S, D, AL); break; case ParsedAttr::AT_OptimizeNone: handleOptimizeNoneAttr(S, D, AL); break; case ParsedAttr::AT_FlagEnum: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_EnumExtensibility: handleEnumExtensibilityAttr(S, D, AL); break; case ParsedAttr::AT_Flatten: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Format: handleFormatAttr(S, D, AL); break; case ParsedAttr::AT_FormatArg: handleFormatArgAttr(S, D, AL); break; case ParsedAttr::AT_CUDAGlobal: handleGlobalAttr(S, D, AL); break; case ParsedAttr::AT_CUDADevice: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_CUDAHost: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_GNUInline: handleGNUInlineAttr(S, D, AL); break; case ParsedAttr::AT_CUDALaunchBounds: handleLaunchBoundsAttr(S, D, AL); break; case ParsedAttr::AT_Restrict: handleRestrictAttr(S, D, AL); break; case ParsedAttr::AT_LifetimeBound: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_MayAlias: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Mode: handleModeAttr(S, D, AL); break; case ParsedAttr::AT_NoAlias: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoCommon: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoSplitStack: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NonNull: if (auto *PVD = dyn_cast(D)) handleNonNullAttrParameter(S, PVD, AL); else handleNonNullAttr(S, D, AL); break; case ParsedAttr::AT_ReturnsNonNull: handleReturnsNonNullAttr(S, D, AL); break; case ParsedAttr::AT_NoEscape: handleNoEscapeAttr(S, D, AL); break; case ParsedAttr::AT_AssumeAligned: handleAssumeAlignedAttr(S, D, AL); break; case ParsedAttr::AT_AllocAlign: handleAllocAlignAttr(S, D, AL); break; case ParsedAttr::AT_Overloadable: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Ownership: handleOwnershipAttr(S, D, AL); break; case ParsedAttr::AT_Cold: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_Hot: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_Naked: handleNakedAttr(S, D, AL); break; case ParsedAttr::AT_NoReturn: handleNoReturnAttr(S, D, AL); break; case ParsedAttr::AT_AnyX86NoCfCheck: handleNoCfCheckAttr(S, D, AL); break; case ParsedAttr::AT_NoThrow: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_CUDAShared: handleSharedAttr(S, D, AL); break; case ParsedAttr::AT_VecReturn: handleVecReturnAttr(S, D, AL); break; case ParsedAttr::AT_ObjCOwnership: handleObjCOwnershipAttr(S, D, AL); break; case ParsedAttr::AT_ObjCPreciseLifetime: handleObjCPreciseLifetimeAttr(S, D, AL); break; case ParsedAttr::AT_ObjCReturnsInnerPointer: handleObjCReturnsInnerPointerAttr(S, D, AL); break; case ParsedAttr::AT_ObjCRequiresSuper: handleObjCRequiresSuperAttr(S, D, AL); break; case ParsedAttr::AT_ObjCBridge: handleObjCBridgeAttr(S, D, AL); break; case ParsedAttr::AT_ObjCBridgeMutable: handleObjCBridgeMutableAttr(S, D, AL); break; case ParsedAttr::AT_ObjCBridgeRelated: handleObjCBridgeRelatedAttr(S, D, AL); break; case ParsedAttr::AT_ObjCDesignatedInitializer: handleObjCDesignatedInitializer(S, D, AL); break; case ParsedAttr::AT_ObjCRuntimeName: handleObjCRuntimeName(S, D, AL); break; case ParsedAttr::AT_ObjCRuntimeVisible: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ObjCBoxable: handleObjCBoxable(S, D, AL); break; case ParsedAttr::AT_CFAuditedTransfer: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_CFUnknownTransfer: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_CFConsumed: case ParsedAttr::AT_NSConsumed: case ParsedAttr::AT_OSConsumed: S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(), parsedAttrToRetainOwnershipKind(AL), /*IsTemplateInstantiation=*/false); break; case ParsedAttr::AT_NSConsumesSelf: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_OSConsumesThis: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_OSReturnsRetainedOnZero: handleSimpleAttributeOrDiagnose( S, D, AL, isValidOSObjectOutParameter(D), diag::warn_ns_attribute_wrong_parameter_type, /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange()); break; case ParsedAttr::AT_OSReturnsRetainedOnNonZero: handleSimpleAttributeOrDiagnose( S, D, AL, isValidOSObjectOutParameter(D), diag::warn_ns_attribute_wrong_parameter_type, /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange()); break; case ParsedAttr::AT_NSReturnsAutoreleased: case ParsedAttr::AT_NSReturnsNotRetained: case ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_CFReturnsNotRetained: case ParsedAttr::AT_CFReturnsRetained: case ParsedAttr::AT_OSReturnsNotRetained: case ParsedAttr::AT_OSReturnsRetained: handleXReturnsXRetainedAttr(S, D, AL); break; case ParsedAttr::AT_WorkGroupSizeHint: handleWorkGroupSize(S, D, AL); break; case ParsedAttr::AT_ReqdWorkGroupSize: handleWorkGroupSize(S, D, AL); break; case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize: handleSubGroupSize(S, D, AL); break; case ParsedAttr::AT_VecTypeHint: handleVecTypeHint(S, D, AL); break; case ParsedAttr::AT_RequireConstantInit: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_InitPriority: handleInitPriorityAttr(S, D, AL); break; case ParsedAttr::AT_Packed: handlePackedAttr(S, D, AL); break; case ParsedAttr::AT_Section: handleSectionAttr(S, D, AL); break; case ParsedAttr::AT_SpeculativeLoadHardening: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_CodeSeg: handleCodeSegAttr(S, D, AL); break; case ParsedAttr::AT_Target: handleTargetAttr(S, D, AL); break; case ParsedAttr::AT_MinVectorWidth: handleMinVectorWidthAttr(S, D, AL); break; case ParsedAttr::AT_Unavailable: handleAttrWithMessage(S, D, AL); break; case ParsedAttr::AT_ArcWeakrefUnavailable: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ObjCRootClass: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ObjCSubclassingRestricted: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ObjCExplicitProtocolImpl: handleObjCSuppresProtocolAttr(S, D, AL); break; case ParsedAttr::AT_ObjCRequiresPropertyDefs: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Unused: handleUnusedAttr(S, D, AL); break; case ParsedAttr::AT_ReturnsTwice: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NotTailCalled: handleSimpleAttributeWithExclusions( S, D, AL); break; case ParsedAttr::AT_DisableTailCalls: handleSimpleAttributeWithExclusions(S, D, AL); break; case ParsedAttr::AT_Used: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Visibility: handleVisibilityAttr(S, D, AL, false); break; case ParsedAttr::AT_TypeVisibility: handleVisibilityAttr(S, D, AL, true); break; case ParsedAttr::AT_WarnUnused: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, AL); break; case ParsedAttr::AT_Weak: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_WeakRef: handleWeakRefAttr(S, D, AL); break; case ParsedAttr::AT_WeakImport: handleWeakImportAttr(S, D, AL); break; case ParsedAttr::AT_TransparentUnion: handleTransparentUnionAttr(S, D, AL); break; case ParsedAttr::AT_ObjCException: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ObjCMethodFamily: handleObjCMethodFamilyAttr(S, D, AL); break; case ParsedAttr::AT_ObjCNSObject: handleObjCNSObject(S, D, AL); break; case ParsedAttr::AT_ObjCIndependentClass: handleObjCIndependentClass(S, D, AL); break; case ParsedAttr::AT_Blocks: handleBlocksAttr(S, D, AL); break; case ParsedAttr::AT_Sentinel: handleSentinelAttr(S, D, AL); break; case ParsedAttr::AT_Const: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Pure: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Cleanup: handleCleanupAttr(S, D, AL); break; case ParsedAttr::AT_NoDebug: handleNoDebugAttr(S, D, AL); break; case ParsedAttr::AT_NoDuplicate: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Convergent: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoInline: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg. handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoStackProtector: // Interacts with -fstack-protector options. handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_StdCall: case ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_ThisCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr::AT_PreserveAll: case ParsedAttr::AT_AArch64VectorPcs: handleCallConvAttr(S, D, AL); break; case ParsedAttr::AT_Suppress: handleSuppressAttr(S, D, AL); break; case ParsedAttr::AT_OpenCLKernel: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_OpenCLAccess: handleOpenCLAccessAttr(S, D, AL); break; case ParsedAttr::AT_OpenCLNoSVM: handleOpenCLNoSVMAttr(S, D, AL); break; case ParsedAttr::AT_SwiftContext: handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext); break; case ParsedAttr::AT_SwiftErrorResult: handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult); break; case ParsedAttr::AT_SwiftIndirectResult: handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult); break; case ParsedAttr::AT_InternalLinkage: handleInternalLinkageAttr(S, D, AL); break; case ParsedAttr::AT_ExcludeFromExplicitInstantiation: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_LTOVisibilityPublic: handleSimpleAttribute(S, D, AL); break; // Microsoft attributes: case ParsedAttr::AT_EmptyBases: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_LayoutVersion: handleLayoutVersion(S, D, AL); break; case ParsedAttr::AT_TrivialABI: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_MSNoVTable: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_MSStruct: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Uuid: handleUuidAttr(S, D, AL); break; case ParsedAttr::AT_MSInheritance: handleMSInheritanceAttr(S, D, AL); break; case ParsedAttr::AT_SelectAny: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_Thread: handleDeclspecThreadAttr(S, D, AL); break; case ParsedAttr::AT_AbiTag: handleAbiTagAttr(S, D, AL); break; // Thread safety attributes: case ParsedAttr::AT_AssertExclusiveLock: handleAssertExclusiveLockAttr(S, D, AL); break; case ParsedAttr::AT_AssertSharedLock: handleAssertSharedLockAttr(S, D, AL); break; case ParsedAttr::AT_GuardedVar: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_PtGuardedVar: handlePtGuardedVarAttr(S, D, AL); break; case ParsedAttr::AT_ScopedLockable: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_NoSanitize: handleNoSanitizeAttr(S, D, AL); break; case ParsedAttr::AT_NoSanitizeSpecific: handleNoSanitizeSpecificAttr(S, D, AL); break; case ParsedAttr::AT_NoThreadSafetyAnalysis: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_GuardedBy: handleGuardedByAttr(S, D, AL); break; case ParsedAttr::AT_PtGuardedBy: handlePtGuardedByAttr(S, D, AL); break; case ParsedAttr::AT_ExclusiveTrylockFunction: handleExclusiveTrylockFunctionAttr(S, D, AL); break; case ParsedAttr::AT_LockReturned: handleLockReturnedAttr(S, D, AL); break; case ParsedAttr::AT_LocksExcluded: handleLocksExcludedAttr(S, D, AL); break; case ParsedAttr::AT_SharedTrylockFunction: handleSharedTrylockFunctionAttr(S, D, AL); break; case ParsedAttr::AT_AcquiredBefore: handleAcquiredBeforeAttr(S, D, AL); break; case ParsedAttr::AT_AcquiredAfter: handleAcquiredAfterAttr(S, D, AL); break; // Capability analysis attributes. case ParsedAttr::AT_Capability: case ParsedAttr::AT_Lockable: handleCapabilityAttr(S, D, AL); break; case ParsedAttr::AT_RequiresCapability: handleRequiresCapabilityAttr(S, D, AL); break; case ParsedAttr::AT_AssertCapability: handleAssertCapabilityAttr(S, D, AL); break; case ParsedAttr::AT_AcquireCapability: handleAcquireCapabilityAttr(S, D, AL); break; case ParsedAttr::AT_ReleaseCapability: handleReleaseCapabilityAttr(S, D, AL); break; case ParsedAttr::AT_TryAcquireCapability: handleTryAcquireCapabilityAttr(S, D, AL); break; // Consumed analysis attributes. case ParsedAttr::AT_Consumable: handleConsumableAttr(S, D, AL); break; case ParsedAttr::AT_ConsumableAutoCast: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_ConsumableSetOnRead: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_CallableWhen: handleCallableWhenAttr(S, D, AL); break; case ParsedAttr::AT_ParamTypestate: handleParamTypestateAttr(S, D, AL); break; case ParsedAttr::AT_ReturnTypestate: handleReturnTypestateAttr(S, D, AL); break; case ParsedAttr::AT_SetTypestate: handleSetTypestateAttr(S, D, AL); break; case ParsedAttr::AT_TestTypestate: handleTestTypestateAttr(S, D, AL); break; // Type safety attributes. case ParsedAttr::AT_ArgumentWithTypeTag: handleArgumentWithTypeTagAttr(S, D, AL); break; case ParsedAttr::AT_TypeTagForDatatype: handleTypeTagForDatatypeAttr(S, D, AL); break; case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_RenderScriptKernel: handleSimpleAttribute(S, D, AL); break; // XRay attributes. case ParsedAttr::AT_XRayInstrument: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_XRayLogArgs: handleXRayLogArgsAttr(S, D, AL); break; // Move semantics attribute. case ParsedAttr::AT_Reinitializes: handleSimpleAttribute(S, D, AL); break; case ParsedAttr::AT_AlwaysDestroy: case ParsedAttr::AT_NoDestroy: handleDestroyAttr(S, D, AL); break; case ParsedAttr::AT_Uninitialized: handleUninitializedAttr(S, D, AL); break; case ParsedAttr::AT_ObjCExternallyRetained: handleObjCExternallyRetainedAttr(S, D, AL); break; } } /// ProcessDeclAttributeList - Apply all the decl attributes in the specified /// attribute list to the specified decl, ignoring any type attributes. void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, bool IncludeCXX11Attributes) { if (AttrList.empty()) return; for (const ParsedAttr &AL : AttrList) ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes); // FIXME: We should be able to handle these cases in TableGen. // GCC accepts // static int a9 __attribute__((weakref)); // but that looks really pointless. We reject it. if (D->hasAttr() && !D->hasAttr()) { Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias) << cast(D); D->dropAttr(); return; } // FIXME: We should be able to handle this in TableGen as well. It would be // good to have a way to specify "these attributes must appear as a group", // for these. Additionally, it would be good to have a way to specify "these // attribute must never appear as a group" for attributes like cold and hot. if (!D->hasAttr()) { // These attributes cannot be applied to a non-kernel function. if (const auto *A = D->getAttr()) { // FIXME: This emits a different error message than // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (!D->hasAttr()) { if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (const auto *A = D->getAttr()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } } } } // Helper for delayed processing TransparentUnion attribute. void Sema::ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList) { for (const ParsedAttr &AL : AttrList) if (AL.getKind() == ParsedAttr::AT_TransparentUnion) { handleTransparentUnionAttr(*this, D, AL); break; } } // Annotation attributes are the only attributes allowed after an access // specifier. bool Sema::ProcessAccessDeclAttributeList( AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) { for (const ParsedAttr &AL : AttrList) { if (AL.getKind() == ParsedAttr::AT_Annotate) { ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute()); } else { Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec); return true; } } return false; } /// checkUnusedDeclAttributes - Check a list of attributes to see if it /// contains any decl attributes that we should warn about. static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) { for (const ParsedAttr &AL : A) { // Only warn if the attribute is an unignored, non-type attribute. if (AL.isUsedAsTypeAttr() || AL.isInvalid()) continue; if (AL.getKind() == ParsedAttr::IgnoredAttribute) continue; if (AL.getKind() == ParsedAttr::UnknownAttribute) { S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL << AL.getRange(); } else { S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL << AL.getRange(); } } } /// checkUnusedDeclAttributes - Given a declarator which is not being /// used to build a declaration, complain about any decl attributes /// which might be lying around on it. void Sema::checkUnusedDeclAttributes(Declarator &D) { ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes()); ::checkUnusedDeclAttributes(*this, D.getAttributes()); for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); } /// DeclClonePragmaWeak - clone existing decl (maybe definition), /// \#pragma weak needs a non-definition decl and source may not have one. NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc) { assert(isa(ND) || isa(ND)); NamedDecl *NewD = nullptr; if (auto *FD = dyn_cast(ND)) { FunctionDecl *NewFD; // FIXME: Missing call to CheckFunctionDeclaration(). // FIXME: Mangling? // FIXME: Is the qualifier info correct? // FIXME: Is the DeclContext correct? NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), Loc, Loc, DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None, false/*isInlineSpecified*/, FD->hasPrototype(), false/*isConstexprSpecified*/); NewD = NewFD; if (FD->getQualifier()) NewFD->setQualifierInfo(FD->getQualifierLoc()); // Fake up parameter variables; they are declared as if this were // a typedef. QualType FDTy = FD->getType(); if (const auto *FT = FDTy->getAs()) { SmallVector Params; for (const auto &AI : FT->param_types()) { ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); Param->setScopeInfo(0, Params.size()); Params.push_back(Param); } NewFD->setParams(Params); } } else if (auto *VD = dyn_cast(ND)) { NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), VD->getInnerLocStart(), VD->getLocation(), II, VD->getType(), VD->getTypeSourceInfo(), VD->getStorageClass()); if (VD->getQualifier()) cast(NewD)->setQualifierInfo(VD->getQualifierLoc()); } return NewD; } /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak /// applied to it, possibly with an alias. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { if (W.getUsed()) return; // only do this once W.setUsed(true); if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) IdentifierInfo *NDId = ND->getIdentifier(); NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); WeakTopLevelDecl.push_back(NewD); // FIXME: "hideous" code from Sema::LazilyCreateBuiltin // to insert Decl at TU scope, sorry. DeclContext *SavedContext = CurContext; CurContext = Context.getTranslationUnitDecl(); NewD->setDeclContext(CurContext); NewD->setLexicalDeclContext(CurContext); PushOnScopeChains(NewD, S); CurContext = SavedContext; } else { // just add weak to existing ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); } } void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { // It's valid to "forward-declare" #pragma weak, in which case we // have to do this. LoadExternalWeakUndeclaredIdentifiers(); if (!WeakUndeclaredIdentifiers.empty()) { NamedDecl *ND = nullptr; if (auto *VD = dyn_cast(D)) if (VD->isExternC()) ND = VD; if (auto *FD = dyn_cast(D)) if (FD->isExternC()) ND = FD; if (ND) { if (IdentifierInfo *Id = ND->getIdentifier()) { auto I = WeakUndeclaredIdentifiers.find(Id); if (I != WeakUndeclaredIdentifiers.end()) { WeakInfo W = I->second; DeclApplyPragmaWeak(S, ND, W); WeakUndeclaredIdentifiers[Id] = W; } } } } } /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in /// it, apply them to D. This is a bit tricky because PD can have attributes /// specified in many different places, and we need to find and apply them all. void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { // Apply decl attributes from the DeclSpec if present. if (!PD.getDeclSpec().getAttributes().empty()) ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes()); // Walk the declarator structure, applying decl attributes that were in a type // position to the decl itself. This handles cases like: // int *__attr__(x)** D; // when X is a decl attribute. for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(), /*IncludeCXX11Attributes=*/false); // Finally, apply any attributes on the decl itself. ProcessDeclAttributeList(S, D, PD.getAttributes()); // Apply additional attributes specified by '#pragma clang attribute'. AddPragmaAttributes(S, D); } /// Is the given declaration allowed to use a forbidden type? /// If so, it'll still be annotated with an attribute that makes it /// illegal to actually use. static bool isForbiddenTypeAllowed(Sema &S, Decl *D, const DelayedDiagnostic &diag, UnavailableAttr::ImplicitReason &reason) { // Private ivars are always okay. Unfortunately, people don't // always properly make their ivars private, even in system headers. // Plus we need to make fields okay, too. if (!isa(D) && !isa(D) && !isa(D)) return false; // Silently accept unsupported uses of __weak in both user and system // declarations when it's been disabled, for ease of integration with // -fno-objc-arc files. We do have to take some care against attempts // to define such things; for now, we've only done that for ivars // and properties. if ((isa(D) || isa(D))) { if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { reason = UnavailableAttr::IR_ForbiddenWeak; return true; } } // Allow all sorts of things in system headers. if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) { // Currently, all the failures dealt with this way are due to ARC // restrictions. reason = UnavailableAttr::IR_ARCForbiddenType; return true; } return false; } /// Handle a delayed forbidden-type diagnostic. static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD, Decl *D) { auto Reason = UnavailableAttr::IR_None; if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) { assert(Reason && "didn't set reason?"); D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc)); return; } if (S.getLangOpts().ObjCAutoRefCount) if (const auto *FD = dyn_cast(D)) { // FIXME: we may want to suppress diagnostics for all // kind of forbidden type messages on unavailable functions. if (FD->hasAttr() && DD.getForbiddenTypeDiagnostic() == diag::err_arc_array_param_no_ownership) { DD.Triggered = true; return; } } S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic()) << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument(); DD.Triggered = true; } static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context, const Decl *D) { // Check each AvailabilityAttr to find the one for this platform. for (const auto *A : D->attrs()) { if (const auto *Avail = dyn_cast(A)) { // FIXME: this is copied from CheckAvailability. We should try to // de-duplicate. // Check if this is an App Extension "platform", and if so chop off // the suffix for matching with the actual platform. StringRef ActualPlatform = Avail->getPlatform()->getName(); StringRef RealizedPlatform = ActualPlatform; if (Context.getLangOpts().AppExt) { size_t suffix = RealizedPlatform.rfind("_app_extension"); if (suffix != StringRef::npos) RealizedPlatform = RealizedPlatform.slice(0, suffix); } StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); // Match the platform name. if (RealizedPlatform == TargetPlatform) return Avail; } } return nullptr; } /// The diagnostic we should emit for \c D, and the declaration that /// originated it, or \c AR_Available. /// /// \param D The declaration to check. /// \param Message If non-null, this will be populated with the message from /// the availability attribute that is selected. /// \param ClassReceiver If we're checking the the method of a class message /// send, the class. Otherwise nullptr. static std::pair ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver) { AvailabilityResult Result = D->getAvailability(Message); // For typedefs, if the typedef declaration appears available look // to the underlying type to see if it is more restrictive. while (const auto *TD = dyn_cast(D)) { if (Result == AR_Available) { if (const auto *TT = TD->getUnderlyingType()->getAs()) { D = TT->getDecl(); Result = D->getAvailability(Message); continue; } } break; } // Forward class declarations get their attributes from their definition. if (const auto *IDecl = dyn_cast(D)) { if (IDecl->getDefinition()) { D = IDecl->getDefinition(); Result = D->getAvailability(Message); } } if (const auto *ECD = dyn_cast(D)) if (Result == AR_Available) { const DeclContext *DC = ECD->getDeclContext(); if (const auto *TheEnumDecl = dyn_cast(DC)) { Result = TheEnumDecl->getAvailability(Message); D = TheEnumDecl; } } // For +new, infer availability from -init. if (const auto *MD = dyn_cast(D)) { if (S.NSAPIObj && ClassReceiver) { ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod( S.NSAPIObj->getInitSelector()); if (Init && Result == AR_Available && MD->isClassMethod() && MD->getSelector() == S.NSAPIObj->getNewSelector() && MD->definedInNSObject(S.getASTContext())) { Result = Init->getAvailability(Message); D = Init; } } } return {Result, D}; } /// whether we should emit a diagnostic for \c K and \c DeclVersion in /// the context of \c Ctx. For example, we should emit an unavailable diagnostic /// in a deprecated context, but not the other way around. static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K, VersionTuple DeclVersion, Decl *Ctx, const NamedDecl *OffendingDecl) { assert(K != AR_Available && "Expected an unavailable declaration here!"); // Checks if we should emit the availability diagnostic in the context of C. auto CheckContext = [&](const Decl *C) { if (K == AR_NotYetIntroduced) { if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C)) if (AA->getIntroduced() >= DeclVersion) return true; } else if (K == AR_Deprecated) { if (C->isDeprecated()) return true; } else if (K == AR_Unavailable) { // It is perfectly fine to refer to an 'unavailable' Objective-C method - // when it's actually defined and is referenced from within the - // @implementation itself. In this context, we interpret unavailable as a - // form of access control. + // when it is referenced from within the @implementation itself. In this + // context, we interpret unavailable as a form of access control. if (const auto *MD = dyn_cast(OffendingDecl)) { if (const auto *Impl = dyn_cast(C)) { - if (MD->getClassInterface() == Impl->getClassInterface() && - MD->isDefined()) + if (MD->getClassInterface() == Impl->getClassInterface()) return true; } } } if (C->isUnavailable()) return true; return false; }; do { if (CheckContext(Ctx)) return false; // An implementation implicitly has the availability of the interface. // Unless it is "+load" method. if (const auto *MethodD = dyn_cast(Ctx)) if (MethodD->isClassMethod() && MethodD->getSelector().getAsString() == "load") return true; if (const auto *CatOrImpl = dyn_cast(Ctx)) { if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) if (CheckContext(Interface)) return false; } // A category implicitly has the availability of the interface. else if (const auto *CatD = dyn_cast(Ctx)) if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) if (CheckContext(Interface)) return false; } while ((Ctx = cast_or_null(Ctx->getDeclContext()))); return true; } static bool shouldDiagnoseAvailabilityByDefault(const ASTContext &Context, const VersionTuple &DeploymentVersion, const VersionTuple &DeclVersion) { const auto &Triple = Context.getTargetInfo().getTriple(); VersionTuple ForceAvailabilityFromVersion; switch (Triple.getOS()) { case llvm::Triple::IOS: case llvm::Triple::TvOS: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11); break; case llvm::Triple::WatchOS: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4); break; case llvm::Triple::Darwin: case llvm::Triple::MacOSX: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13); break; default: // New targets should always warn about availability. return Triple.getVendor() == llvm::Triple::Apple; } return DeploymentVersion >= ForceAvailabilityFromVersion || DeclVersion >= ForceAvailabilityFromVersion; } static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) { for (Decl *Ctx = OrigCtx; Ctx; Ctx = cast_or_null(Ctx->getDeclContext())) { if (isa(Ctx) || isa(Ctx) || isa(Ctx)) return cast(Ctx); if (auto *CD = dyn_cast(Ctx)) { if (auto *Imp = dyn_cast(Ctx)) return Imp->getClassInterface(); return CD; } } return dyn_cast(OrigCtx); } namespace { struct AttributeInsertion { StringRef Prefix; SourceLocation Loc; StringRef Suffix; static AttributeInsertion createInsertionAfter(const NamedDecl *D) { return {" ", D->getEndLoc(), ""}; } static AttributeInsertion createInsertionAfter(SourceLocation Loc) { return {" ", Loc, ""}; } static AttributeInsertion createInsertionBefore(const NamedDecl *D) { return {"", D->getBeginLoc(), "\n"}; } }; } // end anonymous namespace /// Tries to parse a string as ObjC method name. /// /// \param Name The string to parse. Expected to originate from availability /// attribute argument. /// \param SlotNames The vector that will be populated with slot names. In case /// of unsuccessful parsing can contain invalid data. /// \returns A number of method parameters if parsing was successful, None /// otherwise. static Optional tryParseObjCMethodName(StringRef Name, SmallVectorImpl &SlotNames, const LangOptions &LangOpts) { // Accept replacements starting with - or + as valid ObjC method names. if (!Name.empty() && (Name.front() == '-' || Name.front() == '+')) Name = Name.drop_front(1); if (Name.empty()) return None; Name.split(SlotNames, ':'); unsigned NumParams; if (Name.back() == ':') { // Remove an empty string at the end that doesn't represent any slot. SlotNames.pop_back(); NumParams = SlotNames.size(); } else { if (SlotNames.size() != 1) // Not a valid method name, just a colon-separated string. return None; NumParams = 0; } // Verify all slot names are valid. bool AllowDollar = LangOpts.DollarIdents; for (StringRef S : SlotNames) { if (S.empty()) continue; if (!isValidIdentifier(S, AllowDollar)) return None; } return NumParams; } /// Returns a source location in which it's appropriate to insert a new /// attribute for the given declaration \D. static Optional createAttributeInsertion(const NamedDecl *D, const SourceManager &SM, const LangOptions &LangOpts) { if (isa(D)) return AttributeInsertion::createInsertionAfter(D); if (const auto *MD = dyn_cast(D)) { if (MD->hasBody()) return None; return AttributeInsertion::createInsertionAfter(D); } if (const auto *TD = dyn_cast(D)) { SourceLocation Loc = Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts); if (Loc.isInvalid()) return None; // Insert after the 'struct'/whatever keyword. return AttributeInsertion::createInsertionAfter(Loc); } return AttributeInsertion::createInsertionBefore(D); } /// Actually emit an availability diagnostic for a reference to an unavailable /// decl. /// /// \param Ctx The context that the reference occurred in /// \param ReferringDecl The exact declaration that was referenced. /// \param OffendingDecl A related decl to \c ReferringDecl that has an /// availability attribute corresponding to \c K attached to it. Note that this /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl /// and OffendingDecl is the EnumDecl. static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, Decl *Ctx, const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl, StringRef Message, ArrayRef Locs, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Diagnostics for deprecated or unavailable. unsigned diag, diag_message, diag_fwdclass_message; unsigned diag_available_here = diag::note_availability_specified_here; SourceLocation NoteLocation = OffendingDecl->getLocation(); // Matches 'diag::note_property_attribute' options. unsigned property_note_select; // Matches diag::note_availability_specified_here. unsigned available_here_select_kind; VersionTuple DeclVersion; if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl)) DeclVersion = AA->getIntroduced(); if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx, OffendingDecl)) return; SourceLocation Loc = Locs.front(); // The declaration can have multiple availability attributes, we are looking // at one of them. const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl); if (A && A->isInherited()) { for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl; Redecl = Redecl->getPreviousDecl()) { const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context, Redecl); if (AForRedecl && !AForRedecl->isInherited()) { // If D is a declaration with inherited attributes, the note should // point to the declaration with actual attributes. NoteLocation = Redecl->getLocation(); break; } } } switch (K) { case AR_NotYetIntroduced: { // We would like to emit the diagnostic even if -Wunguarded-availability is // not specified for deployment targets >= to iOS 11 or equivalent or // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or // later. const AvailabilityAttr *AA = getAttrForPlatform(S.getASTContext(), OffendingDecl); VersionTuple Introduced = AA->getIntroduced(); bool UseNewWarning = shouldDiagnoseAvailabilityByDefault( S.Context, S.Context.getTargetInfo().getPlatformMinVersion(), Introduced); unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new : diag::warn_unguarded_availability; std::string PlatformName = AvailabilityAttr::getPrettyPlatformName( S.getASTContext().getTargetInfo().getPlatformName()); S.Diag(Loc, Warning) << OffendingDecl << PlatformName << Introduced.getAsString(); S.Diag(OffendingDecl->getLocation(), diag::note_partial_availability_specified_here) << OffendingDecl << PlatformName << Introduced.getAsString() << S.Context.getTargetInfo().getPlatformMinVersion().getAsString(); if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) { if (const auto *TD = dyn_cast(Enclosing)) if (TD->getDeclName().isEmpty()) { S.Diag(TD->getLocation(), diag::note_decl_unguarded_availability_silence) << /*Anonymous*/ 1 << TD->getKindName(); return; } auto FixitNoteDiag = S.Diag(Enclosing->getLocation(), diag::note_decl_unguarded_availability_silence) << /*Named*/ 0 << Enclosing; // Don't offer a fixit for declarations with availability attributes. if (Enclosing->hasAttr()) return; if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE")) return; Optional Insertion = createAttributeInsertion( Enclosing, S.getSourceManager(), S.getLangOpts()); if (!Insertion) return; std::string PlatformName = AvailabilityAttr::getPlatformNameSourceSpelling( S.getASTContext().getTargetInfo().getPlatformName()) .lower(); std::string Introduced = OffendingDecl->getVersionIntroduced().getAsString(); FixitNoteDiag << FixItHint::CreateInsertion( Insertion->Loc, (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName + "(" + Introduced + "))" + Insertion->Suffix) .str()); } return; } case AR_Deprecated: diag = !ObjCPropertyAccess ? diag::warn_deprecated : diag::warn_property_method_deprecated; diag_message = diag::warn_deprecated_message; diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; property_note_select = /* deprecated */ 0; available_here_select_kind = /* deprecated */ 2; if (const auto *AL = OffendingDecl->getAttr()) NoteLocation = AL->getLocation(); break; case AR_Unavailable: diag = !ObjCPropertyAccess ? diag::err_unavailable : diag::err_property_method_unavailable; diag_message = diag::err_unavailable_message; diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; property_note_select = /* unavailable */ 1; available_here_select_kind = /* unavailable */ 0; if (auto AL = OffendingDecl->getAttr()) { if (AL->isImplicit() && AL->getImplicitReason()) { // Most of these failures are due to extra restrictions in ARC; // reflect that in the primary diagnostic when applicable. auto flagARCError = [&] { if (S.getLangOpts().ObjCAutoRefCount && S.getSourceManager().isInSystemHeader( OffendingDecl->getLocation())) diag = diag::err_unavailable_in_arc; }; switch (AL->getImplicitReason()) { case UnavailableAttr::IR_None: break; case UnavailableAttr::IR_ARCForbiddenType: flagARCError(); diag_available_here = diag::note_arc_forbidden_type; break; case UnavailableAttr::IR_ForbiddenWeak: if (S.getLangOpts().ObjCWeakRuntime) diag_available_here = diag::note_arc_weak_disabled; else diag_available_here = diag::note_arc_weak_no_runtime; break; case UnavailableAttr::IR_ARCForbiddenConversion: flagARCError(); diag_available_here = diag::note_performs_forbidden_arc_conversion; break; case UnavailableAttr::IR_ARCInitReturnsUnrelated: flagARCError(); diag_available_here = diag::note_arc_init_returns_unrelated; break; case UnavailableAttr::IR_ARCFieldWithOwnership: flagARCError(); diag_available_here = diag::note_arc_field_with_ownership; break; } } } break; case AR_Available: llvm_unreachable("Warning for availability of available declaration?"); } SmallVector FixIts; if (K == AR_Deprecated) { StringRef Replacement; if (auto AL = OffendingDecl->getAttr()) Replacement = AL->getReplacement(); if (auto AL = getAttrForPlatform(S.Context, OffendingDecl)) Replacement = AL->getReplacement(); CharSourceRange UseRange; if (!Replacement.empty()) UseRange = CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); if (UseRange.isValid()) { if (const auto *MethodDecl = dyn_cast(ReferringDecl)) { Selector Sel = MethodDecl->getSelector(); SmallVector SelectorSlotNames; Optional NumParams = tryParseObjCMethodName( Replacement, SelectorSlotNames, S.getLangOpts()); if (NumParams && NumParams.getValue() == Sel.getNumArgs()) { assert(SelectorSlotNames.size() == Locs.size()); for (unsigned I = 0; I < Locs.size(); ++I) { if (!Sel.getNameForSlot(I).empty()) { CharSourceRange NameRange = CharSourceRange::getCharRange( Locs[I], S.getLocForEndOfToken(Locs[I])); FixIts.push_back(FixItHint::CreateReplacement( NameRange, SelectorSlotNames[I])); } else FixIts.push_back( FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I])); } } else FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement)); } else FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement)); } } if (!Message.empty()) { S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts; if (ObjCProperty) S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) << ObjCProperty->getDeclName() << property_note_select; } else if (!UnknownObjCClass) { S.Diag(Loc, diag) << ReferringDecl << FixIts; if (ObjCProperty) S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) << ObjCProperty->getDeclName() << property_note_select; } else { S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts; S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); } S.Diag(NoteLocation, diag_available_here) << OffendingDecl << available_here_select_kind; } static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, Decl *Ctx) { assert(DD.Kind == DelayedDiagnostic::Availability && "Expected an availability diagnostic here"); DD.Triggered = true; DoEmitAvailabilityWarning( S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(), DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(), DD.getObjCProperty(), false); } void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { assert(DelayedDiagnostics.getCurrentPool()); DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); DelayedDiagnostics.popWithoutEmitting(state); // When delaying diagnostics to run in the context of a parsed // declaration, we only want to actually emit anything if parsing // succeeds. if (!decl) return; // We emit all the active diagnostics in this pool or any of its // parents. In general, we'll get one pool for the decl spec // and a child pool for each declarator; in a decl group like: // deprecated_typedef foo, *bar, baz(); // only the declarator pops will be passed decls. This is correct; // we really do need to consider delayed diagnostics from the decl spec // for each of the different declarations. const DelayedDiagnosticPool *pool = &poppedPool; do { bool AnyAccessFailures = false; for (DelayedDiagnosticPool::pool_iterator i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { // This const_cast is a bit lame. Really, Triggered should be mutable. DelayedDiagnostic &diag = const_cast(*i); if (diag.Triggered) continue; switch (diag.Kind) { case DelayedDiagnostic::Availability: // Don't bother giving deprecation/unavailable diagnostics if // the decl is invalid. if (!decl->isInvalidDecl()) handleDelayedAvailabilityCheck(*this, diag, decl); break; case DelayedDiagnostic::Access: // Only produce one access control diagnostic for a structured binding // declaration: we don't need to tell the user that all the fields are // inaccessible one at a time. if (AnyAccessFailures && isa(decl)) continue; HandleDelayedAccessCheck(diag, decl); if (diag.Triggered) AnyAccessFailures = true; break; case DelayedDiagnostic::ForbiddenType: handleDelayedForbiddenType(*this, diag, decl); break; } } } while ((pool = pool->getParent())); } /// Given a set of delayed diagnostics, re-emit them as if they had /// been delayed in the current context instead of in the given pool. /// Essentially, this just moves them to the current pool. void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); assert(curPool && "re-emitting in undelayed context not supported"); curPool->steal(pool); } static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR, const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl, StringRef Message, ArrayRef Locs, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Delay if we're currently parsing a declaration. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { S.DelayedDiagnostics.add( DelayedDiagnostic::makeAvailability( AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass, ObjCProperty, Message, ObjCPropertyAccess)); return; } Decl *Ctx = cast(S.getCurLexicalContext()); DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl, Message, Locs, UnknownObjCClass, ObjCProperty, ObjCPropertyAccess); } namespace { /// Returns true if the given statement can be a body-like child of \p Parent. bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) { switch (Parent->getStmtClass()) { case Stmt::IfStmtClass: return cast(Parent)->getThen() == S || cast(Parent)->getElse() == S; case Stmt::WhileStmtClass: return cast(Parent)->getBody() == S; case Stmt::DoStmtClass: return cast(Parent)->getBody() == S; case Stmt::ForStmtClass: return cast(Parent)->getBody() == S; case Stmt::CXXForRangeStmtClass: return cast(Parent)->getBody() == S; case Stmt::ObjCForCollectionStmtClass: return cast(Parent)->getBody() == S; case Stmt::CaseStmtClass: case Stmt::DefaultStmtClass: return cast(Parent)->getSubStmt() == S; default: return false; } } class StmtUSEFinder : public RecursiveASTVisitor { const Stmt *Target; public: bool VisitStmt(Stmt *S) { return S != Target; } /// Returns true if the given statement is present in the given declaration. static bool isContained(const Stmt *Target, const Decl *D) { StmtUSEFinder Visitor; Visitor.Target = Target; return !Visitor.TraverseDecl(const_cast(D)); } }; /// Traverses the AST and finds the last statement that used a given /// declaration. class LastDeclUSEFinder : public RecursiveASTVisitor { const Decl *D; public: bool VisitDeclRefExpr(DeclRefExpr *DRE) { if (DRE->getDecl() == D) return false; return true; } static const Stmt *findLastStmtThatUsesDecl(const Decl *D, const CompoundStmt *Scope) { LastDeclUSEFinder Visitor; Visitor.D = D; for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) { const Stmt *S = *I; if (!Visitor.TraverseStmt(const_cast(S))) return S; } return nullptr; } }; /// This class implements -Wunguarded-availability. /// /// This is done with a traversal of the AST of a function that makes reference /// to a partially available declaration. Whenever we encounter an \c if of the /// form: \c if(@available(...)), we use the version from the condition to visit /// the then statement. class DiagnoseUnguardedAvailability : public RecursiveASTVisitor { typedef RecursiveASTVisitor Base; Sema &SemaRef; Decl *Ctx; /// Stack of potentially nested 'if (@available(...))'s. SmallVector AvailabilityStack; SmallVector StmtStack; void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ClassReceiver = nullptr); public: DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx) : SemaRef(SemaRef), Ctx(Ctx) { AvailabilityStack.push_back( SemaRef.Context.getTargetInfo().getPlatformMinVersion()); } bool TraverseDecl(Decl *D) { // Avoid visiting nested functions to prevent duplicate warnings. if (!D || isa(D)) return true; return Base::TraverseDecl(D); } bool TraverseStmt(Stmt *S) { if (!S) return true; StmtStack.push_back(S); bool Result = Base::TraverseStmt(S); StmtStack.pop_back(); return Result; } void IssueDiagnostics(Stmt *S) { TraverseStmt(S); } bool TraverseIfStmt(IfStmt *If); bool TraverseLambdaExpr(LambdaExpr *E) { return true; } // for 'case X:' statements, don't bother looking at the 'X'; it can't lead // to any useful diagnostics. bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) { if (PRE->isClassReceiver()) DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation()); return true; } bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) { if (ObjCMethodDecl *D = Msg->getMethodDecl()) { ObjCInterfaceDecl *ID = nullptr; QualType ReceiverTy = Msg->getClassReceiver(); if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType()) ID = ReceiverTy->getAsObjCInterfaceType()->getInterface(); DiagnoseDeclAvailability( D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID); } return true; } bool VisitDeclRefExpr(DeclRefExpr *DRE) { DiagnoseDeclAvailability(DRE->getDecl(), SourceRange(DRE->getBeginLoc(), DRE->getEndLoc())); return true; } bool VisitMemberExpr(MemberExpr *ME) { DiagnoseDeclAvailability(ME->getMemberDecl(), SourceRange(ME->getBeginLoc(), ME->getEndLoc())); return true; } bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use) << (!SemaRef.getLangOpts().ObjC); return true; } bool VisitTypeLoc(TypeLoc Ty); }; void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability( NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) { AvailabilityResult Result; const NamedDecl *OffendingDecl; std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass); if (Result != AR_Available) { // All other diagnostic kinds have already been handled in // DiagnoseAvailabilityOfDecl. if (Result != AR_NotYetIntroduced) return; const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl); VersionTuple Introduced = AA->getIntroduced(); if (AvailabilityStack.back() >= Introduced) return; // If the context of this function is less available than D, we should not // emit a diagnostic. if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx, OffendingDecl)) return; // We would like to emit the diagnostic even if -Wunguarded-availability is // not specified for deployment targets >= to iOS 11 or equivalent or // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or // later. unsigned DiagKind = shouldDiagnoseAvailabilityByDefault( SemaRef.Context, SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced) ? diag::warn_unguarded_availability_new : diag::warn_unguarded_availability; std::string PlatformName = AvailabilityAttr::getPrettyPlatformName( SemaRef.getASTContext().getTargetInfo().getPlatformName()); SemaRef.Diag(Range.getBegin(), DiagKind) << Range << D << PlatformName << Introduced.getAsString(); SemaRef.Diag(OffendingDecl->getLocation(), diag::note_partial_availability_specified_here) << OffendingDecl << PlatformName << Introduced.getAsString() << SemaRef.Context.getTargetInfo() .getPlatformMinVersion() .getAsString(); auto FixitDiag = SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence) << Range << D << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0 : /*__builtin_available*/ 1); // Find the statement which should be enclosed in the if @available check. if (StmtStack.empty()) return; const Stmt *StmtOfUse = StmtStack.back(); const CompoundStmt *Scope = nullptr; for (const Stmt *S : llvm::reverse(StmtStack)) { if (const auto *CS = dyn_cast(S)) { Scope = CS; break; } if (isBodyLikeChildStmt(StmtOfUse, S)) { // The declaration won't be seen outside of the statement, so we don't // have to wrap the uses of any declared variables in if (@available). // Therefore we can avoid setting Scope here. break; } StmtOfUse = S; } const Stmt *LastStmtOfUse = nullptr; if (isa(StmtOfUse) && Scope) { for (const Decl *D : cast(StmtOfUse)->decls()) { if (StmtUSEFinder::isContained(StmtStack.back(), D)) { LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope); break; } } } const SourceManager &SM = SemaRef.getSourceManager(); SourceLocation IfInsertionLoc = SM.getExpansionLoc(StmtOfUse->getBeginLoc()); SourceLocation StmtEndLoc = SM.getExpansionRange( (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc()) .getEnd(); if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc)) return; StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM); const char *ExtraIndentation = " "; std::string FixItString; llvm::raw_string_ostream FixItOS(FixItString); FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available" : "__builtin_available") << "(" << AvailabilityAttr::getPlatformNameSourceSpelling( SemaRef.getASTContext().getTargetInfo().getPlatformName()) << " " << Introduced.getAsString() << ", *)) {\n" << Indentation << ExtraIndentation; FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str()); SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken( StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(), /*SkipTrailingWhitespaceAndNewLine=*/false); if (ElseInsertionLoc.isInvalid()) ElseInsertionLoc = Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts()); FixItOS.str().clear(); FixItOS << "\n" << Indentation << "} else {\n" << Indentation << ExtraIndentation << "// Fallback on earlier versions\n" << Indentation << "}"; FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str()); } } bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) { const Type *TyPtr = Ty.getTypePtr(); SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()}; if (Range.isInvalid()) return true; if (const auto *TT = dyn_cast(TyPtr)) { TagDecl *TD = TT->getDecl(); DiagnoseDeclAvailability(TD, Range); } else if (const auto *TD = dyn_cast(TyPtr)) { TypedefNameDecl *D = TD->getDecl(); DiagnoseDeclAvailability(D, Range); } else if (const auto *ObjCO = dyn_cast(TyPtr)) { if (NamedDecl *D = ObjCO->getInterface()) DiagnoseDeclAvailability(D, Range); } return true; } bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) { VersionTuple CondVersion; if (auto *E = dyn_cast(If->getCond())) { CondVersion = E->getVersion(); // If we're using the '*' case here or if this check is redundant, then we // use the enclosing version to check both branches. if (CondVersion.empty() || CondVersion <= AvailabilityStack.back()) return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse()); } else { // This isn't an availability checking 'if', we can just continue. return Base::TraverseIfStmt(If); } AvailabilityStack.push_back(CondVersion); bool ShouldContinue = TraverseStmt(If->getThen()); AvailabilityStack.pop_back(); return ShouldContinue && TraverseStmt(If->getElse()); } } // end anonymous namespace void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) { Stmt *Body = nullptr; if (auto *FD = D->getAsFunction()) { // FIXME: We only examine the pattern decl for availability violations now, // but we should also examine instantiated templates. if (FD->isTemplateInstantiation()) return; Body = FD->getBody(); } else if (auto *MD = dyn_cast(D)) Body = MD->getBody(); else if (auto *BD = dyn_cast(D)) Body = BD->getBody(); assert(Body && "Need a body here!"); DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body); } void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver) { std::string Message; AvailabilityResult Result; const NamedDecl* OffendingDecl; // See if this declaration is unavailable, deprecated, or partial. std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver); if (Result == AR_Available) return; if (Result == AR_NotYetIntroduced) { if (AvoidPartialAvailabilityChecks) return; // We need to know the @available context in the current function to // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that // when we're done parsing the current function. if (getCurFunctionOrMethodDecl()) { getEnclosingFunction()->HasPotentialAvailabilityViolations = true; return; } else if (getCurBlock() || getCurLambda()) { getCurFunction()->HasPotentialAvailabilityViolations = true; return; } } const ObjCPropertyDecl *ObjCPDecl = nullptr; if (const auto *MD = dyn_cast(D)) { if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { AvailabilityResult PDeclResult = PD->getAvailability(nullptr); if (PDeclResult == Result) ObjCPDecl = PD; } } EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs, UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess); } Index: vendor/clang/dist-release_80/test/CodeGen/attr-msp430.c =================================================================== --- vendor/clang/dist-release_80/test/CodeGen/attr-msp430.c (nonexistent) +++ vendor/clang/dist-release_80/test/CodeGen/attr-msp430.c (revision 343193) @@ -0,0 +1,10 @@ +// RUN: %clang_cc1 -triple msp430-unknown-unknown -emit-llvm < %s| FileCheck %s + +__attribute__((interrupt(1))) void foo(void) {} +// CHECK: @llvm.used +// CHECK-SAME: @foo + +// CHECK: define msp430_intrcc void @foo() #0 +// CHECK: attributes #0 +// CHECK-SAME: noinline +// CHECK-SAME: "interrupt"="1" Index: vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local-visibility.cpp =================================================================== --- vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local-visibility.cpp (nonexistent) +++ vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local-visibility.cpp (revision 343193) @@ -0,0 +1,17 @@ +// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck --check-prefix=LINUX %s +// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-apple-darwin12 | FileCheck --check-prefix=DARWIN %s + +// Regression test for PR40327 + +// LINUX: @default_tls = thread_local global i32 +// LINUX: @hidden_tls = hidden thread_local global i32 +// LINUX: define weak_odr hidden i32* @_ZTW11default_tls() +// LINUX: define weak_odr hidden i32* @_ZTW10hidden_tls() +// +// DARWIN: @default_tls = internal thread_local global i32 +// DARWIN: @hidden_tls = internal thread_local global i32 +// DARWIN: define cxx_fast_tlscc i32* @_ZTW11default_tls() +// DARWIN: define hidden cxx_fast_tlscc i32* @_ZTW10hidden_tls() + +__attribute__((visibility("default"))) thread_local int default_tls; +__attribute__((visibility("hidden"))) thread_local int hidden_tls; Index: vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local.cpp =================================================================== --- vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local.cpp (revision 343192) +++ vendor/clang/dist-release_80/test/CodeGenCXX/cxx11-thread-local.cpp (revision 343193) @@ -1,344 +1,344 @@ // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck --check-prefix=CHECK --check-prefix=LINUX %s // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -O2 -disable-llvm-passes -o - -triple x86_64-linux-gnu | FileCheck --check-prefix=CHECK --check-prefix=LINUX --check-prefix=CHECK-OPT %s // RUN: %clang_cc1 -std=c++11 -femulated-tls -emit-llvm %s -o - \ // RUN: -triple x86_64-linux-gnu 2>&1 | FileCheck --check-prefix=CHECK --check-prefix=LINUX %s // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-apple-darwin12 | FileCheck --check-prefix=CHECK --check-prefix=DARWIN %s int f(); int g(); // LINUX-DAG: @a = thread_local global i32 0 // DARWIN-DAG: @a = internal thread_local global i32 0 thread_local int a = f(); extern thread_local int b; // CHECK-DAG: @c = global i32 0 int c = b; // CHECK-DAG: @_ZL1d = internal thread_local global i32 0 static thread_local int d = g(); struct U { static thread_local int m; }; // LINUX-DAG: @_ZN1U1mE = thread_local global i32 0 // DARWIN-DAG: @_ZN1U1mE = internal thread_local global i32 0 thread_local int U::m = f(); namespace MismatchedInitType { // Check that we don't crash here when we're forced to create a new global // variable (with a different type) when we add the initializer. union U { int a; float f; constexpr U() : f(0.0) {} }; static thread_local U u; void *p = &u; } template struct V { static thread_local int m; }; template thread_local int V::m = g(); template struct W { static thread_local int m; }; template thread_local int W::m = 123; struct Dtor { ~Dtor(); }; template struct X { static thread_local Dtor m; }; template thread_local Dtor X::m; // CHECK-DAG: @e = global void *e = V::m + W::m + &X::m; template thread_local int V::m; template thread_local int W::m; template thread_local Dtor X::m; extern template thread_local int V::m; extern template thread_local int W::m; extern template thread_local Dtor X::m; void *e2 = V::m + W::m + &X::m; // CHECK-DAG: @_ZN1VIiE1mE = linkonce_odr thread_local global i32 0 // CHECK-DAG: @_ZN1WIiE1mE = linkonce_odr thread_local global i32 123 // CHECK-DAG: @_ZN1XIiE1mE = linkonce_odr thread_local global {{.*}} // CHECK-DAG: @_ZN1VIfE1mE = weak_odr thread_local global i32 0 // CHECK-DAG: @_ZN1WIfE1mE = weak_odr thread_local global i32 123 // CHECK-DAG: @_ZN1XIfE1mE = weak_odr thread_local global {{.*}} // CHECK-DAG: @_ZZ1fvE1n = internal thread_local global i32 0 // CHECK-DAG: @_ZGVZ1fvE1n = internal thread_local global i8 0 // CHECK-DAG: @_ZZ8tls_dtorvE1s = internal thread_local global // CHECK-DAG: @_ZGVZ8tls_dtorvE1s = internal thread_local global i8 0 // CHECK-DAG: @_ZZ8tls_dtorvE1t = internal thread_local global // CHECK-DAG: @_ZGVZ8tls_dtorvE1t = internal thread_local global i8 0 // CHECK-DAG: @_ZZ8tls_dtorvE1u = internal thread_local global // CHECK-DAG: @_ZGVZ8tls_dtorvE1u = internal thread_local global i8 0 // CHECK-DAG: @_ZGRZ8tls_dtorvE1u_ = internal thread_local global // CHECK-DAG: @_ZGVN1VIiE1mE = linkonce_odr thread_local global i64 0 // CHECK-DAG: @__tls_guard = internal thread_local global i8 0 // CHECK-DAG: @llvm.global_ctors = appending global {{.*}} @[[GLOBAL_INIT:[^ ]*]] // LINUX-DAG: @_ZTH1a = alias void (), void ()* @__tls_init // DARWIN-DAG: @_ZTH1a = internal alias void (), void ()* @__tls_init // CHECK-DAG: @_ZTHL1d = internal alias void (), void ()* @__tls_init // LINUX-DAG: @_ZTHN1U1mE = alias void (), void ()* @__tls_init // DARWIN-DAG: @_ZTHN1U1mE = internal alias void (), void ()* @__tls_init // CHECK-DAG: @_ZTHN1VIiE1mE = linkonce_odr alias void (), void ()* @[[V_M_INIT:[^, ]*]] // CHECK-NOT: @_ZTHN1WIiE1mE = // CHECK-DAG: @_ZTHN1XIiE1mE = linkonce_odr alias void (), void ()* @[[X_M_INIT:[^, ]*]] // CHECK-DAG: @_ZTHN1VIfE1mE = weak_odr alias void (), void ()* @[[VF_M_INIT:[^, ]*]] // CHECK-NOT: @_ZTHN1WIfE1mE = // CHECK-DAG: @_ZTHN1XIfE1mE = weak_odr alias void (), void ()* @[[XF_M_INIT:[^, ]*]] // Individual variable initialization functions: // CHECK: define {{.*}} @[[A_INIT:.*]]() // CHECK: call i32 @_Z1fv() // CHECK-NEXT: store i32 {{.*}}, i32* @a, align 4 // CHECK-LABEL: define i32 @_Z1fv() int f() { // CHECK: %[[GUARD:.*]] = load i8, i8* @_ZGVZ1fvE1n, align 1 // CHECK: %[[NEED_INIT:.*]] = icmp eq i8 %[[GUARD]], 0 // CHECK: br i1 %[[NEED_INIT]] // CHECK: %[[CALL:.*]] = call i32 @_Z1gv() // CHECK: store i32 %[[CALL]], i32* @_ZZ1fvE1n, align 4 // CHECK: store i8 1, i8* @_ZGVZ1fvE1n // CHECK: br label static thread_local int n = g(); // CHECK: load i32, i32* @_ZZ1fvE1n, align 4 return n; } // CHECK: define {{.*}} @[[C_INIT:.*]]() // LINUX: call i32* @_ZTW1b() // DARWIN: call cxx_fast_tlscc i32* @_ZTW1b() // CHECK-NEXT: load i32, i32* %{{.*}}, align 4 // CHECK-NEXT: store i32 %{{.*}}, i32* @c, align 4 // LINUX-LABEL: define weak_odr hidden i32* @_ZTW1b() // LINUX: br i1 icmp ne (void ()* @_ZTH1b, void ()* null), // not null: // LINUX: call void @_ZTH1b() // LINUX: br label // finally: // LINUX: ret i32* @b // DARWIN-LABEL: declare cxx_fast_tlscc i32* @_ZTW1b() // There is no definition of the thread wrapper on Darwin for external TLV. // CHECK: define {{.*}} @[[D_INIT:.*]]() // CHECK: call i32 @_Z1gv() // CHECK-NEXT: store i32 %{{.*}}, i32* @_ZL1d, align 4 // CHECK: define {{.*}} @[[U_M_INIT:.*]]() // CHECK: call i32 @_Z1fv() // CHECK-NEXT: store i32 %{{.*}}, i32* @_ZN1U1mE, align 4 // CHECK: define {{.*}} @[[E_INIT:.*]]() // LINUX: call i32* @_ZTWN1VIiE1mE() // DARWIN: call cxx_fast_tlscc i32* @_ZTWN1VIiE1mE() // CHECK-NEXT: load i32, i32* %{{.*}}, align 4 // LINUX: call {{.*}}* @_ZTWN1XIiE1mE() // DARWIN: call cxx_fast_tlscc {{.*}}* @_ZTWN1XIiE1mE() // CHECK: store {{.*}} @e // LINUX-LABEL: define weak_odr hidden i32* @_ZTWN1VIiE1mE() // DARWIN-LABEL: define weak_odr hidden cxx_fast_tlscc i32* @_ZTWN1VIiE1mE() // LINUX: call void @_ZTHN1VIiE1mE() // DARWIN: call cxx_fast_tlscc void @_ZTHN1VIiE1mE() // CHECK: ret i32* @_ZN1VIiE1mE // LINUX-LABEL: define weak_odr hidden i32* @_ZTWN1WIiE1mE() // DARWIN-LABEL: define weak_odr hidden cxx_fast_tlscc i32* @_ZTWN1WIiE1mE() // CHECK-NOT: call // CHECK: ret i32* @_ZN1WIiE1mE // LINUX-LABEL: define weak_odr hidden {{.*}}* @_ZTWN1XIiE1mE() // DARWIN-LABEL: define weak_odr hidden cxx_fast_tlscc {{.*}}* @_ZTWN1XIiE1mE() // LINUX: call void @_ZTHN1XIiE1mE() // DARWIN: call cxx_fast_tlscc void @_ZTHN1XIiE1mE() // CHECK: ret {{.*}}* @_ZN1XIiE1mE // LINUX: define internal void @[[VF_M_INIT]]() // DARWIN: define internal cxx_fast_tlscc void @[[VF_M_INIT]]() // LINUX-SAME: comdat($_ZN1VIfE1mE) // DARWIN-NOT: comdat // CHECK: load i8, i8* bitcast (i64* @_ZGVN1VIfE1mE to i8*) // CHECK: %[[VF_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0 // CHECK: br i1 %[[VF_M_INITIALIZED]], // need init: // CHECK: call i32 @_Z1gv() // CHECK: store i32 %{{.*}}, i32* @_ZN1VIfE1mE, align 4 // CHECK: store i64 1, i64* @_ZGVN1VIfE1mE // CHECK: br label // LINUX: define internal void @[[XF_M_INIT]]() // DARWIN: define internal cxx_fast_tlscc void @[[XF_M_INIT]]() // LINUX-SAME: comdat($_ZN1XIfE1mE) // DARWIN-NOT: comdat // CHECK: load i8, i8* bitcast (i64* @_ZGVN1XIfE1mE to i8*) // CHECK: %[[XF_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0 // CHECK: br i1 %[[XF_M_INITIALIZED]], // need init: // LINUX: call {{.*}}__cxa_thread_atexit // DARWIN: call {{.*}}_tlv_atexit // CHECK: store i64 1, i64* @_ZGVN1XIfE1mE // CHECK: br label // LINUX: declare i32 @__cxa_thread_atexit(void (i8*)*, i8*, i8*) // DARWIN: declare i32 @_tlv_atexit(void (i8*)*, i8*, i8*) // DARWIN: declare cxx_fast_tlscc i32* @_ZTWN1VIcE1mE() // LINUX: define weak_odr hidden i32* @_ZTWN1VIcE1mE() // LINUX-NOT: comdat // LINUX: br i1 icmp ne (void ()* @_ZTHN1VIcE1mE, // LINUX: call void @_ZTHN1VIcE1mE() // LINUX: ret i32* @_ZN1VIcE1mE // DARWIN: declare cxx_fast_tlscc i32* @_ZTWN1WIcE1mE() // LINUX: define weak_odr hidden i32* @_ZTWN1WIcE1mE() // LINUX-NOT: comdat // LINUX: br i1 icmp ne (void ()* @_ZTHN1WIcE1mE, // LINUX: call void @_ZTHN1WIcE1mE() // LINUX: ret i32* @_ZN1WIcE1mE // DARWIN: declare cxx_fast_tlscc {{.*}}* @_ZTWN1XIcE1mE() // LINUX: define weak_odr hidden {{.*}}* @_ZTWN1XIcE1mE() // LINUX-NOT: comdat // LINUX: br i1 icmp ne (void ()* @_ZTHN1XIcE1mE, // LINUX: call void @_ZTHN1XIcE1mE() // LINUX: ret {{.*}}* @_ZN1XIcE1mE struct S { S(); ~S(); }; struct T { ~T(); }; // CHECK-LABEL: define void @_Z8tls_dtorv() void tls_dtor() { // CHECK: load i8, i8* @_ZGVZ8tls_dtorvE1s // CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZZ8tls_dtorvE1s) // LINUX: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZZ8tls_dtorvE1s{{.*}} @__dso_handle // DARWIN: call i32 @_tlv_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZZ8tls_dtorvE1s{{.*}} @__dso_handle // CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1s static thread_local S s; // CHECK: load i8, i8* @_ZGVZ8tls_dtorvE1t // CHECK-NOT: _ZN1T // LINUX: call i32 @__cxa_thread_atexit({{.*}}@_ZN1TD1Ev {{.*}}@_ZZ8tls_dtorvE1t{{.*}} @__dso_handle // DARWIN: call i32 @_tlv_atexit({{.*}}@_ZN1TD1Ev {{.*}}@_ZZ8tls_dtorvE1t{{.*}} @__dso_handle // CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1t static thread_local T t; // CHECK: load i8, i8* @_ZGVZ8tls_dtorvE1u // CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZGRZ8tls_dtorvE1u_) // LINUX: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZGRZ8tls_dtorvE1u_{{.*}} @__dso_handle // DARWIN: call i32 @_tlv_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZGRZ8tls_dtorvE1u_{{.*}} @__dso_handle // CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1u static thread_local const S &u = S(); } // CHECK: define {{.*}} @_Z7PR15991v( int PR15991() { thread_local int n; auto l = [] { return n; }; return l(); } struct PR19254 { static thread_local int n; int f(); }; // CHECK: define {{.*}} @_ZN7PR192541fEv( int PR19254::f() { // LINUX: call void @_ZTHN7PR192541nE( // DARWIN: call cxx_fast_tlscc i32* @_ZTWN7PR192541nE( return this->n; } namespace { thread_local int anon_i{1}; } void set_anon_i() { anon_i = 2; } // LINUX-LABEL: define internal i32* @_ZTWN12_GLOBAL__N_16anon_iE() // DARWIN-LABEL: define internal cxx_fast_tlscc i32* @_ZTWN12_GLOBAL__N_16anon_iE() // LINUX: define internal void @[[V_M_INIT]]() // DARWIN: define internal cxx_fast_tlscc void @[[V_M_INIT]]() // LINUX-SAME: comdat($_ZN1VIiE1mE) // DARWIN-NOT: comdat // CHECK: load i8, i8* bitcast (i64* @_ZGVN1VIiE1mE to i8*) // CHECK: %[[V_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0 // CHECK: br i1 %[[V_M_INITIALIZED]], // need init: // CHECK: call i32 @_Z1gv() // CHECK: store i32 %{{.*}}, i32* @_ZN1VIiE1mE, align 4 // CHECK: store i64 1, i64* @_ZGVN1VIiE1mE // CHECK: br label // LINUX: define internal void @[[X_M_INIT]]() // DARWIN: define internal cxx_fast_tlscc void @[[X_M_INIT]]() // LINUX-SAME: comdat($_ZN1XIiE1mE) // DARWIN-NOT: comdat // CHECK: load i8, i8* bitcast (i64* @_ZGVN1XIiE1mE to i8*) // CHECK: %[[X_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0 // CHECK: br i1 %[[X_M_INITIALIZED]], // need init: // LINUX: call {{.*}}__cxa_thread_atexit // DARWIN: call {{.*}}_tlv_atexit // CHECK: store i64 1, i64* @_ZGVN1XIiE1mE // CHECK: br label // CHECK: define {{.*}}@[[GLOBAL_INIT:.*]]() // CHECK: call void @[[C_INIT]]() // CHECK: call void @[[E_INIT]]() // CHECK: define {{.*}}@__tls_init() // CHECK: load i8, i8* @__tls_guard // CHECK: %[[NEED_TLS_INIT:.*]] = icmp eq i8 %{{.*}}, 0 // CHECK: br i1 %[[NEED_TLS_INIT]], // init: // CHECK: store i8 1, i8* @__tls_guard // CHECK-OPT: call {}* @llvm.invariant.start.p0i8(i64 1, i8* @__tls_guard) // CHECK-NOT: call void @[[V_M_INIT]]() // CHECK: call void @[[A_INIT]]() // CHECK-NOT: call void @[[V_M_INIT]]() // CHECK: call void @[[D_INIT]]() // CHECK-NOT: call void @[[V_M_INIT]]() // CHECK: call void @[[U_M_INIT]]() // CHECK-NOT: call void @[[V_M_INIT]]() -// LIUNX: define weak_odr hidden i32* @_ZTW1a() { +// LINUX: define weak_odr hidden i32* @_ZTW1a() // DARWIN: define cxx_fast_tlscc i32* @_ZTW1a() // LINUX: call void @_ZTH1a() // DARWIN: call cxx_fast_tlscc void @_ZTH1a() // CHECK: ret i32* @a // CHECK: } // LINUX: declare extern_weak void @_ZTH1b() [[ATTR:#[0-9]+]] // LINUX-LABEL: define internal i32* @_ZTWL1d() // DARWIN-LABEL: define internal cxx_fast_tlscc i32* @_ZTWL1d() // LINUX: call void @_ZTHL1d() // DARWIN: call cxx_fast_tlscc void @_ZTHL1d() // CHECK: ret i32* @_ZL1d // LINUX-LABEL: define weak_odr hidden i32* @_ZTWN1U1mE() // DARWIN-LABEL: define cxx_fast_tlscc i32* @_ZTWN1U1mE() // LINUX: call void @_ZTHN1U1mE() // DARWIN: call cxx_fast_tlscc void @_ZTHN1U1mE() // CHECK: ret i32* @_ZN1U1mE // LINUX: attributes [[ATTR]] = { {{.+}} } Index: vendor/clang/dist-release_80/test/Driver/msp430-toolchain.c =================================================================== --- vendor/clang/dist-release_80/test/Driver/msp430-toolchain.c (revision 343192) +++ vendor/clang/dist-release_80/test/Driver/msp430-toolchain.c (revision 343193) @@ -1,78 +1,78 @@ // A basic clang -cc1 command-line, and simple environment check. // RUN: %clang %s -### -no-canonical-prefixes -target msp430 2>&1 \ // RUN: | FileCheck -check-prefix=CC1 %s // CC1: clang{{.*}} "-cc1" "-triple" "msp430" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 \ // RUN: --gcc-toolchain=%S/Inputs/basic_msp430_tree 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430 %s -// MSP430: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../bin/msp430-elf-ld" +// MSP430: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}bin{{/|\\\\}}msp430-elf-ld" // MSP430: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430" -// MSP430: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430" -// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430/crt0.o" -// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o" +// MSP430: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430" +// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430{{/|\\\\}}crt0.o" +// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430{{/|\\\\}}crtbegin.o" // MSP430: "--start-group" "-lmul_none" "-lgcc" "-lc" "-lcrt" "-lnosys" "--end-group" -// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o" -// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430/crtn.o" +// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430{{/|\\\\}}crtend.o" +// MSP430: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430{{/|\\\\}}crtn.o" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -nodefaultlibs \ // RUN: --gcc-toolchain=%S/Inputs/basic_msp430_tree 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-NO-DFT-LIB %s -// MSP430-NO-DFT-LIB: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../bin/msp430-elf-ld" +// MSP430-NO-DFT-LIB: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}bin{{/|\\\\}}msp430-elf-ld" // MSP430-NO-DFT-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430" -// MSP430-NO-DFT-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430" -// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430/crt0.o" -// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o" +// MSP430-NO-DFT-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430" +// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430{{/|\\\\}}crt0.o" +// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430{{/|\\\\}}crtbegin.o" // MSP430-NO-DFT-LIB: "--start-group" "-lmul_none" "-lgcc" "--end-group" -// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o" -// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430/crtn.o" +// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430{{/|\\\\}}crtend.o" +// MSP430-NO-DFT-LIB: "{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430{{/|\\\\}}crtn.o" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -nostartfiles \ // RUN: --gcc-toolchain=%S/Inputs/basic_msp430_tree 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-NO-START %s -// MSP430-NO-START: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../bin/msp430-elf-ld" +// MSP430-NO-START: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}bin{{/|\\\\}}msp430-elf-ld" // MSP430-NO-START: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430" -// MSP430-NO-START: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430" +// MSP430-NO-START: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430" // MSP430-NO-START: "--start-group" "-lmul_none" "-lgcc" "-lc" "-lcrt" "-lnosys" "--end-group" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -nostdlib \ // RUN: --gcc-toolchain=%S/Inputs/basic_msp430_tree 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-NO-STD-LIB %s -// MSP430-NO-STD-LIB: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../bin/msp430-elf-ld" +// MSP430-NO-STD-LIB: "{{.*}}Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}bin{{/|\\\\}}msp430-elf-ld" // MSP430-NO-STD-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430" -// MSP430-NO-STD-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../../../msp430-elf/lib/430" +// MSP430-NO-STD-LIB: "-L{{.*}}/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/../../..{{/|\\\\}}..{{/|\\\\}}msp430-elf{{/|\\\\}}lib/430" // MSP430-NO-STD-LIB: "--start-group" "-lmul_none" "-lgcc" "--end-group" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mmcu=msp430f147 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-16BIT %s // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mmcu=msp430f147 -mhwmult=auto 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-16BIT %s // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mhwmult=16bit 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-16BIT %s // MSP430-HWMult-16BIT: "--start-group" "-lmul_16" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mmcu=msp430f4783 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-32BIT %s // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mmcu=msp430f4783 -mhwmult=auto 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-32BIT %s // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mhwmult=32bit 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-32BIT %s // MSP430-HWMult-32BIT: "--start-group" "-lmul_32" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mhwmult=f5series 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-F5 %s // MSP430-HWMult-F5: "--start-group" "-lmul_f5" // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mhwmult=none 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-NONE %s // RUN: %clang %s -### -no-canonical-prefixes -target msp430 -mhwmult=none -mmcu=msp430f4783 2>&1 \ // RUN: | FileCheck -check-prefix=MSP430-HWMult-NONE %s // MSP430-HWMult-NONE: "--start-group" "-lmul_none" Index: vendor/clang/dist-release_80/test/Sema/attr-msp430.c =================================================================== --- vendor/clang/dist-release_80/test/Sema/attr-msp430.c (revision 343192) +++ vendor/clang/dist-release_80/test/Sema/attr-msp430.c (revision 343193) @@ -1,6 +1,13 @@ // RUN: %clang_cc1 -triple msp430-unknown-unknown -fsyntax-only -verify %s +__attribute__((interrupt(1))) int t; // expected-warning {{'interrupt' attribute only applies to functions}} + int i; -void f(void) __attribute__((interrupt(i))); /* expected-error {{'interrupt' attribute requires an integer constant}} */ +__attribute__((interrupt(i))) void f(void); // expected-error {{'interrupt' attribute requires an integer constant}} +__attribute__((interrupt(1, 2))) void f2(void); // expected-error {{'interrupt' attribute takes one argument}} +__attribute__((interrupt(1))) int f3(void); // expected-warning {{MSP430 'interrupt' attribute only applies to functions that have a 'void' return type}} +__attribute__((interrupt(1))) void f4(int a); // expected-warning {{MSP430 'interrupt' attribute only applies to functions that have no parameters}} +__attribute__((interrupt(64))) void f5(void); // expected-error {{'interrupt' attribute parameter 64 is out of bounds}} -void f2(void) __attribute__((interrupt(12))); +__attribute__((interrupt(0))) void f6(void); +__attribute__((interrupt(63))) void f7(void); Index: vendor/clang/dist-release_80/test/SemaObjC/call-unavailable-init-in-self.m =================================================================== --- vendor/clang/dist-release_80/test/SemaObjC/call-unavailable-init-in-self.m (revision 343192) +++ vendor/clang/dist-release_80/test/SemaObjC/call-unavailable-init-in-self.m (revision 343193) @@ -1,68 +1,86 @@ // RUN: %clang_cc1 -x objective-c -verify -fobjc-arc %s @interface NSObject + (instancetype)new; + (instancetype)alloc; +- (void)declaredInSuper; + @end +@interface NSObject (Category) + +- (void)declaredInSuperCategory; + +@end + @interface Sub: NSObject - (instancetype)init __attribute__((unavailable)); // expected-note 4 {{'init' has been explicitly marked unavailable here}} -- (void)notImplemented __attribute__((unavailable)); // expected-note {{'notImplemented' has been explicitly marked unavailable here}} +- (void)notImplemented __attribute__((unavailable)); +- (void)declaredInSuper __attribute__((unavailable)); +- (void)declaredInSuperCategory __attribute__((unavailable)); + @end @implementation Sub + (Sub *)create { return [[self alloc] init]; } + (Sub *)create2 { return [self new]; } + (Sub *)create3 { return [Sub new]; } - (instancetype) init { return self; } - (void)reportUseOfUnimplemented { - [self notImplemented]; // expected-error {{'notImplemented' is unavailable}} + [self notImplemented]; +} + +- (void)allowSuperCallUsingSelf { + [self declaredInSuper]; + [[Sub alloc] declaredInSuper]; + [self declaredInSuperCategory]; + [[Sub alloc] declaredInSuperCategory]; } @end @interface SubClassContext: Sub @end @implementation SubClassContext - (void)subClassContext { (void)[[Sub alloc] init]; // expected-error {{'init' is unavailable}} (void)[Sub new]; // expected-error {{'new' is unavailable}} } @end void unrelatedContext() { (void)[[Sub alloc] init]; // expected-error {{'init' is unavailable}} (void)[Sub new]; // expected-error {{'new' is unavailable}} } @interface X @end @interface X (Foo) -(void)meth __attribute__((unavailable)); @end @implementation X (Foo) -(void)meth {} -(void)call_it { [self meth]; } @end Index: vendor/clang/dist-release_80/test/SemaObjC/infer-availability-from-init.m =================================================================== --- vendor/clang/dist-release_80/test/SemaObjC/infer-availability-from-init.m (revision 343192) +++ vendor/clang/dist-release_80/test/SemaObjC/infer-availability-from-init.m (revision 343193) @@ -1,58 +1,58 @@ // RUN: %clang_cc1 -triple x86_64-apple-macosx-10.9 -Wunguarded-availability -fblocks -fsyntax-only -verify %s __attribute__((objc_root_class)) @interface NSObject +(instancetype)new; -(instancetype)init; @end @interface MyObject : NSObject -(instancetype)init __attribute__((unavailable)); // expected-note{{'init' has been explicitly marked unavailable here}} @end void usemyobject() { [MyObject new]; // expected-error{{'new' is unavailable}} } @interface MyOtherObject : NSObject +(instancetype)init __attribute__((unavailable)); +(instancetype)new; @end void usemyotherobject() { [MyOtherObject new]; // no error; new is overrideen. } @interface NotGoodOverride : NSObject +(instancetype)init __attribute__((unavailable)); -(instancetype)new; +(instancetype)new: (int)x; @end void usenotgoodoverride() { [NotGoodOverride new]; // no error } @interface NotNSObject +(instancetype)new; -(instancetype)init; @end @interface NotMyObject : NotNSObject -(instancetype)init __attribute__((unavailable)); @end void usenotmyobject() { [NotMyObject new]; // no error; this isn't NSObject } @interface FromSelf : NSObject --(instancetype)init __attribute__((unavailable)); // expected-note {{'init' has been explicitly marked unavailable here}} +-(instancetype)init __attribute__((unavailable)); +(FromSelf*)another_one; @end @implementation FromSelf +(FromSelf*)another_one { - [self new]; // expected-error{{'new' is unavailable}} + [self new]; } @end Index: vendor/clang/dist-release_80/test/Tooling/clang-check-mac-libcxx-fixed-compilation-db.cpp =================================================================== --- vendor/clang/dist-release_80/test/Tooling/clang-check-mac-libcxx-fixed-compilation-db.cpp (revision 343192) +++ vendor/clang/dist-release_80/test/Tooling/clang-check-mac-libcxx-fixed-compilation-db.cpp (revision 343193) @@ -1,16 +1,16 @@ // Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp $(which clang-check) %t/mock-libcxx/bin/ // RUN: cp "%s" "%t/test.cpp" -// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ - +// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin +// REQUIRES: system-darwin #include vector v;