aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/CodeGen/CodeGenFunction.cpp
AgeCommit message (Collapse)AuthorFilesLines
2022-08-24KCFI sanitizerSami Tolvanen1-0/+8
The KCFI sanitizer, enabled with `-fsanitize=kcfi`, implements a forward-edge control flow integrity scheme for indirect calls. It uses a !kcfi_type metadata node to attach a type identifier for each function and injects verification code before indirect calls. Unlike the current CFI schemes implemented in LLVM, KCFI does not require LTO, does not alter function references to point to a jump table, and never breaks function address equality. KCFI is intended to be used in low-level code, such as operating system kernels, where the existing schemes can cause undue complications because of the aforementioned properties. However, unlike the existing schemes, KCFI is limited to validating only function pointers and is not compatible with executable-only memory. KCFI does not provide runtime support, but always traps when a type mismatch is encountered. Users of the scheme are expected to handle the trap. With `-fsanitize=kcfi`, Clang emits a `kcfi` operand bundle to indirect calls, and LLVM lowers this to a known architecture-specific sequence of instructions for each callsite to make runtime patching easier for users who require this functionality. A KCFI type identifier is a 32-bit constant produced by taking the lower half of xxHash64 from a C++ mangled typename. If a program contains indirect calls to assembly functions, they must be manually annotated with the expected type identifiers to prevent errors. To make this easier, Clang generates a weak SHN_ABS `__kcfi_typeid_<function>` symbol for each address-taken function declaration, which can be used to annotate functions in assembly as long as at least one C translation unit linked into the program takes the function address. For example on AArch64, we might have the following code: ``` .c: int f(void); int (*p)(void) = f; p(); .s: .4byte __kcfi_typeid_f .global f f: ... ``` Note that X86 uses a different preamble format for compatibility with Linux kernel tooling. See the comments in `X86AsmPrinter::emitKCFITypeId` for details. As users of KCFI may need to locate trap locations for binary validation and error handling, LLVM can additionally emit the locations of traps to a `.kcfi_traps` section. Similarly to other sanitizers, KCFI checking can be disabled for a function with a `no_sanitize("kcfi")` function attribute. Relands 67504c95494ff05be2a613129110c9bcf17f6c13 with a fix for 32-bit builds. Reviewed By: nickdesaulniers, kees, joaomoreira, MaskRay Differential Revision: https://reviews.llvm.org/D119296
2022-08-24Revert "KCFI sanitizer"Sami Tolvanen1-8/+0
This reverts commit 67504c95494ff05be2a613129110c9bcf17f6c13 as using PointerEmbeddedInt to store 32 bits breaks 32-bit arm builds.
2022-08-24KCFI sanitizerSami Tolvanen1-0/+8
The KCFI sanitizer, enabled with `-fsanitize=kcfi`, implements a forward-edge control flow integrity scheme for indirect calls. It uses a !kcfi_type metadata node to attach a type identifier for each function and injects verification code before indirect calls. Unlike the current CFI schemes implemented in LLVM, KCFI does not require LTO, does not alter function references to point to a jump table, and never breaks function address equality. KCFI is intended to be used in low-level code, such as operating system kernels, where the existing schemes can cause undue complications because of the aforementioned properties. However, unlike the existing schemes, KCFI is limited to validating only function pointers and is not compatible with executable-only memory. KCFI does not provide runtime support, but always traps when a type mismatch is encountered. Users of the scheme are expected to handle the trap. With `-fsanitize=kcfi`, Clang emits a `kcfi` operand bundle to indirect calls, and LLVM lowers this to a known architecture-specific sequence of instructions for each callsite to make runtime patching easier for users who require this functionality. A KCFI type identifier is a 32-bit constant produced by taking the lower half of xxHash64 from a C++ mangled typename. If a program contains indirect calls to assembly functions, they must be manually annotated with the expected type identifiers to prevent errors. To make this easier, Clang generates a weak SHN_ABS `__kcfi_typeid_<function>` symbol for each address-taken function declaration, which can be used to annotate functions in assembly as long as at least one C translation unit linked into the program takes the function address. For example on AArch64, we might have the following code: ``` .c: int f(void); int (*p)(void) = f; p(); .s: .4byte __kcfi_typeid_f .global f f: ... ``` Note that X86 uses a different preamble format for compatibility with Linux kernel tooling. See the comments in `X86AsmPrinter::emitKCFITypeId` for details. As users of KCFI may need to locate trap locations for binary validation and error handling, LLVM can additionally emit the locations of traps to a `.kcfi_traps` section. Similarly to other sanitizers, KCFI checking can be disabled for a function with a `no_sanitize("kcfi")` function attribute. Reviewed By: nickdesaulniers, kees, joaomoreira, MaskRay Differential Revision: https://reviews.llvm.org/D119296
2022-08-04[InstrProf][attempt 2] Add new format for -fprofile-list=Ellis Hoag1-2/+11
In D130807 we added the `skipprofile` attribute. This commit changes the format so we can either `forbid` or `skip` profiling functions by adding the `noprofile` or `skipprofile` attributes, respectively. The behavior of the original format remains unchanged. Also, add the `skipprofile` attribute when using `-fprofile-function-groups`. This was originally landed as https://reviews.llvm.org/D130808 but was reverted due to a Windows test failure. Differential Revision: https://reviews.llvm.org/D131195
2022-08-04Revert "[InstrProf] Add new format for -fprofile-list="Nico Weber1-11/+2
This reverts commit b692312ca432d9a379f67a8d83177a6f1722baaa. Breaks tests on Windows, see https://reviews.llvm.org/D130808#3699952
2022-08-04[InstrProf] Add new format for -fprofile-list=Ellis Hoag1-2/+11
In D130807 we added the `skipprofile` attribute. This commit changes the format so we can either `forbid` or `skip` profiling functions by adding the `noprofile` or `skipprofile` attributes, respectively. The behavior of the original format remains unchanged. Also, add the `skipprofile` attribute when using `-fprofile-function-groups`. Reviewed By: phosek Differential Revision: https://reviews.llvm.org/D130808
2022-07-27[clang] Implement ElaboratedType sugaring for types written bareMatheus Izvekov1-1/+4
Without this patch, clang will not wrap in an ElaboratedType node types written without a keyword and nested name qualifier, which goes against the intent that we should produce an AST which retains enough details to recover how things are written. The lack of this sugar is incompatible with the intent of the type printer default policy, which is to print types as written, but to fall back and print them fully qualified when they are desugared. An ElaboratedTypeLoc without keyword / NNS uses no storage by itself, but still requires pointer alignment due to pre-existing bug in the TypeLoc buffer handling. --- Troubleshooting list to deal with any breakage seen with this patch: 1) The most likely effect one would see by this patch is a change in how a type is printed. The type printer will, by design and default, print types as written. There are customization options there, but not that many, and they mainly apply to how to print a type that we somehow failed to track how it was written. This patch fixes a problem where we failed to distinguish between a type that was written without any elaborated-type qualifiers, such as a 'struct'/'class' tags and name spacifiers such as 'std::', and one that has been stripped of any 'metadata' that identifies such, the so called canonical types. Example: ``` namespace foo { struct A {}; A a; }; ``` If one were to print the type of `foo::a`, prior to this patch, this would result in `foo::A`. This is how the type printer would have, by default, printed the canonical type of A as well. As soon as you add any name qualifiers to A, the type printer would suddenly start accurately printing the type as written. This patch will make it print it accurately even when written without qualifiers, so we will just print `A` for the initial example, as the user did not really write that `foo::` namespace qualifier. 2) This patch could expose a bug in some AST matcher. Matching types is harder to get right when there is sugar involved. For example, if you want to match a type against being a pointer to some type A, then you have to account for getting a type that is sugar for a pointer to A, or being a pointer to sugar to A, or both! Usually you would get the second part wrong, and this would work for a very simple test where you don't use any name qualifiers, but you would discover is broken when you do. The usual fix is to either use the matcher which strips sugar, which is annoying to use as for example if you match an N level pointer, you have to put N+1 such matchers in there, beginning to end and between all those levels. But in a lot of cases, if the property you want to match is present in the canonical type, it's easier and faster to just match on that... This goes with what is said in 1), if you want to match against the name of a type, and you want the name string to be something stable, perhaps matching on the name of the canonical type is the better choice. 3) This patch could expose a bug in how you get the source range of some TypeLoc. For some reason, a lot of code is using getLocalSourceRange(), which only looks at the given TypeLoc node. This patch introduces a new, and more common TypeLoc node which contains no source locations on itself. This is not an inovation here, and some other, more rare TypeLoc nodes could also have this property, but if you use getLocalSourceRange on them, it's not going to return any valid locations, because it doesn't have any. The right fix here is to always use getSourceRange() or getBeginLoc/getEndLoc which will dive into the inner TypeLoc to get the source range if it doesn't find it on the top level one. You can use getLocalSourceRange if you are really into micro-optimizations and you have some outside knowledge that the TypeLocs you are dealing with will always include some source location. 4) Exposed a bug somewhere in the use of the normal clang type class API, where you have some type, you want to see if that type is some particular kind, you try a `dyn_cast` such as `dyn_cast<TypedefType>` and that fails because now you have an ElaboratedType which has a TypeDefType inside of it, which is what you wanted to match. Again, like 2), this would usually have been tested poorly with some simple tests with no qualifications, and would have been broken had there been any other kind of type sugar, be it an ElaboratedType or a TemplateSpecializationType or a SubstTemplateParmType. The usual fix here is to use `getAs` instead of `dyn_cast`, which will look deeper into the type. Or use `getAsAdjusted` when dealing with TypeLocs. For some reason the API is inconsistent there and on TypeLocs getAs behaves like a dyn_cast. 5) It could be a bug in this patch perhaps. Let me know if you need any help! Signed-off-by: Matheus Izvekov <mizvekov@gmail.com> Differential Revision: https://reviews.llvm.org/D112374
2022-07-14Revert "[clang] Implement ElaboratedType sugaring for types written bare"Jonas Devlieghere1-4/+1
This reverts commit 7c51f02effdbd0d5e12bfd26f9c3b2ab5687c93f because it stills breaks the LLDB tests. This was re-landed without addressing the issue or even agreement on how to address the issue. More details and discussion in https://reviews.llvm.org/D112374.
2022-07-15[clang] Implement ElaboratedType sugaring for types written bareMatheus Izvekov1-1/+4
Without this patch, clang will not wrap in an ElaboratedType node types written without a keyword and nested name qualifier, which goes against the intent that we should produce an AST which retains enough details to recover how things are written. The lack of this sugar is incompatible with the intent of the type printer default policy, which is to print types as written, but to fall back and print them fully qualified when they are desugared. An ElaboratedTypeLoc without keyword / NNS uses no storage by itself, but still requires pointer alignment due to pre-existing bug in the TypeLoc buffer handling. --- Troubleshooting list to deal with any breakage seen with this patch: 1) The most likely effect one would see by this patch is a change in how a type is printed. The type printer will, by design and default, print types as written. There are customization options there, but not that many, and they mainly apply to how to print a type that we somehow failed to track how it was written. This patch fixes a problem where we failed to distinguish between a type that was written without any elaborated-type qualifiers, such as a 'struct'/'class' tags and name spacifiers such as 'std::', and one that has been stripped of any 'metadata' that identifies such, the so called canonical types. Example: ``` namespace foo { struct A {}; A a; }; ``` If one were to print the type of `foo::a`, prior to this patch, this would result in `foo::A`. This is how the type printer would have, by default, printed the canonical type of A as well. As soon as you add any name qualifiers to A, the type printer would suddenly start accurately printing the type as written. This patch will make it print it accurately even when written without qualifiers, so we will just print `A` for the initial example, as the user did not really write that `foo::` namespace qualifier. 2) This patch could expose a bug in some AST matcher. Matching types is harder to get right when there is sugar involved. For example, if you want to match a type against being a pointer to some type A, then you have to account for getting a type that is sugar for a pointer to A, or being a pointer to sugar to A, or both! Usually you would get the second part wrong, and this would work for a very simple test where you don't use any name qualifiers, but you would discover is broken when you do. The usual fix is to either use the matcher which strips sugar, which is annoying to use as for example if you match an N level pointer, you have to put N+1 such matchers in there, beginning to end and between all those levels. But in a lot of cases, if the property you want to match is present in the canonical type, it's easier and faster to just match on that... This goes with what is said in 1), if you want to match against the name of a type, and you want the name string to be something stable, perhaps matching on the name of the canonical type is the better choice. 3) This patch could exposed a bug in how you get the source range of some TypeLoc. For some reason, a lot of code is using getLocalSourceRange(), which only looks at the given TypeLoc node. This patch introduces a new, and more common TypeLoc node which contains no source locations on itself. This is not an inovation here, and some other, more rare TypeLoc nodes could also have this property, but if you use getLocalSourceRange on them, it's not going to return any valid locations, because it doesn't have any. The right fix here is to always use getSourceRange() or getBeginLoc/getEndLoc which will dive into the inner TypeLoc to get the source range if it doesn't find it on the top level one. You can use getLocalSourceRange if you are really into micro-optimizations and you have some outside knowledge that the TypeLocs you are dealing with will always include some source location. 4) Exposed a bug somewhere in the use of the normal clang type class API, where you have some type, you want to see if that type is some particular kind, you try a `dyn_cast` such as `dyn_cast<TypedefType>` and that fails because now you have an ElaboratedType which has a TypeDefType inside of it, which is what you wanted to match. Again, like 2), this would usually have been tested poorly with some simple tests with no qualifications, and would have been broken had there been any other kind of type sugar, be it an ElaboratedType or a TemplateSpecializationType or a SubstTemplateParmType. The usual fix here is to use `getAs` instead of `dyn_cast`, which will look deeper into the type. Or use `getAsAdjusted` when dealing with TypeLocs. For some reason the API is inconsistent there and on TypeLocs getAs behaves like a dyn_cast. 5) It could be a bug in this patch perhaps. Let me know if you need any help! Signed-off-by: Matheus Izvekov <mizvekov@gmail.com> Differential Revision: https://reviews.llvm.org/D112374
2022-07-14[InstrProf] Add options to profile function groupsEllis Hoag1-1/+1
Add two options, `-fprofile-function-groups=N` and `-fprofile-selected-function-group=i` used to partition functions into `N` groups and only instrument the functions in group `i`. Similar options were added to xray in https://reviews.llvm.org/D87953 and the goal is the same; to reduce instrumented size overhead by spreading the overhead across multiple builds. Raw profiles from different groups can be added like normal using the `llvm-profdata merge` command. Reviewed By: ianlevesque Differential Revision: https://reviews.llvm.org/D129594
2022-07-13Revert "[clang] Implement ElaboratedType sugaring for types written bare"Jonas Devlieghere1-4/+1
This reverts commit bdc6974f92304f4ed542241b9b89ba58ba6b20aa because it breaks all the LLDB tests that import the std module. import-std-module/array.TestArrayFromStdModule.py import-std-module/deque-basic.TestDequeFromStdModule.py import-std-module/deque-dbg-info-content.TestDbgInfoContentDequeFromStdModule.py import-std-module/forward_list.TestForwardListFromStdModule.py import-std-module/forward_list-dbg-info-content.TestDbgInfoContentForwardListFromStdModule.py import-std-module/list.TestListFromStdModule.py import-std-module/list-dbg-info-content.TestDbgInfoContentListFromStdModule.py import-std-module/queue.TestQueueFromStdModule.py import-std-module/stack.TestStackFromStdModule.py import-std-module/vector.TestVectorFromStdModule.py import-std-module/vector-bool.TestVectorBoolFromStdModule.py import-std-module/vector-dbg-info-content.TestDbgInfoContentVectorFromStdModule.py import-std-module/vector-of-vectors.TestVectorOfVectorsFromStdModule.py https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/45301/
2022-07-13[clang] Implement ElaboratedType sugaring for types written bareMatheus Izvekov1-1/+4
Without this patch, clang will not wrap in an ElaboratedType node types written without a keyword and nested name qualifier, which goes against the intent that we should produce an AST which retains enough details to recover how things are written. The lack of this sugar is incompatible with the intent of the type printer default policy, which is to print types as written, but to fall back and print them fully qualified when they are desugared. An ElaboratedTypeLoc without keyword / NNS uses no storage by itself, but still requires pointer alignment due to pre-existing bug in the TypeLoc buffer handling. Signed-off-by: Matheus Izvekov <mizvekov@gmail.com> Differential Revision: https://reviews.llvm.org/D112374
2022-07-12[X86] initial -mfunction-return=thunk-extern supportNick Desaulniers1-0/+14
Adds support for: * `-mfunction-return=<value>` command line flag, and * `__attribute__((function_return("<value>")))` function attribute Where the supported <value>s are: * keep (disable) * thunk-extern (enable) thunk-extern enables clang to change ret instructions into jmps to an external symbol named __x86_return_thunk, implemented as a new MachineFunctionPass named "x86-return-thunks", keyed off the new IR attribute fn_ret_thunk_extern. The symbol __x86_return_thunk is expected to be provided by the runtime the compiled code is linked against and is not defined by the compiler. Enabling this option alone doesn't provide mitigations without corresponding definitions of __x86_return_thunk! This new MachineFunctionPass is very similar to "x86-lvi-ret". The <value>s "thunk" and "thunk-inline" are currently unsupported. It's not clear yet that they are necessary: whether the thunk pattern they would emit is beneficial or used anywhere. Should the <value>s "thunk" and "thunk-inline" become necessary, x86-return-thunks could probably be merged into x86-retpoline-thunks which has pre-existing machinery for emitting thunks (which could be used to implement the <value> "thunk"). Has been found to build+boot with corresponding Linux kernel patches. This helps the Linux kernel mitigate RETBLEED. * CVE-2022-23816 * CVE-2022-28693 * CVE-2022-29901 See also: * "RETBLEED: Arbitrary Speculative Code Execution with Return Instructions." * AMD SECURITY NOTICE AMD-SN-1037: AMD CPU Branch Type Confusion * TECHNICAL GUIDANCE FOR MITIGATING BRANCH TYPE CONFUSION REVISION 1.0 2022-07-12 * Return Stack Buffer Underflow / Return Stack Buffer Underflow / CVE-2022-29901, CVE-2022-28693 / INTEL-SA-00702 SystemZ may eventually want to support "thunk-extern" and "thunk"; both options are used by the Linux kernel's CONFIG_EXPOLINE. This functionality has been available in GCC since the 8.1 release, and was backported to the 7.3 release. Many thanks for folks that provided discrete review off list due to the embargoed nature of this hardware vulnerability. Many Bothans died to bring us this information. Link: https://www.youtube.com/watch?v=IF6HbCKQHK8 Link: https://github.com/llvm/llvm-project/issues/54404 Link: https://gcc.gnu.org/legacy-ml/gcc-patches/2018-01/msg01197.html Link: https://www.intel.com/content/www/us/en/developer/articles/technical/software-security-guidance/advisory-guidance/return-stack-buffer-underflow.html Link: https://arstechnica.com/information-technology/2022/07/intel-and-amd-cpus-vulnerable-to-a-new-speculative-execution-attack/?comments=1 Link: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ce114c866860aa9eae3f50974efc68241186ba60 Link: https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00702.html Link: https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00707.html Reviewed By: aaron.ballman, craig.topper Differential Revision: https://reviews.llvm.org/D129572
2022-06-27[ubsan] Using metadata instead of prologue data for function sanitizerYuanfang Chen1-29/+7
Information in the function `Prologue Data` is intentionally opaque. When a function with `Prologue Data` is duplicated. The self (global value) references inside `Prologue Data` is still pointing to the original function. This may cause errors like `fatal error: error in backend: Cannot represent a difference across sections`. This patch detaches the information from function `Prologue Data` and attaches it to a function metadata node. This and D116130 fix https://github.com/llvm/llvm-project/issues/49689. Reviewed By: pcc Differential Revision: https://reviews.llvm.org/D115844
2022-06-24[HIP] add -fhip-kernel-arg-nameYaxun (Sam) Liu1-7/+10
Add option -fhip-kernel-arg-name to emit kernel argument name metadata, which is needed for certain HIP applications. Reviewed by: Artem Belevich, Fangrui Song, Brian Sumner Differential Revision: https://reviews.llvm.org/D128022
2022-06-22Fix interaction of pragma FENV_ACCESS with other pragmasSerge Pavlov1-6/+6
Previously `#pragma STDC FENV_ACCESS ON` always set dynamic rounding mode and strict exception handling. It is not correct in the presence of other pragmas that also modify rounding mode and exception handling. For example, the effect of previous pragma FENV_ROUND could be cancelled, which is not conformant with the C standard. Also `#pragma STDC FENV_ACCESS OFF` turned off only FEnvAccess flag, leaving rounding mode and exception handling unchanged, which is incorrect in general case. Concrete rounding and exception mode depend on a combination of several factors like various pragmas and command-line options. During the review of this patch an idea was proposed that the semantic actions associated with such pragmas should only set appropriate flags. Actual rounding mode and exception handling should be calculated taking into account the state of all relevant options. In such implementation the pragma FENV_ACCESS should not override properties set by other pragmas but should set them if such setting is absent. To implement this approach the following main changes are made: - Field `FPRoundingMode` is removed from `LangOptions`. Actually there are no options that set it to arbitrary rounding mode, the choice was only `dynamic` or `tonearest`. Instead, a new boolean flag `RoundingMath` is added, with the same meaning as the corresponding command-line option. - Type `FPExceptionModeKind` now has possible value `FPE_Default`. It does not represent any particular exception mode but indicates that such mode was not set and default value should be used. It allows to distinguish the case: { #pragma STDC FENV_ACCESS ON ... } where the pragma must set FPE_Strict, from the case: { #pragma clang fp exceptions(ignore) #pragma STDC FENV_ACCESS ON ... } where exception mode should remain `FPE_Ignore`. - Class `FPOptions` has now methods `getRoundingMode` and `getExceptionMode`, which calculates the respective properties from other specified FP properties. - Class `LangOptions` has now methods `getDefaultRoundingMode` and `getDefaultExceptionMode`, which calculates default modes from the specified options and should be used instead of `getRoundingMode` and `getFPExceptionMode` of the same class. Differential Revision: https://reviews.llvm.org/D126364
2022-06-20[clang] Don't use Optional::getValue (NFC)Kazu Hirata1-2/+1
2022-05-19[clang] Fix __has_builtinYaxun (Sam) Liu1-9/+6
Fix __has_builtin to return 1 only if the requested target features of a builtin are enabled by refactoring the code for checking required target features of a builtin and use it in evaluation of __has_builtin. Reviewed by: Artem Belevich Differential Revision: https://reviews.llvm.org/D125829
2022-04-08Reland "[MTE] Add -fsanitize=memtag* and friends."Mitch Phillips1-1/+1
Differential Revision: https://reviews.llvm.org/D118948
2022-04-08Revert "[MTE] Add -fsanitize=memtag* and friends."Aaron Ballman1-1/+1
This reverts commit 8aa1490513f111afd407d87c3f07d26f65c8a686. Broke testing: https://lab.llvm.org/buildbot/#/builders/109/builds/36233
2022-04-08[MTE] Add -fsanitize=memtag* and friends.Mitch Phillips1-1/+1
Currently, enablement of heap MTE on Android is specified by an ELF note, which signals to the linker to enable heap MTE. This change allows -fsanitize=memtag-heap to synthesize these notes, rather than adding them through the build system. We need to extend this feature to also signal the linker to do special work for MTE globals (in future) and MTE stack (currently implemented in the toolchain, but not implemented in the loader). Current Android uses a non-backwards-compatible ELF note, called ".note.android.memtag". Stack MTE is an ABI break anyway, so we don't mind that we won't be able to run executables with stack MTE on Android 11/12 devices. The current expectation is to support the verbiage used by Android, in that "SYNC" means MTE Synchronous mode, and "ASYNC" effectively means "fast", using the Kernel auto-upgrade feature that allows hardware-specific and core-specific configuration as to whether "ASYNC" would end up being Asynchronous, Asymmetric, or Synchronous on that particular core, whichever has a reasonable performance delta. Of course, this is platform and loader-specific. Differential Revision: https://reviews.llvm.org/D118948
2022-03-29[X86][regcall] Support passing / returning structuresPhoebe Wang1-0/+3
Currently, the regcall calling conversion in Clang doesn't match with ICC when passing / returning structures. https://godbolt.org/z/axxKMKrW7 This patch tries to fix the problem to match with ICC. Reviewed By: LuoYuanke Differential Revision: https://reviews.llvm.org/D122104
2022-03-24Fix a crash with variably-modified parameter types in a naked functionAaron Ballman1-16/+15
Naked functions have no prolog, so it's not valid to emit prolog code to evaluate the variably-modified type. This fixes Issue 50541.
2022-03-23[NFC] Replace a not-null-check && isa with isa_and_nonnullErich Keane1-1/+2
2022-03-18Use llvm::append_range instead of push_back loops where applicable. NFCI.Benjamin Kramer1-5/+3
2022-03-17[CodeGen] Avoid some pointer element type accessesNikita Popov1-1/+1
2022-03-16[Attr] Fix a btf_type_tag AST generationYonghong Song1-0/+1
Current ASTContext.getAttributedType() takes attribute kind, ModifiedType and EquivType as the hash to decide whether an AST node has been generated or note. But this is not enough for btf_type_tag as the attribute might have the same ModifiedType and EquivType, but still have different string associated with attribute. For example, for a data structure like below, struct map_value { int __attribute__((btf_type_tag("tag1"))) __attribute__((btf_type_tag("tag3"))) *a; int __attribute__((btf_type_tag("tag2"))) __attribute__((btf_type_tag("tag4"))) *b; }; The current ASTContext.getAttributedType() will produce an AST similar to below: struct map_value { int __attribute__((btf_type_tag("tag1"))) __attribute__((btf_type_tag("tag3"))) *a; int __attribute__((btf_type_tag("tag1"))) __attribute__((btf_type_tag("tag3"))) *b; }; and this is incorrect. It is very difficult to use the current AttributedType as it is hard to get the tag information. To fix the problem, this patch introduced BTFTagAttributedType which is similar to AttributedType in many ways but with an additional BTFTypeTagAttr. The tag itself can be retrieved with BTFTypeTagAttr. With the new BTFTagAttributed type, the debuginfo code can be greatly simplified compared to previous TypeLoc based approach. Differential Revision: https://reviews.llvm.org/D120296
2022-03-16[Clang] Allow "ext_vector_type" applied to BooleansSimon Moll1-0/+16
This is the `ext_vector_type` alternative to D81083. This patch extends Clang to allow 'bool' as a valid vector element type (attribute ext_vector_type) in C/C++. This is intended as the canonical type for SIMD masks and facilitates clean vector intrinsic declarations. Vectors of i1 are supported on IR level and below down to many SIMD ISAs, such as AVX512, ARM SVE (fixed vector length) and the VE target (NEC SX-Aurora TSUBASA). The RFC on cfe-dev: https://lists.llvm.org/pipermail/cfe-dev/2020-May/065434.html Reviewed By: erichkeane Differential Revision: https://reviews.llvm.org/D88905
2022-03-01[SanitizerBounds] Add support for NoSanitizeBounds functionTong Zhang1-0/+4
Currently adding attribute no_sanitize("bounds") isn't disabling -fsanitize=local-bounds (also enabled in -fsanitize=bounds). The Clang frontend handles fsanitize=array-bounds which can already be disabled by no_sanitize("bounds"). However, instrumentation added by the BoundsChecking pass in the middle-end cannot be disabled by the attribute. The fix is very similar to D102772 that added the ability to selectively disable sanitizer pass on certain functions. In this patch, if no_sanitize("bounds") is provided, an additional function attribute (NoSanitizeBounds) is attached to IR to let the BoundsChecking pass know we want to disable local-bounds checking. In order to support this feature, the IR is extended (similar to D102772) to make Clang able to preserve the information and let BoundsChecking pass know bounds checking is disabled for certain function. Reviewed By: melver Differential Revision: https://reviews.llvm.org/D119816
2022-02-22[clang] Remove Address::deprecated() calls in CodeGenFunction.cppArthur Eubanks1-3/+4
2022-02-18[asan] Add support for disable_sanitizer_instrumentation attributeAlexander Potapenko1-15/+16
For ASan this will effectively serve as a synonym for __attribute__((no_sanitize("address"))). Adding the disable_sanitizer_instrumentation to functions will drop the sanitize_XXX attributes on the IR level. This is the third reland of https://reviews.llvm.org/D114421. Now that TSan test is fixed (https://reviews.llvm.org/D120050) there should be no deadlocks. Differential Revision: https://reviews.llvm.org/D120055
2022-02-17[CodeGen] Rename deprecated Address constructorNikita Popov1-6/+6
To make uses of the deprecated constructor easier to spot, and to ensure that no new uses are introduced, rename it to Address::deprecated(). While doing the rename, I've filled in element types in cases where it was relatively obvious, but we're still left with 135 calls to the deprecated constructor.
2022-02-15Revert "[asan] Add support for disable_sanitizer_instrumentation attribute"Alexander Potapenko1-16/+15
This reverts commit dd145f953db3dafbc019f1d3783bb4f09a28af92. https://reviews.llvm.org/D119726, like https://reviews.llvm.org/D114421, still causes TSan to fail, see https://lab.llvm.org/buildbot/#/builders/70/builds/18020 Differential Revision: https://reviews.llvm.org/D119838
2022-02-15[asan] Add support for disable_sanitizer_instrumentation attributeAlexander Potapenko1-14/+16
For ASan this will effectively serve as a synonym for __attribute__((no_sanitize("address"))) This is a reland of https://reviews.llvm.org/D114421 Reviewed By: melver, eugenis Differential Revision: https://reviews.llvm.org/D119726
2022-02-08[X86] Implement -fzero-call-used-regs optionBill Wendling1-0/+4
The "-fzero-call-used-regs" option tells the compiler to zero out certain registers before the function returns. It's also available as a function attribute: zero_call_used_regs. The two upper categories are: - "used": Zero out used registers. - "all": Zero out all registers, whether used or not. The individual options are: - "skip": Don't zero out any registers. This is the default. - "used": Zero out all used registers. - "used-arg": Zero out used registers that are used for arguments. - "used-gpr": Zero out used registers that are GPRs. - "used-gpr-arg": Zero out used GPRs that are used as arguments. - "all": Zero out all registers. - "all-arg": Zero out all registers used for arguments. - "all-gpr": Zero out all GPRs. - "all-gpr-arg": Zero out all GPRs used for arguments. This is used to help mitigate Return-Oriented Programming exploits. Reviewed By: nickdesaulniers Differential Revision: https://reviews.llvm.org/D110869
2022-01-20[clang-cl] Support the /HOTPATCH flagAlexandre Ganea1-0/+7
This patch adds support for the MSVC /HOTPATCH flag: https://docs.microsoft.com/sv-se/cpp/build/reference/hotpatch-create-hotpatchable-image?view=msvc-170&viewFallbackFrom=vs-2019 The flag is translated to a new -fms-hotpatch flag, which in turn adds a 'patchable-function' attribute for each function in the TU. This is then picked up by the PatchableFunction pass which would generate a TargetOpcode::PATCHABLE_OP of minsize = 2 (which means the target instruction must resolve to at least two bytes). TargetOpcode::PATCHABLE_OP is only implemented for x86/x64. When targetting ARM/ARM64, /HOTPATCH isn't required (instructions are always 2/4 bytes and suitable for hotpatching). Additionally, when using /Z7, we generate a 'hot patchable' flag in the CodeView debug stream, in the S_COMPILE3 record. This flag is then picked up by LLD (or link.exe) and is used in conjunction with the linker /FUNCTIONPADMIN flag to generate extra space before each function, to accommodate for live patching long jumps. Please see: https://github.com/llvm/llvm-project/blob/d703b922961e0d02a5effdd4bfbb23ad50a3cc9f/lld/COFF/Writer.cpp#L1298 The outcome is that we can finally use Live++ or Recode along with clang-cl. NOTE: It seems that MSVC cl.exe always enables /HOTPATCH on x64 by default, although if we did the same I thought we might generate sub-optimal code (if this flag was active by default). Additionally, MSVC always generates a .debug$S section and a S_COMPILE3 record, which Clang doesn't do without /Z7. Therefore, the following MSVC command-line "cl /c file.cpp" would have to be written with Clang such as "clang-cl /c file.cpp /HOTPATCH /Z7" in order to obtain the same result. Depends on D43002, D80833 and D81301 for the full feature. Differential Revision: https://reviews.llvm.org/D116511
2022-01-12[clang][CodeGen][UBSan] VLA size checking for unsigned integer parameterAdam Magier1-12/+16
The code generation for the UBSan VLA size check was qualified by a con- dition that the parameter must be a signed integer, however the C spec does not make any distinction that only signed integer parameters can be used to declare a VLA, only qualifying that it must be greater than zero if it is not a constant. Reviewed By: rjmccall Differential Revision: https://reviews.llvm.org/D116048
2022-01-11[CodeGen] Avoid deprecated Address constructorNikita Popov1-0/+1
2022-01-09[clang] Use true/false instead of 1/0 (NFC)Kazu Hirata1-2/+2
Identified with modernize-use-bool-literals.
2021-12-29[clang] Use nullptr instead of 0 or NULL (NFC)Kazu Hirata1-3/+3
Identified with modernize-use-nullptr.
2021-12-23[CodeGen] Avoid pointer element type access when creating LValueNikita Popov1-2/+2
This required fixing two places that were passing the pointer type rather than the expected pointee type to the method.
2021-12-21[CodeGen] Avoid some pointer element type accessesNikita Popov1-1/+2
This avoids some pointer element type accesses when compiling C++ code.
2021-12-20Reland "[AST] Add UsingType: a sugar type for types found via UsingDecl"Sam McCall1-0/+1
This reverts commit cc56c66f27e131b914082d3bd21180646e842e9a. Fixed a bad assertion, the target of a UsingShadowDecl must not have *local* qualifiers, but it can be a typedef whose underlying type is qualified.
2021-12-20Revert "[AST] Add UsingType: a sugar type for types found via UsingDecl"Sam McCall1-1/+0
This reverts commit e1600db19d6303f84b995acb9340459694e06ea9. Breaks sanitizer tests, at least on windows: https://lab.llvm.org/buildbot/#/builders/127/builds/21592/steps/4/logs/stdio
2021-12-20[AST] Add UsingType: a sugar type for types found via UsingDeclSam McCall1-0/+1
Currently there's no way to find the UsingDecl that a typeloc found its underlying type through. Compare to DeclRefExpr::getFoundDecl(). Design decisions: - a sugar type, as there are many contexts this type of use may appear in - UsingType is a leaf like TypedefType, the underlying type has no TypeLoc - not unified with UnresolvedUsingType: a single name is appealing, but being sometimes-sugar is often fiddly. - not unified with TypedefType: the UsingShadowDecl is not a TypedefNameDecl or even a TypeDecl, and users think of these differently. - does not cover other rarer aliases like objc @compatibility_alias, in order to be have a concrete API that's easy to understand. - implicitly desugared by the hasDeclaration ASTMatcher, to avoid breaking existing patterns and following the precedent of ElaboratedType. Scope: - This does not cover types associated with template names introduced by using declarations. A future patch should introduce a sugar TemplateName variant for this. (CTAD deduced types fall under this) - There are enough AST matchers to fix the in-tree clang-tidy tests and probably any other matchers, though more may be useful later. Caveats: - This changes a fairly common pattern in the AST people may depend on matching. Previously, typeLoc(loc(recordType())) matched whether a struct was referred to by its original scope or introduced via using-decl. Now, the using-decl case is not matched, and needs a separate matcher. This is similar to the case of typedefs but nevertheless both adds complexity and breaks existing code. Differential Revision: https://reviews.llvm.org/D114251
2021-12-17[CodeGen] Fix element type for sret argumentNikita Popov1-1/+1
Fix a mistake in 9bf917394eba3ba4df77cc17690c6d04f4e9d57f: sret arguments use ConvertType, not ConvertTypeForMem, see the handling in CodeGenTypes::GetFunctionType(). This fixes fp-matrix-pragma.c on s390x.
2021-12-17[CodeGen] Avoid more pointer element type accessesNikita Popov1-1/+2
2021-12-16[clang] Cleanup unneeded Function nullptr checks [NFC]Mike Rice1-30/+26
Add an assert and avoid unneeded checks of Fn in CodeGenFunction::GenerateCode. Differential Revision: https://reviews.llvm.org/D115817
2021-12-10Revert "[asan] Add support for disable_sanitizer_instrumentation attribute"Andrew Browne1-16/+14
This reverts commit 2b554920f11c8b763cd9ed9003f4e19b919b8e1f. This change causes tsan test timeout on x86_64-linux-autoconf. The timeout can be reproduced by: git clone https://github.com/llvm/llvm-zorg.git BUILDBOT_CLOBBER= BUILDBOT_REVISION=eef8f3f85679c5b1ae725bade1c23ab7bb6b924f llvm-zorg/zorg/buildbot/builders/sanitizers/buildbot_standard.sh
2021-12-10[asan] Add support for disable_sanitizer_instrumentation attributeAlexander Potapenko1-14/+16
For ASan this will effectively serve as a synonym for __attribute__((no_sanitize("address"))) Differential Revision: https://reviews.llvm.org/D114421