diff mbox

RFA: new pass to warn on questionable uses of alloca() and VLAs

Message ID 577F9301.10205@redhat.com
State New
Headers show

Commit Message

Aldy Hernandez July 8, 2016, 11:48 a.m. UTC
[New thread now that I actually have a tested patch :)].

> I think detecting potentially problematic uses of alloca would
> be useful, especially when done in an intelligent way like in
> your patch (as opposed to simply diagnosing every call to
> the function regardless of the value of its argument).  At
> the same time, it seems that an even more reliable solution
> than pointing out potentially unsafe calls to the function
> and relying on users to modify their code to use malloc for
> large/unbounded allocations would be to let GCC do it for
> them automatically (i.e., in response to some other option,
> emit a call to malloc instead, and insert a call to free when
> appropriate).

As Jeff said, we were thinking the other way around: notice a malloced 
area that doesn't escape and replace it with a call to alloca.  But all 
this is beyond the scope of this patch.

>
> I applied the patch and experimented with it a bit (I haven't
> studied the code in any detail yet) and found a few opportunities
> for improvements.  I describe them below (Sorry in advance for
> the length of my comments!)

BTW, thank you so much for taking the time to look into this.  Your 
feedback has been invaluable.

>
> I found the "warning: unbounded use of alloca" misleading when
> a call to the function was, in fact, bounded but to a limit
> that's greater than alloca-max-size as in the program below:

I have added various levels of granularity for the warning, along with 
appropriately different messages:

// Possible problematic uses of alloca.
enum alloca_type {
   // Alloca argument is within known bounds that are appropriate.
   ALLOCA_OK,

   // Alloca argument is KNOWN to have a value that is too large.
   ALLOCA_BOUND_DEFINITELY_LARGE,

   // Alloca argument may be too large.
   ALLOCA_BOUND_MAYBE_LARGE,

   // Alloca argument is bounded but of an indeterminate size.
   ALLOCA_BOUND_UNKNOWN,

   // Alloca argument was casted from a signed integer.
   ALLOCA_CAST_FROM_SIGNED,

   // Alloca appears in a loop.
   ALLOCA_IN_LOOP,

   // Alloca call is unbounded.  That is, there is no controlling
   // predicate for its argument.
   ALLOCA_UNBOUNDED
};

Of course, there are plenty of cases where we can't get the exact 
diagnosis (due to the limitations on our range info) and we fall back to 
ALLOCA_UNBOUNDED or ALLOCA_BOUND_MAYBE_LARGE.  In practice, I'm 
wondering whether we should lump everything into 2-3 warnings instead of 
trying so hard to get the exact reason for the problematic use of 
alloca.  (More details on upcoming changes to range info further down.)

>
>   void f (void*);
>
>   void g (int n)
>   {
>     void *p;
>     if (n < 4096)
>       p = __builtin_alloca (n);
>     else
>       p = __builtin_malloc (n);
>     f (p);
>   }
>   t.C: In function ‘g’:
>   t.C:7:7: warning: unbounded use of alloca [-Walloca]
>        p = __builtin_alloca (n);

Well, in this particular case you are using a signed int, so n < 4096 
can cause the value passed to alloca  to be rather large in the case of 
n < 0.

>
> I would suggest to rephrase the diagnostic to mention the limit,
> e.g.,
>
>   warning: calling alloca with an argument in excess of '4000'
>   bytes

In the attached patch I try to diagnose these cases with:

a.c: In function ‘g’:
a.c:7:10: warning: cast from signed type in alloca [-Walloca]
p = __builtin_alloca (n);

I'm not 100% convinced this the best idea, and I could be easily 
convinced to narrow the wide variety of warning cases I currently have 
into just a handful less specific ones.

>
> I'm not sure I understand how -Walloca-max-size is supposed to
> be used.  For example, it has no effect on the test case above
> (i.e., I couldn't find a way to use it to raise the limit to
> avoid the warning).  Maybe the interaction of the two options
> is more subtle than I think.  I would have expected either

If by subtle you mean buggy, then yes-- thank you for your kind words 
:).  I have fixed it all, and those found responsible have been sacked.

> a single option to control whether alloca warnings are to be
> emitted and also (optionally) the allocation threshold, or
> perhaps two options, one to turn the warning on and off, and
> another just to override the threshold (though this latter
> approach seems superfluous given that a single option can do
> both).
...
> I also think that VLA diagnostics would be better controlled
> by a separate option, and emit a different diagnostic (one

I have overhauled the options and added extensive documentation to 
invoke.texi explaining them.  See the included testcases.  I have tried 
to add a testcase for everything the pass currently handles.

In the interest of keeping a consistent relationship with -Wvla, we now 
have:

-Walloca:	Warn on every use of alloca (not VLAs).
-Walloca=999:	Warn on unbounded uses of alloca, bounded uses with
		no known limit, and bounded uses where the number of
		bytes is greater than 999.
-Wvla:		Behaves as currently (warn on every use of VLAs).
-Wvla=999:	Similar to -Walloca=999, but for -Wvla.

Notice plain -Walloca doesn't have a default, and just warns on every 
use of alloca, just like -Wvla does for VLAs.  This way we can be 
consistent with -Wvla, and just add the -Wvla=999 variant.

I have added appropriate warnings to avoid confusion with -Wvla=0 and 
-Walloca=0, because they would conflict with -Wno-vla and -Wno-alloca 
(setting warn_vla=0 and warn_alloca=0 respectively).

The option handling is a bit convoluted because no -Wvla passed is 
warn_vla == -1, and CPP and the FE's depend on this information to know 
when no -Wvla was passed (pedantic warnings and some CPP pre-defines). 
So to keep everything consistent I had to differentiate between no -Wvla 
passed, plain -Wvla passed, and -Wvla=999 passed, without getting 
confused by -Wvla=0 and -Wno-vla.  Ughhh...

> Beyond a separate option for VLAs, in my limited testing I
> couldn't figure out how constrain the VLA size so that using
> -Walloca wouldn't complain for example on the following code:
>
>   void f (void*);
>
>   void h (int n)
>   {
>     if (n < 100)
>     {
>       int a [n];
>       f (a);
>     }
>   }

Fixed.  Also, you have a signed int here as well.  That could cause a 
very large allocation.

This patch depends on range information, which is less than stellar past 
the VRP pass.  To get better range information, we'd have to incorporate 
this somehow into the VRP pass and use the ASSERT_EXPRs therein.  And 
still, VRP gets awfully confused with PHI merge points.  Andrew Macleod 
is working on a new fancy range info infrastructure that should 
eliminate a lot of the false positives we may get and/or help us 
diagnose a wider range of cases.  Hence the reason that I'm not bending 
over backwards to incorporate this pass into tree-vrp.c.

FYI, I have a few XFAILed tests in this patch, to make sure we don't 
lose track of possible improvements (which in this case should be 
handled by better range info).  What's the blessed way of doing this? 
Are adding new XFAILed tests acceptable?

I have regstrapped this patch on x86-64 Linux, and have tested the 
resulting compiler by building glibc with:

/source/glibc/configure --prefix=/usr CC="/path/bin/gcc -Walloca=5000" 
--disable-werror

This of course, pointed out all sorts of interesting things!

Fire away!

Aldy
gcc/

	* Makefile.in (OBJS): Add gimple-ssa-warn-walloca.o.
	* common.opt (Walloca): New.
	(Walloca=): New.
	* passes.def: Add pass_walloca.
	* tree-pass.h (make_pass_walloca): New.
	* gimple-ssa-warn-walloca.c: New file.
	* opts.c (finish_options): Warn on specific variants of -Walloca
	and -Wvla=.
	(common_handle_option): Add cases for OPT_Walloca and OPT_Walloca_.
	* doc/invoke.texi: Document -Walloca, -Walloca=, and -Wvla
	options.

gcc/c-family/

	* c-cppbuiltin.c (c_cpp_builtins): Make sure not all negative
	numbers get treated the same when evaluating warn_vla.
	* c-opts.c (c_common_handle_option): Add case for OPT_Wvla and
	OPT_Wvla_.
	* c.opt: Add entries for Walloca, Walloca=, and Wvla=.

gcc/c/

	* c-decl.c (warn_variable_length_array): Do not warn when
	-Wvla=999 is being used.
	* c-errors.c (pedwarn_c90): Not all negative numbers case a
	warning to be silenced.

gcc/cp/

	* decl.c (compute_array_index_type): Handle -Wvla=999 warning.

Comments

Martin Sebor July 10, 2016, 10:09 p.m. UTC | #1
On 07/08/2016 05:48 AM, Aldy Hernandez wrote:
> [New thread now that I actually have a tested patch :)].
...
> I have overhauled the options and added extensive documentation to
> invoke.texi explaining them.  See the included testcases.  I have tried
> to add a testcase for everything the pass currently handles.
>
> In the interest of keeping a consistent relationship with -Wvla, we now
> have:
>
> -Walloca:    Warn on every use of alloca (not VLAs).
> -Walloca=999:    Warn on unbounded uses of alloca, bounded uses with
>          no known limit, and bounded uses where the number of
>          bytes is greater than 999.
> -Wvla:        Behaves as currently (warn on every use of VLAs).
> -Wvla=999:    Similar to -Walloca=999, but for -Wvla.
>
> Notice plain -Walloca doesn't have a default, and just warns on every
> use of alloca, just like -Wvla does for VLAs.  This way we can be
> consistent with -Wvla, and just add the -Wvla=999 variant.

I like it!

> This patch depends on range information, which is less than stellar past
> the VRP pass.  To get better range information, we'd have to incorporate
> this somehow into the VRP pass and use the ASSERT_EXPRs therein.  And
> still, VRP gets awfully confused with PHI merge points.  Andrew Macleod
> is working on a new fancy range info infrastructure that should
> eliminate a lot of the false positives we may get and/or help us
> diagnose a wider range of cases.  Hence the reason that I'm not bending
> over backwards to incorporate this pass into tree-vrp.c.
>
> FYI, I have a few XFAILed tests in this patch, to make sure we don't
> lose track of possible improvements (which in this case should be
> handled by better range info).  What's the blessed way of doing this?
> Are adding new XFAILed tests acceptable?
>
> I have regstrapped this patch on x86-64 Linux, and have tested the
> resulting compiler by building glibc with:
>
> /source/glibc/configure --prefix=/usr CC="/path/bin/gcc -Walloca=5000"
> --disable-werror
>
> This of course, pointed out all sorts of interesting things!
>
> Fire away!

I've played with the patch a bit over the weekend and have a few
comments and suggestions (I hope you won't regret encouraging me :)
I like the consistency between -Walloca and -Wvla! (And despite
the volume of my remaining comments, the rest of the patch too!

1) Optimization.  Without -O2 GCC prints:

   sorry, unimplemented: -Walloca ignored without -O2

It seems that a warning would be more appropriate here than
a hard error, but the checker could, and I would say should, be
made available (in a limited form) without optimization because
  -Walloca with no argument doesn't rely on it.  I suspect in this
form, -Walloca is probably mainly going to be useful as a mechanism
to enforce a "thou shall not use alloca" policy, though not much
more beyond that.  Some development processes only require that
code build without optimization in order to allow a commit and
do more extensive testing with optimization during continuous
integration, and not enabling it at -O0 would make it difficult
to adopt the warning on projects that use such a process.

2) When passed an argument of a signed type, GCC prints

   warning: cast from signed type in alloca

even though there is no explicit cast in the code.  It may not
be obvious why the conversion is a problem in this context.  I
would suggest to rephrase the warning along the lines of
-Wsign-conversion which prints:

   conversion to ‘long unsigned int’ from ‘int’ may change the sign of 
the result

and add why it's a potential problem.  Perhaps something like:

   argument to alloca may be too large due to conversion from
   'int to 'long unsigned int'

(In addition, assuming one accepts the lack of range checking and
constant propagation, this aspect of -Walloca also doesn't need
optimization.)

3) I wonder if the warning should also detect alloca calls with
a zero argument and VLAs of zero size.  They are both likely to
be programmer errors.  (Although it seems that that would need
to be done earlier than in the alloca pass.)

4) I wasn't able to trigger the -Wvla=N warning with VLAs used
in loops even though VRP provides the range of the value:

   $ cat t.c && /build/gcc-walloca/gcc/xgcc -B /build/gcc-walloca/gcc 
-O2 -S -Wall -Wextra -Wpedantic -Wvla=3 -fdump-tree-vrp=/dev/stdout t.c 
| grep _2
   void f0 (void*);

   void f1 (void)
   {
     for (int i = 0; i != 32; ++i)
     {
       char a [i];
       f0 (a);
     }
   }

   _2: [0, 31]
     sizetype _2;
     _2 = (sizetype) i_16;
     a.1_8 = __builtin_alloca_with_align (_2, 8);

5) The -Wvla=N logic only seems to take into consideration the number
of elements but not the size of the element type. For example, I wasn't
able to get it to warn on the following with -Wvla=255 or greater:

   void f0 (void*);

   void f1 (unsigned char a)
   {
     int x [a];   // or even char a [n][__INT_MAX__];
     f0 (x);
   }

6) The patch seems to assume that __builtin_alloca_with_align implies
a VLA, but that need not be the case.  Based on tree dumps it looks
like there is a way to distinguish a VLA from a call to the built-in.
For accuracy's sake I think it would be worth making that distinction
in the diagnostic.

7) The -Walloca=N and -Wvla=N argument is a 32-bit integer and no
checking appears to be done to make sure it doesn't overflow, so
that invoking GCC with an argument of UINT_MAX results in:

   cc1: note: -Wvla=0 disables -Wvla.  Use -Wno-vla instead.

and with larger arguments in imposing a limit that's modulo UINT_MAX.
Although stack size in excess of UINT_MAX bytes is unlikely, it seems
that such exceedingly large arguments should be handled more gracefully
(if they cannot be stored in a size_t argument it would be nice give
a warning).

8) Finally, I think it would be helpful to provide information about
the values GCC used to decide to issue the warning, especially when
optimization is involved.  In many cases it will not be immediately
obvious how GCC determined that an alloca argument is too big, or
what the limit even is (for instance, when the -Walloca=N option
is set via a #pragma GCC diagnostic far away from the call).
Mentioning both the argument value or range and the threshold for
the warning will help make it clear.

Martin

PS I also ran into a couple internal compiler errors with the test
cases below:

   void f0 (void*);

   void f1 (int a, int b)
   {
     int x [a][b];
     f0 (x);
   }

   0x11def63 tree_to_uhwi(tree_node const*)
   /src/gcc/walloca/gcc/tree.c:7339
   ...

   void f0 (void*);

   void f1 (unsigned char a)
   {
     void *p = __builtin_alloca_with_align (a, 8);
     f0 (p);
   }

   x181cb74 alloca_call_type
   /src/gcc/walloca/gcc/gimple-ssa-warn-alloca.c:257
   ...
Manuel López-Ibáñez July 10, 2016, 11:41 p.m. UTC | #2
> +Walloca
> +LangEnabledBy(C ObjC C++ ObjC++)
> +; in common.opt
> +
> +Walloca=
> +LangEnabledBy(C ObjC C++ ObjC++)
> +; in common.opt
> +

I'm not sure what you think the above means, but this is an invalid use of 
LangEnabledBy(). (It would be nice if the .awk scripts were able to catch it 
and give an error.)


> +;; warn_vla == 0 for -Wno-vla
> +;; warn_vla == -1 for nothing passed.
> +;; warn_vla == -2 for -Wvla passed
> +;; warn_vla == NUM for -Wvla=NUM
>  Wvla
>  C ObjC C++ ObjC++ Var(warn_vla) Init(-1) Warning
>  Warn if a variable length array is used.
>
> +Wvla=
> +C ObjC C++ ObjC++ Var(warn_vla) Warning Joined RejectNegative UInteger
> +-Wvla=<number> Warn on unbounded uses of variable-length arrays, and
> +warn on bounded uses of variable-length arrays whose bound can be
> +larger than <number> bytes.
> +

This overloading of warn_vla seems confusing (as shown by all the places that 
require updating). Why not call it Wvla-larger-than= and use a different 
warn_vla_larger_than variable? We already have -Wlarger-than= and 
-Wframe-larger-than=.

Using warn_vla_larger_than (even if you wish to keep -Wvla= as the option name) 
as a variable distinct from warn_vla would make things simpler:

-Wvla => warn_vla == 1
-Wno-vla => warn_vla == 0
-Wvla=N => warn_vla_larger_than == N (where N == 0 means disable).

If you wish that -Wno-vla implies -Wvla=0 then you'll need to handle that 
manually. I don't think we have support for that in the .opt files. But that 
seems far less complex than having a single shared Var().

Cheers,
	Manuel.
Aldy Hernandez July 11, 2016, 10:10 a.m. UTC | #3
On 07/10/2016 07:41 PM, Manuel López-Ibáñez wrote:
>> +Walloca
>> +LangEnabledBy(C ObjC C++ ObjC++)
>> +; in common.opt
>> +
>> +Walloca=
>> +LangEnabledBy(C ObjC C++ ObjC++)
>> +; in common.opt
>> +
>
> I'm not sure what you think the above means, but this is an invalid use
> of LangEnabledBy(). (It would be nice if the .awk scripts were able to
> catch it and give an error.)

I was following the practice for -Warray-bounds in c-family/c.opt:

Warray-bounds
LangEnabledBy(C ObjC C++ ObjC++,Wall)
; in common.opt

Warray-bounds=
LangEnabledBy(C ObjC C++ ObjC++,Wall,1,0)
; in common.opt

...as well as the generic version in common.opt:

Warray-bounds
Common Var(warn_array_bounds) Warning
Warn if an array is accessed out of bounds.

Warray-bounds=
Common Joined RejectNegative UInteger Var(warn_array_bounds) Warning
Warn if an array is accessed out of bounds.

I *thought* you defined the option in common.opt, and narrowed the 
language variants in c-family/c.opt.  ??

>
>
>> +;; warn_vla == 0 for -Wno-vla
>> +;; warn_vla == -1 for nothing passed.
>> +;; warn_vla == -2 for -Wvla passed
>> +;; warn_vla == NUM for -Wvla=NUM
>>  Wvla
>>  C ObjC C++ ObjC++ Var(warn_vla) Init(-1) Warning
>>  Warn if a variable length array is used.
>>
>> +Wvla=
>> +C ObjC C++ ObjC++ Var(warn_vla) Warning Joined RejectNegative UInteger
>> +-Wvla=<number> Warn on unbounded uses of variable-length arrays, and
>> +warn on bounded uses of variable-length arrays whose bound can be
>> +larger than <number> bytes.
>> +
>
> This overloading of warn_vla seems confusing (as shown by all the places
> that require updating). Why not call it Wvla-larger-than= and use a
> different warn_vla_larger_than variable? We already have -Wlarger-than=
> and -Wframe-larger-than=.

Hey, I'm all for different options.  It would definitely be easier for 
me :).  I wast trying really hard to use -Wvla= and keep the current 
-Wvla meaning the same.  Though I see your point about using -Wvla* but 
using different variables for representing -Wvla and -Wvla=blah.

The easiest thing would be:

-Wvla: Current behavior (warn on everything).

-Wvla-larger-than=xxxx: Warn on unbounded VLA and bounded VLAs > xxxx.

-Walloca: Warn on every use of alloca (analogous to -Wvla).

-Walloca-larger-than=xxxx: Warn on unbounded alloca and bounded allocas 
 > xxxx.

This seems straightforward and avoids all the overloading you see. 
Would this be ok with everyone?

>
> Using warn_vla_larger_than (even if you wish to keep -Wvla= as the
> option name) as a variable distinct from warn_vla would make things
> simpler:
>
> -Wvla => warn_vla == 1
> -Wno-vla => warn_vla == 0
> -Wvla=N => warn_vla_larger_than == N (where N == 0 means disable).
>
> If you wish that -Wno-vla implies -Wvla=0 then you'll need to handle
> that manually. I don't think we have support for that in the .opt files.
> But that seems far less complex than having a single shared Var().
>
> Cheers,
>      Manuel.
>

Thanks.
Aldy
Manuel López-Ibáñez July 11, 2016, 2:21 p.m. UTC | #4
On 11 July 2016 at 11:10, Aldy Hernandez <aldyh@redhat.com> wrote:
> On 07/10/2016 07:41 PM, Manuel López-Ibáñez wrote:
>>>
>>> +Walloca
>>> +LangEnabledBy(C ObjC C++ ObjC++)
>>> +; in common.opt
>>> +
>>> +Walloca=
>>> +LangEnabledBy(C ObjC C++ ObjC++)
>>> +; in common.opt
>>> +
>>
>>
>> I'm not sure what you think the above means, but this is an invalid use
>> of LangEnabledBy(). (It would be nice if the .awk scripts were able to
>> catch it and give an error.)
>
>
> I was following the practice for -Warray-bounds in c-family/c.opt:
>
> Warray-bounds
> LangEnabledBy(C ObjC C++ ObjC++,Wall)
> ; in common.opt
>
> Warray-bounds=
> LangEnabledBy(C ObjC C++ ObjC++,Wall,1,0)
> ; in common.opt

The ones you quoted mean: For that list of languages, -Warray-bounds
is enabled by -Wall.

https://gcc.gnu.org/onlinedocs/gccint/Option-properties.html#Option-properties

But the entries that you added do not specify an option. It should
give an error by the *.awk scripts that parse .opt files. I'm actually
not sure what the scripts are generating in your case.

> I *thought* you defined the option in common.opt, and narrowed the language
> variants in c-family/c.opt.  ??

No, options that are language specific just need to be defined for the
respective FEs using the respective language flags: Wvla is an example
of that. It doesn't appear in common.opt.

Adding language flags to a common option is just redundant (again,
this is not what LangEnabledBy is doing).

Cheers,

Manuel.
Jeff Law July 11, 2016, 2:24 p.m. UTC | #5
On 07/08/2016 05:48 AM, Aldy Hernandez wrote:
> [New thread now that I actually have a tested patch :)].
>
>> I think detecting potentially problematic uses of alloca would
>> be useful, especially when done in an intelligent way like in
>> your patch (as opposed to simply diagnosing every call to
>> the function regardless of the value of its argument).  At
>> the same time, it seems that an even more reliable solution
>> than pointing out potentially unsafe calls to the function
>> and relying on users to modify their code to use malloc for
>> large/unbounded allocations would be to let GCC do it for
>> them automatically (i.e., in response to some other option,
>> emit a call to malloc instead, and insert a call to free when
>> appropriate).
>
> As Jeff said, we were thinking the other way around: notice a malloced
> area that doesn't escape and replace it with a call to alloca.  But all
> this is beyond the scope of this patch.
Definitely out of scope for this set of changes.    BUt it's part of my 
evil plan to squash explicit alloca calls while still allowing its use 
when it's provably safe.  But we're not in that world yet.

>> I found the "warning: unbounded use of alloca" misleading when
>> a call to the function was, in fact, bounded but to a limit
>> that's greater than alloca-max-size as in the program below:
>
> I have added various levels of granularity for the warning, along with
> appropriately different messages:
>
> // Possible problematic uses of alloca.
> enum alloca_type {
>   // Alloca argument is within known bounds that are appropriate.
>   ALLOCA_OK,
>
>   // Alloca argument is KNOWN to have a value that is too large.
>   ALLOCA_BOUND_DEFINITELY_LARGE,
>
>   // Alloca argument may be too large.
>   ALLOCA_BOUND_MAYBE_LARGE,
>
>   // Alloca argument is bounded but of an indeterminate size.
>   ALLOCA_BOUND_UNKNOWN,
>
>   // Alloca argument was casted from a signed integer.
>   ALLOCA_CAST_FROM_SIGNED,
>
>   // Alloca appears in a loop.
>   ALLOCA_IN_LOOP,
>
>   // Alloca call is unbounded.  That is, there is no controlling
>   // predicate for its argument.
>   ALLOCA_UNBOUNDED
> };
>
> Of course, there are plenty of cases where we can't get the exact
> diagnosis (due to the limitations on our range info) and we fall back to
> ALLOCA_UNBOUNDED or ALLOCA_BOUND_MAYBE_LARGE.  In practice, I'm
> wondering whether we should lump everything into 2-3 warnings instead of
> trying so hard to get the exact reason for the problematic use of
> alloca.  (More details on upcoming changes to range info further down.)
I'll trust your judgment on this -- I kind of like the more precise 
warnings -- if for no other reason than it makes it easier for someone 
looking at legacy code (think glibc) to see why GCC determined their 
alloca call was unsafe.

>
>>
>>   void f (void*);
>>
>>   void g (int n)
>>   {
>>     void *p;
>>     if (n < 4096)
>>       p = __builtin_alloca (n);
>>     else
>>       p = __builtin_malloc (n);
>>     f (p);
>>   }
>>   t.C: In function ‘g’:
>>   t.C:7:7: warning: unbounded use of alloca [-Walloca]
>>        p = __builtin_alloca (n);
>
> Well, in this particular case you are using a signed int, so n < 4096
> can cause the value passed to alloca  to be rather large in the case of
> n < 0.
Right.  And if the bad guys can get control of "N" in this case, they 
can pass in a negative value and perform a "stack shift" -- essentially 
moving the stack so that it points somewhere else  more "interesting" in 
memory.


>
> This patch depends on range information, which is less than stellar past
> the VRP pass.  To get better range information, we'd have to incorporate
> this somehow into the VRP pass and use the ASSERT_EXPRs therein.  And
> still, VRP gets awfully confused with PHI merge points.  Andrew Macleod
> is working on a new fancy range info infrastructure that should
> eliminate a lot of the false positives we may get and/or help us
> diagnose a wider range of cases.  Hence the reason that I'm not bending
> over backwards to incorporate this pass into tree-vrp.c.
Right.  Getting better range information is important in so many ways.

>
> FYI, I have a few XFAILed tests in this patch, to make sure we don't
> lose track of possible improvements (which in this case should be
> handled by better range info).  What's the blessed way of doing this?
> Are adding new XFAILed tests acceptable?
I'd go with a new XFAIL'd test.

Jeff
Jeff Law July 11, 2016, 2:32 p.m. UTC | #6
On 07/10/2016 04:09 PM, Martin Sebor wrote:
> On 07/08/2016 05:48 AM, Aldy Hernandez wrote:
>
> I've played with the patch a bit over the weekend and have a few
> comments and suggestions (I hope you won't regret encouraging me :)
> I like the consistency between -Walloca and -Wvla! (And despite
> the volume of my remaining comments, the rest of the patch too!
>
> 1) Optimization.  Without -O2 GCC prints:
>
>   sorry, unimplemented: -Walloca ignored without -O2
>
> It seems that a warning would be more appropriate here than
> a hard error, but the checker could, and I would say should, be
> made available (in a limited form) without optimization because
>  -Walloca with no argument doesn't rely on it.  I suspect in this
> form, -Walloca is probably mainly going to be useful as a mechanism
> to enforce a "thou shall not use alloca" policy, though not much
> more beyond that.
:-)  Which would be fine with me -- the difference is, we'd be able to 
back up my "programmers can't correctly use alloca" rant from several 
years ago with compiler analysis showing why each particular alloca was 
unsafe.

>
> 2) When passed an argument of a signed type, GCC prints
>
>   warning: cast from signed type in alloca
>
> even though there is no explicit cast in the code.  It may not
> be obvious why the conversion is a problem in this context.  I
> would suggest to rephrase the warning along the lines of
> -Wsign-conversion which prints:
>
>   conversion to ‘long unsigned int’ from ‘int’ may change the sign of
> the result
>
> and add why it's a potential problem.  Perhaps something like:
>
>   argument to alloca may be too large due to conversion from
>   'int to 'long unsigned int'
I like Martin's much better.

>
> 3) I wonder if the warning should also detect alloca calls with
> a zero argument and VLAs of zero size.  They are both likely to
> be programmer errors.  (Although it seems that that would need
> to be done earlier than in the alloca pass.)
Seems like Aldy ought to add this as a testcase, even if it's XFAIL'd 
for now.

>
> 4) I wasn't able to trigger the -Wvla=N warning with VLAs used
> in loops even though VRP provides the range of the value:
Similarly for the others in your message.



Jeff
Martin Sebor July 11, 2016, 3:08 p.m. UTC | #7
>
> Hey, I'm all for different options.  It would definitely be easier for
> me :).  I wast trying really hard to use -Wvla= and keep the current
> -Wvla meaning the same.  Though I see your point about using -Wvla* but
> using different variables for representing -Wvla and -Wvla=blah.
>
> The easiest thing would be:
>
> -Wvla: Current behavior (warn on everything).
>
> -Wvla-larger-than=xxxx: Warn on unbounded VLA and bounded VLAs > xxxx.
>
> -Walloca: Warn on every use of alloca (analogous to -Wvla).
>
> -Walloca-larger-than=xxxx: Warn on unbounded alloca and bounded allocas
>  > xxxx.
>
> This seems straightforward and avoids all the overloading you see. Would
> this be ok with everyone?

I like the consistency.

Given the common root with -Wlarger-than=N, what do envision the effect
of setting -Wlarger-than=N to be on the two new options?

FWIW, I tend to view -Wlarger-than= and certainly -Wframe-larger-than=
not warning on alloca larger than N as a defect.  It could be fixed by
simply hooking -Walloca-larger-than= up to it.

   void f (void*);
   void g (void)
   {
     void *p = __builtin_alloca (1024);
     f (p);
   }

Martin
Aldy Hernandez July 11, 2016, 3:40 p.m. UTC | #8
On 07/11/2016 11:08 AM, Martin Sebor wrote:
>>
>> Hey, I'm all for different options.  It would definitely be easier for
>> me :).  I wast trying really hard to use -Wvla= and keep the current
>> -Wvla meaning the same.  Though I see your point about using -Wvla* but
>> using different variables for representing -Wvla and -Wvla=blah.
>>
>> The easiest thing would be:
>>
>> -Wvla: Current behavior (warn on everything).
>>
>> -Wvla-larger-than=xxxx: Warn on unbounded VLA and bounded VLAs > xxxx.
>>
>> -Walloca: Warn on every use of alloca (analogous to -Wvla).
>>
>> -Walloca-larger-than=xxxx: Warn on unbounded alloca and bounded allocas
>>  > xxxx.
>>
>> This seems straightforward and avoids all the overloading you see. Would
>> this be ok with everyone?
>
> I like the consistency.
>
> Given the common root with -Wlarger-than=N, what do envision the effect
> of setting -Wlarger-than=N to be on the two new options?
>
> FWIW, I tend to view -Wlarger-than= and certainly -Wframe-larger-than=
> not warning on alloca larger than N as a defect.  It could be fixed by
> simply hooking -Walloca-larger-than= up to it.

I'm not touching any of these independent options.  -Wvla-larger-than= 
and -Walloca-larger-than= will be implemented independently of whatever 
-Wlarger-than= and -Wframe-larger-than=.  Any problems with these last 
two options can be treated indpendently (PRs).

Aldy
Martin Sebor July 11, 2016, 5:56 p.m. UTC | #9
On 07/11/2016 09:40 AM, Aldy Hernandez wrote:
> On 07/11/2016 11:08 AM, Martin Sebor wrote:
>>>
>>> Hey, I'm all for different options.  It would definitely be easier for
>>> me :).  I wast trying really hard to use -Wvla= and keep the current
>>> -Wvla meaning the same.  Though I see your point about using -Wvla* but
>>> using different variables for representing -Wvla and -Wvla=blah.
>>>
>>> The easiest thing would be:
>>>
>>> -Wvla: Current behavior (warn on everything).
>>>
>>> -Wvla-larger-than=xxxx: Warn on unbounded VLA and bounded VLAs > xxxx.
>>>
>>> -Walloca: Warn on every use of alloca (analogous to -Wvla).
>>>
>>> -Walloca-larger-than=xxxx: Warn on unbounded alloca and bounded allocas
>>>  > xxxx.
>>>
>>> This seems straightforward and avoids all the overloading you see. Would
>>> this be ok with everyone?
>>
>> I like the consistency.
>>
>> Given the common root with -Wlarger-than=N, what do envision the effect
>> of setting -Wlarger-than=N to be on the two new options?
>>
>> FWIW, I tend to view -Wlarger-than= and certainly -Wframe-larger-than=
>> not warning on alloca larger than N as a defect.  It could be fixed by
>> simply hooking -Walloca-larger-than= up to it.
>
> I'm not touching any of these independent options.  -Wvla-larger-than=
> and -Walloca-larger-than= will be implemented independently of whatever
> -Wlarger-than= and -Wframe-larger-than=.  Any problems with these last
> two options can be treated indpendently (PRs).

Strictly speaking there is no defect in -Wframe-larger-than= because
it's documented not to warn for alloca or VLAs.  I asked because it
seems like an unnecessary (and IMO undesirable) limitation that could
be easily removed as part of this patch.  Not removing it, OTOH, and
providing a separate solution, feels like highlighting the limitation.
With the new options, users interested in detecting all forms of
excessive stack allocation will be able to do so but not using
a single option.  Instead, they will need to use all three.

Martin
Aldy Hernandez July 15, 2016, 5:05 p.m. UTC | #10
On 07/11/2016 01:56 PM, Martin Sebor wrote:
> On 07/11/2016 09:40 AM, Aldy Hernandez wrote:
>> On 07/11/2016 11:08 AM, Martin Sebor wrote:
>>>>
>>>> Hey, I'm all for different options.  It would definitely be easier for
>>>> me :).  I wast trying really hard to use -Wvla= and keep the current
>>>> -Wvla meaning the same.  Though I see your point about using -Wvla* but
>>>> using different variables for representing -Wvla and -Wvla=blah.
>>>>
>>>> The easiest thing would be:
>>>>
>>>> -Wvla: Current behavior (warn on everything).
>>>>
>>>> -Wvla-larger-than=xxxx: Warn on unbounded VLA and bounded VLAs > xxxx.
>>>>
>>>> -Walloca: Warn on every use of alloca (analogous to -Wvla).
>>>>
>>>> -Walloca-larger-than=xxxx: Warn on unbounded alloca and bounded allocas
>>>>  > xxxx.
>>>>
>>>> This seems straightforward and avoids all the overloading you see.
>>>> Would
>>>> this be ok with everyone?
>>>
>>> I like the consistency.
>>>
>>> Given the common root with -Wlarger-than=N, what do envision the effect
>>> of setting -Wlarger-than=N to be on the two new options?
>>>
>>> FWIW, I tend to view -Wlarger-than= and certainly -Wframe-larger-than=
>>> not warning on alloca larger than N as a defect.  It could be fixed by
>>> simply hooking -Walloca-larger-than= up to it.
>>
>> I'm not touching any of these independent options.  -Wvla-larger-than=
>> and -Walloca-larger-than= will be implemented independently of whatever
>> -Wlarger-than= and -Wframe-larger-than=.  Any problems with these last
>> two options can be treated indpendently (PRs).
>
> Strictly speaking there is no defect in -Wframe-larger-than= because
> it's documented not to warn for alloca or VLAs.  I asked because it
> seems like an unnecessary (and IMO undesirable) limitation that could
> be easily removed as part of this patch.  Not removing it, OTOH, and
> providing a separate solution, feels like highlighting the limitation.
> With the new options, users interested in detecting all forms of
> excessive stack allocation will be able to do so but not using
> a single option.  Instead, they will need to use all three.

I'll address this as a follow-up patch.

Aldy
diff mbox

Patch

diff --git a/gcc/Makefile.in b/gcc/Makefile.in
index 776f6d7..2a13b8f 100644
--- a/gcc/Makefile.in
+++ b/gcc/Makefile.in
@@ -1284,6 +1284,7 @@  OBJS = \
 	gimple-ssa-nonnull-compare.o \
 	gimple-ssa-split-paths.o \
 	gimple-ssa-strength-reduction.o \
+	gimple-ssa-warn-alloca.o \
 	gimple-streamer-in.o \
 	gimple-streamer-out.o \
 	gimple-walk.o \
diff --git a/gcc/c-family/c-cppbuiltin.c b/gcc/c-family/c-cppbuiltin.c
index 408ad47..3cf13d9 100644
--- a/gcc/c-family/c-cppbuiltin.c
+++ b/gcc/c-family/c-cppbuiltin.c
@@ -827,7 +827,7 @@  c_cpp_builtins (cpp_reader *pfile)
 	 (corresponding to the initial test release of GNU C++) if we won't
 	 complain about use of VLAs.  */
       if (c_dialect_cxx ()
-	  && (pedantic ? warn_vla == 0 : warn_vla <= 0))
+	  && (pedantic ? warn_vla == 0 : warn_vla == -1))
 	cpp_define (pfile, "__cpp_runtime_arrays=198712");
 
       if (cxx_dialect >= cxx11)
diff --git a/gcc/c-family/c-opts.c b/gcc/c-family/c-opts.c
index ff6339c..71dd170 100644
--- a/gcc/c-family/c-opts.c
+++ b/gcc/c-family/c-opts.c
@@ -376,6 +376,19 @@  c_common_handle_option (size_t scode, const char *arg, int value,
       cpp_opts->warn_num_sign_change = value;
       break;
 
+    case OPT_Wvla:
+      /* Plain -Wvla will set warn_vla to 1, but this conflicts with
+	 -Wvla=1.  Set to -2 here which means -Wvla was set with no
+	 argument.  */
+      if (value == 1)
+	warn_vla = -2;
+      break;
+
+    case OPT_Wvla_:
+      if (value == 0)
+	inform (loc, "-Wvla=0 disables -Wvla.  Use -Wno-vla instead.");
+      break;
+
     case OPT_Wunknown_pragmas:
       /* Set to greater than 1, so that even unknown pragmas in
 	 system headers will be warned about.  */
diff --git a/gcc/c-family/c.opt b/gcc/c-family/c.opt
index 83fd84c..5221e0c 100644
--- a/gcc/c-family/c.opt
+++ b/gcc/c-family/c.opt
@@ -275,6 +275,14 @@  Wall
 C ObjC C++ ObjC++ Warning
 Enable most warning messages.
 
+Walloca
+LangEnabledBy(C ObjC C++ ObjC++)
+; in common.opt
+
+Walloca=
+LangEnabledBy(C ObjC C++ ObjC++)
+; in common.opt
+
 Warray-bounds
 LangEnabledBy(C ObjC C++ ObjC++,Wall)
 ; in common.opt
@@ -976,10 +984,20 @@  Wvarargs
 C ObjC C++ ObjC++ Warning Var(warn_varargs) Init(1)
 Warn about questionable usage of the macros used to retrieve variable arguments.
 
+;; warn_vla == 0 for -Wno-vla
+;; warn_vla == -1 for nothing passed.
+;; warn_vla == -2 for -Wvla passed
+;; warn_vla == NUM for -Wvla=NUM
 Wvla
 C ObjC C++ ObjC++ Var(warn_vla) Init(-1) Warning
 Warn if a variable length array is used.
 
+Wvla=
+C ObjC C++ ObjC++ Var(warn_vla) Warning Joined RejectNegative UInteger
+-Wvla=<number> Warn on unbounded uses of variable-length arrays, and
+warn on bounded uses of variable-length arrays whose bound can be
+larger than <number> bytes.
+
 Wvolatile-register-var
 C ObjC C++ ObjC++ Var(warn_volatile_register_var) Warning LangEnabledBy(C ObjC C++ ObjC++,Wall)
 Warn when a register variable is declared volatile.
diff --git a/gcc/c/c-decl.c b/gcc/c/c-decl.c
index 5c08c59..0a34d23 100644
--- a/gcc/c/c-decl.c
+++ b/gcc/c/c-decl.c
@@ -5247,6 +5247,11 @@  check_bitfield_type_and_width (location_t loc, tree *type, tree *width,
 static void
 warn_variable_length_array (tree name, tree size)
 {
+  /* warn_vla > 0 is -Wvla=9999 which warns on specific instances of
+     VLA, not generically on all.  */
+  if (warn_vla > 0)
+    return;
+
   if (TREE_CONSTANT (size))
     {
       if (name)
diff --git a/gcc/c/c-errors.c b/gcc/c/c-errors.c
index af157c0..d7d4d9e 100644
--- a/gcc/c/c-errors.c
+++ b/gcc/c/c-errors.c
@@ -86,7 +86,7 @@  pedwarn_c90 (location_t location, int opt, const char *gmsgid, ...)
       int opt_var = *(int *) option_flag_var (opt, &global_options);
       if (opt_var == 0)
         goto out;
-      else if (opt_var > 0)
+      else if (opt_var != -1)
 	{
 	  diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
 			       (pedantic && !flag_isoc99)
diff --git a/gcc/common.opt b/gcc/common.opt
index f0d7196..7edcdc6 100644
--- a/gcc/common.opt
+++ b/gcc/common.opt
@@ -545,6 +545,19 @@  Waggressive-loop-optimizations
 Common Var(warn_aggressive_loop_optimizations) Init(1) Warning
 Warn if a loop with constant number of iterations triggers undefined behavior.
 
+;; warn_alloca == 0 for -Wno-alloca
+;; warn_alloca == -1 for nothing passed.
+;; warn_alloca == -2 for -Walloca passed
+;; warn_alloca == NUM for -Walloca=NUM
+Walloca
+Common Var(warn_alloca) Warning Init(-1)
+Warn on all uses of alloca.
+
+Walloca=
+Common Joined RejectNegative UInteger Var(warn_alloca) Warning
+-Walloca=<number>	Warn on unbounded uses of alloca, and warn on
+bounded uses of alloca whose argument can be larger than <number> bytes.
+
 Warray-bounds
 Common Var(warn_array_bounds) Warning
 Warn if an array is accessed out of bounds.
diff --git a/gcc/cp/decl.c b/gcc/cp/decl.c
index a03e48f..b8a2489 100644
--- a/gcc/cp/decl.c
+++ b/gcc/cp/decl.c
@@ -8870,14 +8870,19 @@  compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
 	error ("size of array is not an integral constant-expression");
       size = integer_one_node;
     }
-  else if (pedantic && warn_vla != 0)
+  /* In pedantic mode, warn if no -Wvla was explicitly passed
+     (warn_vla == -1) or if -Wvla was passed (warn_vla == -2).  Don't
+     warn on pedantic and -Wvla=xxx, which means something else.  */
+  else if (pedantic && warn_vla < 0)
     {
       if (name)
 	pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array %qD", name);
       else
 	pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array");
     }
-  else if (warn_vla > 0)
+  /* Warn if -Wvla was passed (warn_vla == -2), but not with -Wvla=xxx
+     which means something else.  */
+  else if (warn_vla == -2)
     {
       if (name)
 	warning (OPT_Wvla, 
diff --git a/gcc/doc/invoke.texi b/gcc/doc/invoke.texi
index 2105351..aee1212 100644
--- a/gcc/doc/invoke.texi
+++ b/gcc/doc/invoke.texi
@@ -253,6 +253,7 @@  Objective-C and Objective-C++ Dialects}.
 @gccoptlist{-fsyntax-only  -fmax-errors=@var{n}  -Wpedantic @gol
 -pedantic-errors @gol
 -w  -Wextra  -Wall  -Waddress  -Waggregate-return  @gol
+-Walloca -Walloca=@var{n} @gol
 -Wno-aggressive-loop-optimizations -Warray-bounds -Warray-bounds=@var{n} @gol
 -Wno-attributes -Wbool-compare -Wno-builtin-macro-redefined @gol
 -Wc90-c99-compat -Wc99-c11-compat @gol
@@ -309,7 +310,7 @@  Objective-C and Objective-C++ Dialects}.
 -Wunused-const-variable -Wunused-const-variable=@var{n} @gol
 -Wunused-but-set-parameter -Wunused-but-set-variable @gol
 -Wuseless-cast -Wvariadic-macros -Wvector-operation-performance @gol
--Wvla -Wvolatile-register-var  -Wwrite-strings @gol
+-Wvla -Wvla=@var{n} -Wvolatile-register-var  -Wwrite-strings @gol
 -Wzero-as-null-pointer-constant -Whsa}
 
 @item C and Objective-C-only Warning Options
@@ -4618,6 +4619,56 @@  annotations.
 Warn about overriding virtual functions that are not marked with the override
 keyword.
 
+@item -Walloca
+@itemx -Walloca=@var{n}
+@opindex Wno-alloca
+@opindex Walloca
+This option warns on suspicious uses of @code{alloca}.  If no argument
+is specified, a warning is issued for any use of @code{alloca} in the
+source.  However, if an argument is specified, a warning is issued for
+either unbounded uses of @code{alloca}, or bounded uses of
+@code{alloca} where the argument can be larger than @var{n} bytes.
+
+For example, a bounded case of @code{alloca} could be:
+
+@smallexample
+unsigned int n;
+...
+if (n <= 1000)
+  alloca (n);
+@end smallexample
+
+In the above example, passing @code{-Walloca=500} would cause the
+compiler to warn because the bound can be determined at compile time
+to be larger than 500.
+
+Unbounded uses, on the other hand, are uses of @code{alloca} with no
+controlling predicate verifying its size.  For example:
+
+@smallexample
+stuff ();
+alloca (n);
+@end smallexample
+
+If @code{-Walloca=500} was passed, the above code would also trigger a
+warning, but this time because of the lack of bounds checking.
+
+Note, that even seemingly correct code involving signed integers could
+cause a warning:
+
+@smallexample
+signed int n;
+...
+if (n < 500)
+  alloca (n);
+@end smallexample
+
+In the above example, @var{n} could be negative, causing a larger than
+expected argument to be implicitly casted into the @code{alloca} call.
+
+This warning is not enabled by @option{-Wall}, and is only active when
+@option{-ftree-vrp} is active (default for @option{-O2} and above).
+
 @item -Warray-bounds
 @itemx -Warray-bounds=@var{n}
 @opindex Wno-array-bounds
@@ -5780,11 +5831,20 @@  moved-from state.  If the move assignment operator is written to avoid
 moving from a moved-from object, this warning can be disabled.
 
 @item -Wvla
+@itemx -Wvla=@var{n}
 @opindex Wvla
 @opindex Wno-vla
-Warn if variable length array is used in the code.
+Warn if a variable-length array is used in the code.
 @option{-Wno-vla} prevents the @option{-Wpedantic} warning of
-the variable length array.
+the variable-length array.
+
+If an argument is used with this option, the compiler will only warn
+on uses of variable-length arrays where the size is either unbounded,
+or bounded by an argument that can be larger than @var{n} bytes.  This
+is similar to how @option{-Walloca=@var{n}} works, but with
+variable-length arrays.
+
+See also @option{-Walloca=@var{n}}.
 
 @item -Wvolatile-register-var
 @opindex Wvolatile-register-var
diff --git a/gcc/gimple-ssa-warn-alloca.c b/gcc/gimple-ssa-warn-alloca.c
new file mode 100644
index 0000000..6180d9e
--- /dev/null
+++ b/gcc/gimple-ssa-warn-alloca.c
@@ -0,0 +1,456 @@ 
+/* Warn on problematic uses of alloca and variable length arrays.
+   Copyright (C) 2016 Free Software Foundation, Inc.
+   Contributed by Aldy Hernandez <aldyh@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "backend.h"
+#include "tree.h"
+#include "gimple.h"
+#include "tree-pass.h"
+#include "ssa.h"
+#include "gimple-pretty-print.h"
+#include "diagnostic-core.h"
+#include "fold-const.h"
+#include "gimple-iterator.h"
+#include "tree-ssa.h"
+#include "params.h"
+#include "tree-cfg.h"
+#include "calls.h"
+#include "cfgloop.h"
+
+const pass_data pass_data_walloca = {
+  GIMPLE_PASS,
+  "walloca",
+  OPTGROUP_NONE,
+  TV_NONE,
+  PROP_cfg, // properties_required
+  0,	    // properties_provided
+  0,	    // properties_destroyed
+  0,	    // properties_start
+  0,	    // properties_finish
+};
+
+class pass_walloca : public gimple_opt_pass
+{
+public:
+  pass_walloca (gcc::context *ctxt)
+    : gimple_opt_pass(pass_data_walloca, ctxt)
+  {}
+  virtual bool gate (function *);
+  virtual unsigned int execute (function *);
+};
+
+bool
+pass_walloca::gate (function *fun ATTRIBUTE_UNUSED)
+{
+  // As a reference:
+  //
+  // nothing passed:	warn_vla = -1
+  // -Wvla:		warn_vla = -2
+  // -Wvla=ARG:		warn_vla = ARG
+  // -Wno-vla:		warn_vla = 0
+  //
+  // nothing passed:	warn_alloca = -1
+  // -Walloca:		warn_alloca = -2
+  // -Walloca=ARG	warn_alloca = ARG
+  // -Wno-alloca:	warn_alloca = 0
+
+  // Normalize those annoying -1 out.
+  if (warn_alloca == -1)
+    warn_alloca = 0;
+  if (warn_vla == -1)
+    warn_vla = 0;
+
+#define alloca_strict_mode	(warn_alloca == -2)
+#define vla_strict_mode		(warn_vla == -2)
+  if (!warn_alloca
+      // -Wvla strict mode is handled in the front-end.
+      && (!warn_vla || vla_strict_mode))
+    return false;
+
+  return true;
+}
+
+// Possible problematic uses of alloca.
+enum alloca_type {
+  // Alloca argument is within known bounds that are appropriate.
+  ALLOCA_OK,
+
+  // Alloca argument is KNOWN to have a value that is too large.
+  ALLOCA_BOUND_DEFINITELY_LARGE,
+
+  // Alloca argument may be too large.
+  ALLOCA_BOUND_MAYBE_LARGE,
+
+  // Alloca argument is bounded but of an indeterminate size.
+  ALLOCA_BOUND_UNKNOWN,
+
+  // Alloca argument was casted from a signed integer.
+  ALLOCA_CAST_FROM_SIGNED,
+
+  // Alloca appears in a loop.
+  ALLOCA_IN_LOOP,
+
+  // Alloca call is unbounded.  That is, there is no controlling
+  // predicate for its argument.
+  ALLOCA_UNBOUNDED
+};
+
+// We have a few heuristics up our sleeve to determine if a call to
+// alloca() is within bounds.  Try them out and return the type of
+// alloca call this is based on its argument.
+//
+// Given a known argument (ARG) to alloca() and an EDGE (E)
+// calculating said argument, verify that the last statement in the BB
+// in E->SRC is a gate comparing ARG to an acceptable bound for
+// alloca().  See examples below.
+//
+// MAX_SIZE is WARN_ALLOCA= adjusted for VLAs.  It is the maximum size
+// in bytes we allow for arg.
+//
+// Returns the alloca type.
+
+static enum alloca_type
+alloca_call_type_by_arg (tree arg, edge e, unsigned max_size)
+{
+  // All the tests bellow depend on the jump being on the TRUE path.
+  if (!(e->flags & EDGE_TRUE_VALUE))
+    return ALLOCA_UNBOUNDED;
+
+  basic_block bb = e->src;
+  gimple_stmt_iterator gsi = gsi_last_bb (bb);
+  gimple *last = gsi_stmt (gsi);
+  if (!last || gimple_code (last) != GIMPLE_COND)
+    return ALLOCA_UNBOUNDED;
+
+  /* Check for:
+     if (ARG <= N)
+       goto <bb 3>;
+      else
+        goto <bb 4>;
+      <bb 3>:
+      alloca(ARG);
+  */
+  if (gimple_cond_code (last) == LE_EXPR
+      && gimple_cond_lhs (last) == arg)
+    {
+      if (TREE_CODE (gimple_cond_rhs (last)) == INTEGER_CST)
+	return
+	  tree_to_uhwi (gimple_cond_rhs (last)) > max_size
+	  ? ALLOCA_BOUND_MAYBE_LARGE : ALLOCA_OK;
+      else
+	return ALLOCA_BOUND_UNKNOWN;
+    }
+
+  /* Check for:
+     if (arg .cond. LIMIT) -or- if (LIMIT .cond. arg)
+       alloca(arg);
+
+     Where LIMIT has a bound of unknown range.  */
+  tree limit = NULL;
+  if (gimple_cond_lhs (last) == arg)
+    limit = gimple_cond_rhs (last);
+  else if (gimple_cond_rhs (last) == arg)
+    limit = gimple_cond_lhs (last);
+  if (limit && TREE_CODE (limit) == SSA_NAME)
+    {
+      wide_int min, max;
+      value_range_type range_type = get_range_info (limit, &min, &max);
+      if (range_type == VR_UNDEFINED || range_type == VR_VARYING)
+	return ALLOCA_BOUND_UNKNOWN;
+      // FIXME: We could try harder here and handle a possible range
+      // or anti-range.  Hopefully the upcoming changes to range info
+      // will give us finer grained info, and we can avoid somersaults
+      // here.
+    }
+
+  return ALLOCA_UNBOUNDED;
+}
+
+// Return TRUE if SSA's definition is a cast from a signed type.
+
+static bool
+cast_from_signed_p (tree ssa)
+{
+  gimple *def = SSA_NAME_DEF_STMT (ssa);
+  if (!def || gimple_nop_p (def))
+    return false;
+  return (gimple_assign_cast_p (def)
+	  && !TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def))));
+}
+
+// Return TURE if X has a maximum range of MAX, basically covering the
+// entire domain, in which case it's no range at all.
+
+static bool
+is_max (tree x, wide_int max)
+{
+  return wi::max_value (TREE_TYPE (x)) == max;
+}
+
+// Analyze the alloca call in STMT and return an `enum alloca_type'
+// explaining what type of alloca it is.  IS_VLA is set if the alloca
+// call is really a BUILT_IN_ALLOCA_WITH_ALIGN, signifying a VLA.
+
+static enum alloca_type
+alloca_call_type (gimple *stmt, bool is_vla)
+{
+  gcc_assert (gimple_alloca_call_p (stmt));
+  tree len = gimple_call_arg (stmt, 0);
+  enum alloca_type w = ALLOCA_UNBOUNDED;
+  wide_int min, max;
+
+  gcc_assert (warn_vla > 0 || !is_vla);
+  gcc_assert (warn_alloca > 0 || is_vla);
+
+  // Check if we're in a loop.
+  basic_block bb = gimple_bb (stmt);
+  if (bb->loop_father
+      // ?? Functions with no loops get a loop_father?  I
+      // don't get it.  The following conditional seems to do
+      // the trick to exclude such nonsense.
+      && bb->loop_father->header != ENTRY_BLOCK_PTR_FOR_FN (cfun))
+    {
+      // Do not warn on VLAs occurring in a loop, since VLAs are
+      // guaranteed to be cleaned up when they go out of scope.
+      // That is, there is a corresponding __builtin_stack_restore
+      // at the end of the scope in which the VLA occurs.
+      tree fndecl = gimple_call_fn (stmt);
+      while (TREE_CODE (fndecl) == ADDR_EXPR)
+	fndecl = TREE_OPERAND (fndecl, 0);
+      if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
+	  && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_ALLOCA_WITH_ALIGN)
+	return ALLOCA_OK;
+
+      return ALLOCA_IN_LOOP;
+    }
+
+  // Adjust warn_alloca_max_size for VLAs, by taking the underlying
+  // type into account.
+  unsigned HOST_WIDE_INT max_size;
+  if (is_vla)
+    max_size = (unsigned HOST_WIDE_INT) warn_vla;
+  else
+    max_size = (unsigned HOST_WIDE_INT) warn_alloca;
+  if (is_vla)
+    {
+      tree ptype = TREE_TYPE (gimple_call_lhs (stmt));
+      gcc_assert (TREE_CODE (ptype) == POINTER_TYPE);
+      gcc_assert (TREE_CODE (TREE_TYPE (ptype)) == ARRAY_TYPE);
+      tree inner_type = TREE_TYPE (TREE_TYPE (ptype));
+      tree unit = TYPE_SIZE_UNIT (inner_type);
+      max_size *= tree_to_uhwi (unit);
+    }
+
+  // Check for the obviously bounded case.
+  if (TREE_CODE (len) == INTEGER_CST)
+    {
+      if (tree_to_uhwi (len) > max_size)
+	return ALLOCA_BOUND_DEFINITELY_LARGE;
+      w = ALLOCA_OK;
+    }
+  else if (TREE_CODE (len) != SSA_NAME)
+    return ALLOCA_UNBOUNDED;
+  // Check the range info if available.
+  else
+    {
+      if (value_range_type range_type = get_range_info (len, &min, &max))
+	{
+	  if (range_type == VR_RANGE)
+	    {
+	      if (wi::leu_p (max, max_size))
+		w = ALLOCA_OK;
+	      else if (is_max (len, max))
+		{
+		  // A cast may have created a range we don't care
+		  // about.  For instance, a cast from 16-bit to
+		  // 32-bit creates a range of 0..65535, even if there
+		  // is not really a determinable range in the
+		  // underlying code.  In this case, look through the
+		  // cast at the original argument, and fall through
+		  // to look at other alternatives.
+		  gimple *def = SSA_NAME_DEF_STMT (len);
+		  if (gimple_assign_cast_p (def))
+		    len = gimple_assign_rhs1 (def);
+		}
+	      else
+		{
+		  /* If `len' is merely a cast that is being
+		     calculated right before the call to alloca, look
+		     at the range for the original value.
+
+		     This avoids the cast creating a range where the
+		     original expression did not have a range:
+
+		     # RANGE [0, 18446744073709551615] NONZERO 4294967295
+		     _2 = (long unsigned int) n_7(D);
+		     p_9 = __builtin_alloca (_2);
+
+		     The correct thing would've been for the user to
+		     use size_t, which in the case above would've been
+		     'long unsigned int', and everything would've
+		     worked.  But we have to catch cases where the
+		     user is using some other compatible type for the
+		     call argument to alloca (say unsigned short).  */
+		  gimple *def = SSA_NAME_DEF_STMT (len);
+		  if (gimple_assign_cast_p (def))
+		    {
+		      len = gimple_assign_rhs1 (def);
+		      range_type = get_range_info (len, &min, &max);
+		    }
+
+		  if (range_type != VR_VARYING && is_max (len, max))
+		    {
+		      // Treat a max of the entire domain as if it had no
+		      // range info, and fall through the try other
+		      // alternatives.
+		    }
+		  else
+		    return ALLOCA_BOUND_MAYBE_LARGE;
+		}
+	    }
+	  else if (range_type == VR_ANTI_RANGE)
+	    {
+	      // There may be some wrapping around going on.
+	      if (cast_from_signed_p (len))
+		return ALLOCA_CAST_FROM_SIGNED;
+	      // Fall thru and try other things.
+	    }
+	  else if (range_type == VR_VARYING)
+	    {
+	      // No easily determined range.  Try other things.
+	    }
+	}
+    }
+
+  // If we couldn't find anything, try a few heuristics for things we
+  // can easily determine.  Check these misc cases but only accept
+  // them if all predecessors have a known bound.
+  if (w == ALLOCA_UNBOUNDED)
+    {
+      w = ALLOCA_OK;
+      for (unsigned ix = 0; ix < EDGE_COUNT (bb->preds); ix++)
+	{
+	  enum alloca_type w
+	    = alloca_call_type_by_arg (len, EDGE_PRED (bb, ix), max_size);
+	  if (w != ALLOCA_OK)
+	    return w;
+	}
+    }
+
+  return w;
+}
+
+static inline const char *
+alloca_str (bool is_vla)
+{
+  return is_vla ? "variable-length array" : "alloca";
+}
+
+// Return the warning code for -Walloca or -Wvla depending on whether
+// we are talking about a VLA.
+
+static inline enum opt_code
+Wcode (bool is_vla)
+{
+  return is_vla ? OPT_Wvla : OPT_Walloca;
+}
+
+unsigned int
+pass_walloca::execute (function *fun)
+{
+  basic_block bb;
+  FOR_EACH_BB_FN (bb, fun)
+    {
+      for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
+	   gsi_next (&si))
+	{
+	  gimple *stmt = gsi_stmt (si);
+	  location_t loc = gimple_location (stmt);
+
+	  if (!gimple_alloca_call_p (stmt))
+	    continue;
+	  gcc_assert (gimple_call_num_args (stmt) >= 1);
+
+	  // GCC emits two types of __builtin_alloca's, the
+	  // traditional __builtin_alloca and a
+	  // __builtin_alloca_with_align.  The latter gets generated
+	  // for VLA's, which means we can kill two birds with one
+	  // code.
+	  bool is_vla = DECL_FUNCTION_CODE (gimple_call_fndecl (stmt))
+					    == BUILT_IN_ALLOCA_WITH_ALIGN;
+
+	  // Strict mode whining for VLAs is handled by the front-end.
+	  if (is_vla && (!warn_vla || vla_strict_mode))
+	    continue;
+
+	  // Strict mode; warn on all alloca uses.
+	  if (!is_vla && (!warn_alloca || alloca_strict_mode))
+	    {
+	      if (alloca_strict_mode)
+		warning_at (loc, OPT_Walloca, "use of alloca");
+	      continue;
+	    }
+
+	  enum alloca_type w = alloca_call_type (stmt, is_vla);
+	  switch (w)
+	    {
+	    case ALLOCA_OK:
+	      break;
+	    case ALLOCA_BOUND_MAYBE_LARGE:
+	      warning_at (loc, Wcode (is_vla),
+			  "argument to %s may be too large",
+			  alloca_str (is_vla));
+	      break;
+	    case ALLOCA_BOUND_DEFINITELY_LARGE:
+	      warning_at (loc, Wcode (is_vla),
+			  "argument to %s is too large",
+			  alloca_str (is_vla));
+	      break;
+	    case ALLOCA_BOUND_UNKNOWN:
+	      warning_at (loc, Wcode (is_vla), "%s bound is unknown",
+			  alloca_str (is_vla));
+	      break;
+	    case ALLOCA_UNBOUNDED:
+	      warning_at (loc, Wcode (is_vla), "unbounded use of %s",
+			  alloca_str (is_vla));
+	      break;
+	    case ALLOCA_IN_LOOP:
+	      warning_at (loc, Wcode (is_vla), "use of %s within a loop",
+			  alloca_str (is_vla));
+	      break;
+	    case ALLOCA_CAST_FROM_SIGNED:
+	      warning_at (loc, Wcode (is_vla), "cast from signed type "
+			  "in %s", alloca_str (is_vla));
+	      break;
+	    default:
+	      gcc_unreachable ();
+	    }
+	}
+    }
+  return 0;
+}
+
+gimple_opt_pass *
+make_pass_walloca (gcc::context *ctxt)
+{
+  return new pass_walloca (ctxt);
+}
diff --git a/gcc/opts.c b/gcc/opts.c
index e80331f..74278a4 100644
--- a/gcc/opts.c
+++ b/gcc/opts.c
@@ -743,6 +743,28 @@  finish_options (struct gcc_options *opts, struct gcc_options *opts_set,
   if (opts->x_flag_tm && opts->x_flag_non_call_exceptions)
     sorry ("transactional memory is not supported with non-call exceptions");
 
+  /* -Walloca needs range info which is only available at -O2.  We
+      could theoretically run -Walloca with -O1, because plain
+      -Walloca warns on everything (and doesn't need range info).
+      However, the pass itself gets run within the
+      `pass_all_optimizations' framework in passes.def, which gets run
+      at -O1 and above.  To simplify matters, just bail.  */
+  if (opts->x_optimize < 2
+      && (opts->x_warn_alloca == -2
+	  || opts->x_warn_alloca > 0))
+    {
+      sorry ("-Walloca ignored without -O2");
+      opts->x_warn_alloca = 0;
+    }
+
+  /* -Wvla= needs range info which is only available at -O2.  */
+  if (opts->x_optimize < 2
+      && opts->x_warn_vla > 0)
+    {
+      sorry ("-Wvla= ignored without -O2");
+      opts->x_warn_vla = 0;
+    }
+
   /* Unless the user has asked for section anchors, we disable toplevel
      reordering at -O0 to disable transformations that might be surprising
      to end users and to get -fno-toplevel-reorder tested.  */
@@ -1777,6 +1799,20 @@  common_handle_option (struct gcc_options *opts,
       /* Currently handled in a prescan.  */
       break;
 
+    case OPT_Walloca:
+      /* Plain -Walloca will set warn_alloca to 1, but this conflicts
+         with -Walloca=1, and we can't tell the difference.  Set to -2
+         here which means -Walloca was set with no argument.  */
+      if (value == 1)
+	warn_alloca = -2;
+      break;
+
+    case OPT_Walloca_:
+      if (value == 0)
+	inform (loc,
+		"-Walloca=0 disables -Walloca.  Use -Wno-alloca instead.");
+      break;
+
     case OPT_Werror:
       dc->warning_as_error_requested = value;
       break;
diff --git a/gcc/passes.def b/gcc/passes.def
index 3647e90..4b503e8 100644
--- a/gcc/passes.def
+++ b/gcc/passes.def
@@ -303,6 +303,7 @@  along with GCC; see the file COPYING3.  If not see
       NEXT_PASS (pass_simduid_cleanup);
       NEXT_PASS (pass_lower_vector_ssa);
       NEXT_PASS (pass_cse_reciprocals);
+      NEXT_PASS (pass_walloca);
       NEXT_PASS (pass_reassoc, false /* insert_powi_p */);
       NEXT_PASS (pass_strength_reduction);
       NEXT_PASS (pass_split_paths);
diff --git a/gcc/testsuite/gcc.dg/Walloca-1.c b/gcc/testsuite/gcc.dg/Walloca-1.c
new file mode 100644
index 0000000..dc7b2a9
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-1.c
@@ -0,0 +1,49 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca=2000 -O2" } */
+
+#define alloca __builtin_alloca
+
+typedef __SIZE_TYPE__ size_t;
+extern size_t strlen(const char *);
+
+extern void useit (char *);
+
+int num;
+
+void test_walloca (size_t len, size_t len2, size_t len3)
+{
+  int i;
+
+  for (i=0; i < 123; ++i)
+    {
+      char *s = alloca (566);	/* { dg-warning "alloca within a loop" } */
+      useit (s);
+    }
+
+  char *s = alloca (123);
+  useit (s);			// OK, constant argument to alloca
+
+  s = alloca (num);		// { dg-warning "cast from signed type in alloca" }
+  useit (s);
+
+  s = alloca(90000);		/* { dg-warning "is too large" } */
+  useit (s);
+
+  if (len < 2000)
+    {
+      s = alloca(len);		// OK, bounded
+      useit (s);
+    }
+
+  if (len + len2 < 2000)	// OK, bounded
+    {
+      s = alloca(len + len2);
+      useit (s);
+    }
+
+  if (len3 <= 2001)
+    {
+      s = alloca(len3);		/* { dg-warning "may be too large" } */
+      useit(s);
+    }
+}
diff --git a/gcc/testsuite/gcc.dg/Walloca-2.c b/gcc/testsuite/gcc.dg/Walloca-2.c
new file mode 100644
index 0000000..dcf3959
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-2.c
@@ -0,0 +1,37 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca=2000 -O2" } */
+
+void f (void *);
+
+void
+g1 (int n)
+{
+  void *p;
+  if (n > 0 && n < 2000)
+    p = __builtin_alloca (n);
+  else
+    p = __builtin_malloc (n);
+  f (p);
+}
+
+void
+g2 (int n)
+{
+  void *p;
+  if (n < 2000)
+    p = __builtin_alloca (n); // { dg-warning "cast from signed type in alloca" }
+  else
+    p = __builtin_malloc (n);
+  f (p);
+}
+
+void
+g3 (int n)
+{
+  void *p;
+  if (n > 0 && n < 3000)
+    p = __builtin_alloca (n); // { dg-warning "alloca may be too large" }
+  else
+    p = __builtin_malloc (n);
+  f (p);
+}
diff --git a/gcc/testsuite/gcc.dg/Walloca-3.c b/gcc/testsuite/gcc.dg/Walloca-3.c
new file mode 100644
index 0000000..16466fa
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-3.c
@@ -0,0 +1,33 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca=2000 -O2" } */
+
+void f (void *);
+
+__SIZE_TYPE__ LIMIT;
+
+// Warn when there is an alloca bound, but it is an unknown bound.
+
+void
+g1 (__SIZE_TYPE__ n)
+{
+  void *p;
+  if (n < LIMIT)
+    p = __builtin_alloca (n); // { dg-warning "alloca bound is unknown" }
+  else
+    p = __builtin_malloc (n);
+  f (p);
+}
+
+// Similar to the above, but do not get confused by the upcast.
+
+unsigned short SHORT_LIMIT;
+void
+g2 (unsigned short n)
+{
+  void *p;
+  if (n < SHORT_LIMIT)
+    p = __builtin_alloca (n); // { dg-warning "alloca bound is unknown" }
+  else
+    p = __builtin_malloc (n);
+  f (p);
+}
diff --git a/gcc/testsuite/gcc.dg/Walloca-4.c b/gcc/testsuite/gcc.dg/Walloca-4.c
new file mode 100644
index 0000000..f910a8d
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-4.c
@@ -0,0 +1,20 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca=5000 -O2" } */
+/* { dg-xfail-if "Currently broken but Andrew's work should fix this" { *-*-* } } */
+
+// Should be another variant of Walloca-7.c.
+// This should not warn, as we have a known bound within limits.
+
+ char *
+ _i18n_number_rewrite (char *w, char *rear_ptr)
+{
+
+  char *src;
+ _Bool 
+      use_alloca = (((rear_ptr - w) * sizeof (char)) < 4096U);
+ if (use_alloca)
+    src = (char *) __builtin_alloca ((rear_ptr - w) * sizeof (char));
+  else
+    src = (char *) __builtin_malloc ((rear_ptr - w) * sizeof (char));
+  return src;
+}
diff --git a/gcc/testsuite/gcc.dg/Walloca-5.c b/gcc/testsuite/gcc.dg/Walloca-5.c
new file mode 100644
index 0000000..60d5715
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-5.c
@@ -0,0 +1,32 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca -O2" } */
+/* { dg-xfail-if "Currently broken but Andrew's work should fix this" { *-*-* } } */
+
+/* The argument to alloca ends up having a range of 0..MAXINT(32bits),
+   so we think we have a range because of the upcast.  Consequently,
+   we warn with "alloca may be too large", but we should technically
+   warn with "unbounded use of alloca".
+
+   We currently drill through casts to figure this stuff out, but we
+   get confused because it's not just a cast.  It's a cast, plus a
+   multiply.
+
+   <bb 2>:
+  # RANGE [0, 4294967295] NONZERO 4294967295
+  _1 = (long unsigned int) something_4(D);
+  # RANGE [0, 34359738360] NONZERO 34359738360
+  _2 = _1 * 8;
+  _3 = __builtin_alloca (_2);
+
+  I don't know whether it's even worth such fine-grained warnings.
+  Perhaps we should generically warn everywhere with "alloca may be
+  too large".
+
+  I'm hoping that this particular case will be easier to diagnose with
+  Andrew's work.  */
+
+void useit(void *);
+void foobar(unsigned int something)
+{
+  useit(__builtin_alloca (something * sizeof (const char *))); // { dg-warning "unbounded use of alloca" "" { xfail *-*-* } }
+}
diff --git a/gcc/testsuite/gcc.dg/Walloca-6.c b/gcc/testsuite/gcc.dg/Walloca-6.c
new file mode 100644
index 0000000..e89e74b
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Walloca-6.c
@@ -0,0 +1,11 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca -O2" } */
+/* { dg-xfail-if "Currently broken but Andrew's work should fix this" { *-*-* } } */
+
+void f (void*);
+void g (__SIZE_TYPE__ n)
+{
+  // No warning on this case.  Range is easily determinable.
+  if (n > 0 && n < 256)
+    f (__builtin_alloca (n));
+}
diff --git a/gcc/testsuite/gcc.dg/Wvla-1.c b/gcc/testsuite/gcc.dg/Wvla-1.c
new file mode 100644
index 0000000..a1b939f
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Wvla-1.c
@@ -0,0 +1,24 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Wvla=100 -O2" } */
+
+typedef __SIZE_TYPE__ size_t;
+
+extern void useit (char *);
+
+int num;
+
+void test_vlas (size_t num)
+{
+  char str2[num];		/* { dg-warning "unbounded use" } */
+  useit(str2);
+
+  num = 98;
+  for (int i=0; i < 1234; ++i) {
+    char str[num];	        // OK, VLA in a loop, but it is a
+				// known size *AND* the compiler takes
+				// care of cleaning up between
+				// iterations with
+				// __builtin_stack_restore.
+    useit(str);
+  }
+}
diff --git a/gcc/testsuite/gcc.dg/Wvla-2.c b/gcc/testsuite/gcc.dg/Wvla-2.c
new file mode 100644
index 0000000..353bf58
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Wvla-2.c
@@ -0,0 +1,22 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Wvla=2000 -O2" } */
+
+void f (void*);
+
+void h1 (unsigned n)
+{
+  if (n <= 2001)
+    {
+      int a [n]; // { dg-warning "variable-length array may be too large" }
+      f (a);
+    }
+}
+
+void h2 (unsigned n)
+{
+  if (n <= 2000)
+    {
+      int a [n];
+      f (a);
+    }
+}
diff --git a/gcc/testsuite/gcc.dg/Wvla-3.c b/gcc/testsuite/gcc.dg/Wvla-3.c
new file mode 100644
index 0000000..5124476
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Wvla-3.c
@@ -0,0 +1,12 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Walloca -O2" } */
+
+// Make sure we don't warn on VLA with -Walloca.
+
+void f (void*);
+
+void h1 (unsigned n)
+{
+  int a [n];
+  f (a);
+}
diff --git a/gcc/tree-pass.h b/gcc/tree-pass.h
index 36299a6..57b61f4 100644
--- a/gcc/tree-pass.h
+++ b/gcc/tree-pass.h
@@ -469,6 +469,7 @@  extern simple_ipa_opt_pass *make_pass_ipa_oacc (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_ipa_oacc_kernels (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_gen_hsail (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_warn_nonnull_compare (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_walloca (gcc::context *ctxt);
 
 /* IPA Passes */
 extern simple_ipa_opt_pass *make_pass_ipa_lower_emutls (gcc::context *ctxt);