Skip to content

Commit d7b499d

Browse files
authored
Fix CUDA_PERROR_EXIT and print failing expression (PaddlePaddle#446)
`CUDA_PERROR_EXIT ` can lead to incorrect usage (see e.g. [this description](https://www.cs.technion.ac.il/users/yechiel/c++-faq/macros-with-if.html)) because it contains an incomplete `if` expression. Consider: ``` if (condition) CUDA_PERROR_EXIT(cudaFree(x)) else free(x); ``` The author of the code forgot to add a semicolon after the macro. In that case, the `else` will bind to the `if` inside the macro definition, leading to code that the author did not intend or expect. It the author does use a semicolon, the code will not compile, which is awkward. The change adds a `do while` around the `if`, which always requires a semicolon. This PR also adds the text of the failing expression to the printed error message.
1 parent 310ed81 commit d7b499d

File tree

1 file changed

+6
-5
lines changed
  • tools/util/include/cutlass/util

1 file changed

+6
-5
lines changed

tools/util/include/cutlass/util/debug.h

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,17 +80,18 @@
8080
* \return The CUDA error.
8181
*/
8282
__host__ CUTLASS_DEVICE cudaError_t cuda_perror_impl(cudaError_t error,
83+
const char* expression,
8384
const char* filename,
8485
int line) {
8586
(void)filename;
8687
(void)line;
8788
if (error) {
8889
#if !defined(__CUDA_ARCH__)
8990
fprintf(
90-
stderr, "CUDA error %d [%s, %d]: %s\n", error, filename, line, cudaGetErrorString(error));
91+
stderr, "CUDA error %d [%s, %d] in expression '%s': %s\n", error, filename, line, expression, cudaGetErrorString(error));
9192
fflush(stderr);
9293
#else
93-
printf("CUDA error %d [%s, %d]\n", error, filename, line);
94+
printf("CUDA error %d [%s, %d] in expression '%s'\n", error, filename, line, expression);
9495
#endif
9596
}
9697
return error;
@@ -100,17 +101,17 @@ __host__ CUTLASS_DEVICE cudaError_t cuda_perror_impl(cudaError_t error,
100101
* \brief Perror macro
101102
*/
102103
#ifndef CUDA_PERROR
103-
#define CUDA_PERROR(e) cuda_perror_impl((cudaError_t)(e), __FILE__, __LINE__)
104+
#define CUDA_PERROR(e) cuda_perror_impl((cudaError_t)(e), #e, __FILE__, __LINE__)
104105
#endif
105106

106107
/**
107108
* \brief Perror macro with exit
108109
*/
109110
#ifndef CUDA_PERROR_EXIT
110111
#define CUDA_PERROR_EXIT(e) \
111-
if (cuda_perror_impl((cudaError_t)(e), __FILE__, __LINE__)) { \
112+
do { if (cuda_perror_impl((cudaError_t)(e), #e, __FILE__, __LINE__)) { \
112113
exit(1); \
113-
}
114+
} } while (0)
114115
#endif
115116

116117
/**

0 commit comments

Comments
 (0)