Skip to content

Commit 652cd7c

Browse files
committed
[InstCombine] Fix user iterator invalidation in bitcast of phi transform
This fixes the issue encountered in D71164. Instead of using a range-based for, manually iterate over the users and advance the iterator beforehand, so we do not skip any users due to iterator invalidation. Differential Revision: https://reviews.llvm.org/D72657
1 parent fa63234 commit 652cd7c

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed

llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2344,7 +2344,10 @@ Instruction *InstCombiner::optimizeBitCastFromPhi(CastInst &CI, PHINode *PN) {
23442344
Instruction *RetVal = nullptr;
23452345
for (auto *OldPN : OldPhiNodes) {
23462346
PHINode *NewPN = NewPNodes[OldPN];
2347-
for (User *V : OldPN->users()) {
2347+
for (auto It = OldPN->user_begin(), End = OldPN->user_end(); It != End; ) {
2348+
User *V = *It;
2349+
// We may remove this user, advance to avoid iterator invalidation.
2350+
++It;
23482351
if (auto *SI = dyn_cast<StoreInst>(V)) {
23492352
assert(SI->isSimple() && SI->getOperand(0) == OldPN);
23502353
Builder.SetInsertPoint(SI);

llvm/test/Transforms/InstCombine/bitcast-phi-uselistorder.ll

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,13 @@ define double @test(i1 %c, i64* %p) {
88
; CHECK-NEXT: entry:
99
; CHECK-NEXT: br i1 [[C:%.*]], label [[IF:%.*]], label [[END:%.*]]
1010
; CHECK: if:
11-
; CHECK-NEXT: [[LOAD:%.*]] = load i64, i64* bitcast (double* @Q to i64*), align 8
12-
; CHECK-NEXT: [[TMP0:%.*]] = bitcast i64 [[LOAD]] to double
13-
; CHECK-NEXT: [[PHITMP:%.*]] = bitcast i64 [[LOAD]] to double
11+
; CHECK-NEXT: [[LOAD1:%.*]] = load double, double* @Q, align 8
1412
; CHECK-NEXT: br label [[END]]
1513
; CHECK: end:
16-
; CHECK-NEXT: [[TMP1:%.*]] = phi double [ 0.000000e+00, [[ENTRY:%.*]] ], [ [[TMP0]], [[IF]] ]
17-
; CHECK-NEXT: [[PHI:%.*]] = phi double [ 0.000000e+00, [[ENTRY]] ], [ [[PHITMP]], [[IF]] ]
18-
; CHECK-NEXT: [[TMP2:%.*]] = bitcast i64* [[P:%.*]] to double*
19-
; CHECK-NEXT: store double [[TMP1]], double* [[TMP2]], align 8
20-
; CHECK-NEXT: ret double [[PHI]]
14+
; CHECK-NEXT: [[TMP0:%.*]] = phi double [ 0.000000e+00, [[ENTRY:%.*]] ], [ [[LOAD1]], [[IF]] ]
15+
; CHECK-NEXT: [[TMP1:%.*]] = bitcast i64* [[P:%.*]] to double*
16+
; CHECK-NEXT: store double [[TMP0]], double* [[TMP1]], align 8
17+
; CHECK-NEXT: ret double [[TMP0]]
2118
;
2219
entry:
2320
br i1 %c, label %if, label %end

0 commit comments

Comments
 (0)