[clang] [Clang] Add GCC's __builtin_stack_address() to Clang. (PR #121332)

via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 2 02:03:25 PST 2025


================
@@ -4782,6 +4782,30 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
     Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
     return RValue::get(Builder.CreateCall(F, Depth));
   }
+  case Builtin::BI__builtin_stack_address: {
+    IntegerType *SPRegType;
+    StringRef SPRegName;
+    switch (getTarget().getTriple().getArch()) {
+    case Triple::x86:
+      SPRegType = Int32Ty;
+      SPRegName = "esp";
+      break;
+    case Triple::x86_64:
+      SPRegType = Int64Ty;
+      SPRegName = "rsp";
+      break;
+    default:
+      llvm_unreachable("Intrinsic __builtin_stack_address is not supported for "
+                       "the target architecture");
+    }
----------------
aalhwc wrote:

> The compiler shouldn't crash just because someone used an attribute on a platform where it's not supported.

I agree. It's probably more appropriate to report an error instead of crashing?

> You should probably make this a target-specific builtin

I see.  I made this a general builtin because I noticed that `__builtin_frame_address` and `__builtin_return_address` are defined as general builtin's so I thought `__builtin_stack_address` should follow the same approach?

Making this a target-specific builtin is a good idea, but what do you think about keeping `__builtin_stack_address` as a general builtin and generating a [`Cannot compile this __builtin_stack_address yet` compile error](https://github.com/llvm/llvm-project/blob/d5c8af492f2d8620b04330024d46a5f48db546fe/clang/lib/CodeGen/CGBuiltin.cpp#L4800)) when the target arch is unsupported? The compile error will look like the following:
```cpp
llvm-project/clang/test/CodeGen/builtin-stackaddress.c:17:10: error: cannot compile this __builtin_stack_address yet
   17 |   return __builtin_stack_address();
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
```
 Insights are appreciated!



https://github.com/llvm/llvm-project/pull/121332


More information about the cfe-commits mailing list