Compiler projects using llvm
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; REQUIRES: x86-registered-target
; RUN: opt -loop-reduce -S < %s | FileCheck %s

; Strength reduction analysis here relies on IV Users analysis, that
; only finds users among instructions with types that are treated as
; legal by the data layout. When running this test on pure non-x86
; configs (for example, ARM 64), it gets confused with the target
; triple and uses a default data layout instead. This default layout
; does not have any legal types (even i32), so the transformation
; does not happen.

target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx"

; PR15470: LSR miscompile. The test2 function should return '1'.
;
; SCEV expander cannot expand quadratic recurrences outside of the
; loop. This recurrence depends on %sub.us, so can't be expanded.
; We cannot fold SCEVUnknown (sub.us) with recurrences since it is
; declared after the loop.
define i32 @test2(i32 %a, i32 %b) {
; CHECK-LABEL: @test2(
; CHECK-NEXT:  entry:
; CHECK-NEXT:    br label [[TEST2_LOOP:%.*]]
; CHECK:       test2.loop:
; CHECK-NEXT:    [[LSR_IV1:%.*]] = phi i32 [ [[LSR_IV_NEXT2:%.*]], [[TEST2_LOOP]] ], [ -16777216, [[ENTRY:%.*]] ]
; CHECK-NEXT:    [[LSR_IV:%.*]] = phi i32 [ [[LSR_IV_NEXT:%.*]], [[TEST2_LOOP]] ], [ 1, [[ENTRY]] ]
; CHECK-NEXT:    [[INC1115_US:%.*]] = phi i32 [ 0, [[ENTRY]] ], [ [[INC11_US:%.*]], [[TEST2_LOOP]] ]
; CHECK-NEXT:    [[INC11_US]] = add nsw i32 [[INC1115_US]], 1
; CHECK-NEXT:    [[LSR_IV_NEXT]] = add nsw i32 [[LSR_IV]], -1
; CHECK-NEXT:    [[LSR_IV_NEXT2]] = add nsw i32 [[LSR_IV1]], 16777216
; CHECK-NEXT:    [[CMP_US:%.*]] = icmp slt i32 [[INC11_US]], 2
; CHECK-NEXT:    br i1 [[CMP_US]], label [[TEST2_LOOP]], label [[FOR_END:%.*]]
; CHECK:       for.end:
; CHECK-NEXT:    [[TOBOOL_US:%.*]] = icmp eq i32 [[LSR_IV_NEXT]], 0
; CHECK-NEXT:    [[SUB_US:%.*]] = select i1 [[TOBOOL_US]], i32 [[A:%.*]], i32 [[B:%.*]]
; CHECK-NEXT:    [[TMP0:%.*]] = sub i32 0, [[SUB_US]]
; CHECK-NEXT:    [[TMP1:%.*]] = sub i32 [[TMP0]], [[LSR_IV_NEXT]]
; CHECK-NEXT:    [[SEXT_US:%.*]] = mul i32 [[LSR_IV_NEXT2]], [[TMP1]]
; CHECK-NEXT:    [[F:%.*]] = ashr i32 [[SEXT_US]], 24
; CHECK-NEXT:    br label [[EXIT:%.*]]
; CHECK:       exit:
; CHECK-NEXT:    ret i32 [[F]]
;
entry:
  br label %test2.loop

test2.loop:
  %inc1115.us = phi i32 [ 0, %entry ], [ %inc11.us, %test2.loop ]
  %inc11.us = add nsw i32 %inc1115.us, 1
  %cmp.us = icmp slt i32 %inc11.us, 2
  br i1 %cmp.us, label %test2.loop, label %for.end

for.end:
  %tobool.us = icmp eq i32 %inc1115.us, 0
  %sub.us = select i1 %tobool.us, i32 %a, i32 %b
  %mul.us = shl i32 %inc1115.us, 24
  %sub.cond.us = sub nsw i32 %inc1115.us, %sub.us
  %sext.us = mul i32 %mul.us, %sub.cond.us
  %f = ashr i32 %sext.us, 24
  br label %exit

exit:
  ret i32 %f
}