Index: lib/Transforms/Scalar/SROA.cpp =================================================================== --- lib/Transforms/Scalar/SROA.cpp +++ lib/Transforms/Scalar/SROA.cpp @@ -2708,7 +2708,10 @@ // the old pointer, which necessarily must be in the right position to // dominate the PHI. IRBuilderTy PtrBuilder(IRB); - PtrBuilder.SetInsertPoint(OldPtr); + if (isa(OldPtr)) + PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt()); + else + PtrBuilder.SetInsertPoint(OldPtr); PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc()); Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType()); Index: test/Transforms/SROA/phi-and-select.ll =================================================================== --- test/Transforms/SROA/phi-and-select.ll +++ test/Transforms/SROA/phi-and-select.ll @@ -566,3 +566,31 @@ %4 = load float* %3, align 4 ret float %4 } + +%struct.S = type { i32 } + +define void @PR20822() { +entry: + %f = alloca %struct.S, align 4 +; CHECK: %[[alloca:.*]] = alloca + br i1 undef, label %if.end, label %for.cond + +for.cond: ; preds = %for.cond, %entry + br label %if.end + +if.end: ; preds = %for.cond, %entry + %f2 = phi %struct.S* [ %f, %entry ], [ %f, %for.cond ] +; CHECK: phi i32 +; CHECK: %[[cast:.*]] = bitcast i32* %[[alloca]] to %struct.S* + phi i32 [ undef, %entry ], [ undef, %for.cond ] + br i1 undef, label %if.then5, label %if.then2 + +if.then2: ; preds = %if.end + br label %if.then5 + +if.then5: ; preds = %if.then2, %if.end + %f1 = phi %struct.S* [ undef, %if.then2 ], [ %f2, %if.end ] +; CHECK: phi {{.*}} %[[cast]] + store %struct.S undef, %struct.S* %f1, align 4 + ret void +}