[LLVMdev] optimization assumes malloc return is non-null

Chris Lattner sabre at nondot.org
Thu May 1 15:54:25 PDT 2008


On Thu, 1 May 2008, Sandro Magi wrote:
>>  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.
>
> I don't see how this could be true in general, without either
> knowledge of the malloc implementation, which would be fine, or
> presuming knowledge of the target, which would not be fine. If
> "malloc(sizeof(int))" were changed to "malloc(3245677423)", would it
> still be eliminated?

Would it cause your head to explode if you knew that llvm optimizes this:

static char* G;
void foo() {
   G = malloc(sizeof(char));
}
char get() { return *G; }
void set(char x) { *G = x; }

into this (note the lack of malloc):

@G.body = internal global i8 undef		; <i8*> [#uses=2]
define i8 @get() signext nounwind  {
entry:
 	%tmp2 = load i8* @G.body, align 1		; <i8> [#uses=1]
 	ret i8 %tmp2
}
define void @set(i8 signext  %x) nounwind  {
entry:
 	store i8 %x, i8* @G.body, align 1
 	ret void
}
define void @foo() nounwind  {
entry:
 	ret void
}

?

This is safe even without "whole program" information.  I love the as-if 
rule ;-)

-Chris

-- 
http://nondot.org/sabre/
http://llvm.org/



More information about the llvm-dev mailing list