Index: lib/Transforms/InstCombine/InstructionCombining.cpp =================================================================== --- lib/Transforms/InstCombine/InstructionCombining.cpp +++ lib/Transforms/InstCombine/InstructionCombining.cpp @@ -1544,13 +1544,13 @@ if (!shouldMergeGEPs(*cast(&GEP), *Src)) return nullptr; - // Note that if our source is a gep chain itself then we wait for that - // chain to be resolved before we perform this transformation. This - // avoids us creating a TON of code in some cases. - if (GEPOperator *SrcGEP = - dyn_cast(Src->getOperand(0))) - if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) - return nullptr; // Wait until our source is folded to completion. + // Note that if our source is a gep chain itself having more than one use + // then we wait for that chain to be resolved before we perform this + // transformation. This avoids us creating a TON of code in some cases. + if (!Src->hasOneUse()) + if (GEPOperator *SrcGEP = dyn_cast(Src->getOperand(0))) + if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) + return nullptr; // Wait until our source is folded to completion. SmallVector Indices; Index: test/Transforms/InstCombine/getelementptr.ll =================================================================== --- test/Transforms/InstCombine/getelementptr.ll +++ test/Transforms/InstCombine/getelementptr.ll @@ -931,4 +931,16 @@ ret i32 addrspace(1)* %x } +define i32* @resolve_gep_chains(%pair* %p, i64 %i) { +; CHECK-LABEL: @resolve_gep_chains( +; CHECK-NEXT: [[TMP0:%.*]] = getelementptr %pair, %pair* %p, i64 %i +; CHECK-NEXT: [[TMP2:%.*]] = getelementptr %pair, %pair* [[TMP0]], i64 1, i32 1 +; CHECK-NEXT: ret i32* [[TMP2]] +; + %tmp0 = getelementptr %pair, %pair* %p, i64 %i + %tmp1 = getelementptr %pair, %pair* %tmp0, i64 1 + %tmp2 = getelementptr %pair, %pair* %tmp1, i64 0, i32 1 + ret i32* %tmp2 +} + ; CHECK: attributes [[NUW]] = { nounwind }