On Thu, May 1, 2008 at 5:10 PM, Daniel Berlin <[EMAIL PROTECTED]> wrote: > > Sure, a malloc call has side-effects, so a DCE pass cannot just remove it. > > Only struct-reorg knows that it has replaced all side-effects with others. > > Malloc only has side effects if the result is used. > > > For example, LLVM will transform > > > int main(int argc, char** argv){ > if(malloc(sizeof(int)) == NULL){ return 0; } > else{ return 1; } > } > > into return 1 > > There is a thread going on in the llvm mailing lists about this right > now, and so far all the text people can find in standards says this is > okay (though I think susv2/POSIX says differently). > > Chris says: > " > LLVM should not (and does not, afaik) assume the malloc succeeds in > general. > > If LLVM is able to eliminate all users of the malloc assuming the > malloc succeeded (as in this case), then it is safe to assume the malloc > returned success."
BTW, the argument goes something like this: Transforming malloc into: our_malloc(int size) { if (callsite == the one being compared against null) { static char buf[size] __attribute__(maximally_aligned) return (void *)buf; } else return malloc(size) } is legal, and would produce a result that is always non-null. Thus, if you can eliminate all users of your malloc under the assumption that malloc returns non-null, you can do so and delete the malloc. This also means that things like if (malloc(x) == 0x12345678) <do something> would *not* be transformed into "if (1)", only those cases where the behavior of malloc is checked for nullness.