File: GenXLscAddrCalcFolding.cpp

package info (click to toggle)
intel-graphics-compiler2 2.28.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 792,744 kB
  • sloc: cpp: 5,761,745; ansic: 466,928; lisp: 312,143; python: 114,790; asm: 44,736; pascal: 10,930; sh: 8,033; perl: 7,914; ml: 3,625; awk: 3,523; yacc: 2,747; javascript: 2,667; lex: 1,898; f90: 1,028; cs: 573; xml: 474; makefile: 344; objc: 162
file content (610 lines) | stat: -rw-r--r-- 19,542 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*========================== begin_copyright_notice ============================

Copyright (C) 2024-2025 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "GenXSubtarget.h"
#include "GenXTargetMachine.h"

#include "vc/Support/BackendConfig.h"
#include "vc/Utils/GenX/Intrinsics.h"
#include "vc/Utils/GenX/IntrinsicsWrapper.h"

#include "llvmWrapper/IR/Instructions.h"
#include "llvmWrapper/Support/MathExtras.h"

#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/KnownBits.h"

#define DEBUG_TYPE "genx-lsc-addr-calc-folding"

using namespace llvm;
using namespace genx;

namespace {
class GenXLscAddrCalcFolding : public FunctionPass,
                               public InstVisitor<GenXLscAddrCalcFolding> {
public:
  static char ID;
  GenXLscAddrCalcFolding() : FunctionPass(ID) {}

  StringRef getPassName() const override {
    return "GenX LSC Address Calculation Folding";
  }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<GenXBackendConfig>();
    AU.addRequired<TargetPassConfig>();
    AU.setPreservesCFG();
  }

  bool runOnFunction(Function &F) override;
  void visitCallInst(CallInst &CI);

private:
  bool foldLscAddrCalculation(CallInst &CI);
  bool foldLscAddrBase(CallInst &CI);
  bool foldLscAddrExtend(CallInst &CI);

  Value *applyLscAddrConstFolding(Value *Offsets, APInt &Scale, APInt &Offset);

  Value *applyLscAddrFolding(Value *Offsets, APInt &Scale, APInt &Offset,
                             CallInst *Inst);

  static constexpr unsigned Block2DIndexX = 10;
  static constexpr unsigned Block2DIndexY = 11;
  static constexpr unsigned Block2DOffsetX = 12;
  static constexpr unsigned Block2DOffsetY = 13;

  bool foldLscBlock2DAddrCalculation(CallInst &CI, unsigned IndexArg,
                                     unsigned OffsetArg);

  const GenXBackendConfig *BC = nullptr;
  const GenXSubtarget *ST = nullptr;

  unsigned Supported2DOffsetBits = 0;
  bool Changed = false;

  unsigned OffsetAlignment = 0;

  unsigned AllowedScale = 1;
};

} // namespace

char GenXLscAddrCalcFolding::ID = 0;

namespace llvm {
void initializeGenXLscAddrCalcFoldingPass(PassRegistry &);
} // namespace llvm

INITIALIZE_PASS_BEGIN(GenXLscAddrCalcFolding, "GenXLscAddrCalcFolding",
                      "GenXLscAddrCalcFolding", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
INITIALIZE_PASS_DEPENDENCY(GenXBackendConfig)
INITIALIZE_PASS_END(GenXLscAddrCalcFolding, "GenXLscAddrCalcFolding",
                    "GenXLscAddrCalcFolding", false, false)

FunctionPass *llvm::createGenXLscAddrCalcFoldingPass() {
  initializeGenXLscAddrCalcFoldingPass(*PassRegistry::getPassRegistry());
  return new GenXLscAddrCalcFolding();
}

bool GenXLscAddrCalcFolding::runOnFunction(Function &F) {
  BC = &getAnalysis<GenXBackendConfig>();
  ST = &getAnalysis<TargetPassConfig>()
            .getTM<GenXTargetMachine>()
            .getGenXSubtarget();

  if (!ST->hasLSCMessages() || !ST->hasLSCOffset())
    return false;

  Changed = false;
  visit(F);
  return Changed;
}

void GenXLscAddrCalcFolding::visitCallInst(CallInst &CI) {
  IGC_ASSERT(ST->hasLSCMessages() && ST->hasLSCOffset());

  const auto IID = vc::getAnyIntrinsicID(&CI);

  switch (IID) {
  default:
    break;
  case vc::InternalIntrinsic::lsc_atomic_ugm:
  case vc::InternalIntrinsic::lsc_load_ugm:
  case vc::InternalIntrinsic::lsc_load_quad_ugm:
  case vc::InternalIntrinsic::lsc_prefetch_ugm:
  case vc::InternalIntrinsic::lsc_prefetch_quad_ugm:
  case vc::InternalIntrinsic::lsc_store_ugm:
  case vc::InternalIntrinsic::lsc_store_quad_ugm:
  case vc::InternalIntrinsic::lsc_atomic_slm:
  case vc::InternalIntrinsic::lsc_load_slm:
  case vc::InternalIntrinsic::lsc_load_quad_slm:
  case vc::InternalIntrinsic::lsc_store_slm:
  case vc::InternalIntrinsic::lsc_store_quad_slm:
    if (ST->hasLSCBase()) {
      Changed |= foldLscAddrCalculation(CI);
      Changed |= foldLscAddrBase(CI);
      Changed |= foldLscAddrCalculation(CI);
      Changed |= foldLscAddrExtend(CI);
    }
    LLVM_FALLTHROUGH;
  case vc::InternalIntrinsic::lsc_atomic_bti:
  case vc::InternalIntrinsic::lsc_load_bti:
  case vc::InternalIntrinsic::lsc_load_quad_bti:
  case vc::InternalIntrinsic::lsc_prefetch_bti:
  case vc::InternalIntrinsic::lsc_prefetch_quad_bti:
  case vc::InternalIntrinsic::lsc_store_bti:
  case vc::InternalIntrinsic::lsc_store_quad_bti:
    Changed |= foldLscAddrCalculation(CI);
    break;
  case vc::InternalIntrinsic::lsc_load_block_2d_ugm:
  case vc::InternalIntrinsic::lsc_load_block_2d_ugm_transposed:
  case vc::InternalIntrinsic::lsc_load_block_2d_ugm_vnni:
  case vc::InternalIntrinsic::lsc_prefetch_block_2d_ugm:
  case vc::InternalIntrinsic::lsc_store_block_2d_ugm:
    Changed |= foldLscBlock2DAddrCalculation(CI, Block2DIndexX, Block2DOffsetX);
    Changed |= foldLscBlock2DAddrCalculation(CI, Block2DIndexY, Block2DOffsetY);
    break;
  }
}

bool GenXLscAddrCalcFolding::foldLscBlock2DAddrCalculation(CallInst &CI,
                                                           unsigned IndexArg,
                                                           unsigned OffsetArg) {
  IGC_ASSERT(ST->hasLSCMessages() && ST->hasLSCOffset());

  auto *Index = CI.getArgOperand(IndexArg);
  auto *OldIndex = Index;
  auto Offset = cast<ConstantInt>(CI.getArgOperand(OffsetArg))->getValue();

  while (auto *BO = dyn_cast<BinaryOperator>(Index)) {
    auto Opcode = BO->getOpcode();
    if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
      break;

    auto *Const = dyn_cast<ConstantInt>(BO->getOperand(1));
    if (!Const)
      break;

    auto ConstValue = Const->getValue();

    APInt NewOffset;
    bool Overflow = false;

    switch (Opcode) {
    case Instruction::Add:
      NewOffset = Offset.sadd_ov(ConstValue, Overflow);
      break;
    case Instruction::Sub:
      NewOffset = Offset.ssub_ov(ConstValue, Overflow);
      break;
    default:
      llvm_unreachable("Unexpected opcode");
    }

    if (Overflow)
      break;

    Offset = std::move(NewOffset);
    Index = BO->getOperand(0);

    LLVM_DEBUG(dbgs() << "LSC address folding found, index: " << *Index
                      << ", offset: " << Offset.getSExtValue() << "\n");
  }

  if (Index == OldIndex)
    return false;

  const auto OffsetV = Offset.getSExtValue();
  const auto ElementSizeBits =
      vc::InternalIntrinsic::getMemoryRegisterElementSize(&CI);
  if (OffsetV * ElementSizeBits % genx::DWordBits != 0) {
    LLVM_DEBUG(dbgs() << "Offset is not dword-aligned\n");
    return false;
  }

  IRBuilder<> Builder(&CI);

  LLVM_DEBUG(dbgs() << "Folding LSC address calculation for instruction: " << CI
                    << "\n");
  CI.setArgOperand(IndexArg, Index);
  CI.setArgOperand(OffsetArg, Builder.getInt32(OffsetV));
  LLVM_DEBUG(dbgs() << "Updated instruction: " << CI << "\n");

  return true;
}

bool GenXLscAddrCalcFolding::foldLscAddrCalculation(CallInst &Inst) {
  constexpr unsigned AddrIndex = 6, ScaleIndex = 7, OffsetIndex = 8;

  IGC_ASSERT(ST->hasLSCMessages() && ST->hasLSCOffset());
  IGC_ASSERT_MESSAGE(isa<ConstantInt>(Inst.getOperand(ScaleIndex)) &&
                         isa<ConstantInt>(Inst.getOperand(OffsetIndex)),
                     "Scale and Offset must be constant");

  bool Changed = false;
  auto *Index = Inst.getOperand(AddrIndex);
  auto Scale = cast<ConstantInt>(Inst.getOperand(ScaleIndex))->getValue();
  auto Offset = cast<ConstantInt>(Inst.getOperand(OffsetIndex))->getValue();

  OffsetAlignment = vc::InternalIntrinsic::getMemoryRegisterElementSize(&Inst) /
                    genx::ByteBits;

  AllowedScale = vc::InternalIntrinsic::getMemoryRegisterElementSize(&Inst) *
                 vc::InternalIntrinsic::getMemoryVectorSizePerLane(&Inst) /
                 genx::ByteBits;

  AllowedScale = isPowerOf2_32(AllowedScale) ? AllowedScale : 1;
  AllowedScale = std::min(AllowedScale, ST->getLSCScaleMax());

  while (auto *NewIndex = applyLscAddrFolding(Index, Scale, Offset, &Inst)) {
    Index = NewIndex;
    Changed = true;
    LLVM_DEBUG(dbgs() << "LSC address folding found, index: " << *Index
                      << ", scale: " << Scale.getZExtValue()
                      << ", offset: " << Offset.getSExtValue() << "\n");
  }

  if (Changed) {
    IRBuilder<> Builder(&Inst);
    LLVM_DEBUG(dbgs() << "Folding LSC address calculation for instruction: "
                      << Inst << "\n");
    auto OffsetV = Offset.getSExtValue();
    if (vc::InternalIntrinsic::isSlmIntrinsic(&Inst) &&
        (OffsetV & SlmNullProtectionMask) == genx::SlmNullProtection)
      OffsetV &= ~SlmNullProtectionMask;

    Inst.setOperand(AddrIndex, Index);
    Inst.setOperand(ScaleIndex, Builder.getInt16(Scale.getZExtValue()));
    Inst.setOperand(OffsetIndex, Builder.getInt32(OffsetV));
    LLVM_DEBUG(dbgs() << "Updated instruction: " << Inst << "\n");
  }

  return Changed;
}

// applyLscAddrFolding : fold address calculation of LSC intrinsics
//
// Addr = Offsets * Scale + Offsets
//
// If Offsets is add-like operation (Offsets = Offsets0 + Imm0), it can be
// folded in new ImmOffset.
//
// If Offsets is mul-like operation (Offsets = Offsets0 * Imm0), it can be
// folded in new Scale
//
// This folding is done iteratively for chains of such operations.
//
Value *GenXLscAddrCalcFolding::applyLscAddrFolding(Value *Offsets, APInt &Scale,
                                                   APInt &Offset,
                                                   CallInst *Inst) {
  LLVM_DEBUG(dbgs() << "applyLscAddrFolding instruction: " << Inst << "\n");
  IGC_ASSERT(ST->hasLSCMessages() && ST->hasLSCOffset());

  if (isa<ConstantDataVector>(Offsets))
    return applyLscAddrConstFolding(Offsets, Scale, Offset);

  if (!isa<BinaryOperator>(Offsets))
    return nullptr;

  auto *BinOp = cast<BinaryOperator>(Offsets);

  unsigned ConstIdx;
  if (isa<Constant>(BinOp->getOperand(0)))
    ConstIdx = 0;
  else if (isa<Constant>(BinOp->getOperand(1)))
    ConstIdx = 1;
  else
    return nullptr;

  auto *ConstOp = cast<Constant>(BinOp->getOperand(ConstIdx));
  if (!isa<ConstantInt>(ConstOp) &&
      (!ConstOp->getType()->isVectorTy() || !ConstOp->getSplatValue()))
    return nullptr;

  Value *NewOffsets = BinOp->getOperand(1 - ConstIdx);

  auto Imm = ConstOp->getUniqueInteger();
  auto NewScale(Scale);
  auto NewOffset(Offset);
  bool Overflow = false;

  const auto Opcode = BinOp->getOpcode();

  switch (Opcode) {
  default:
    return nullptr;
  case Instruction::Add:
  case Instruction::Sub:
    if (Imm.getSignificantBits() > Offset.getBitWidth())
      return nullptr;
    Imm = Imm.sextOrTrunc(Offset.getBitWidth())
              .smul_ov(Scale.zext(Offset.getBitWidth()), Overflow);
    if (Overflow)
      return nullptr;
    if (Opcode == Instruction::Add)
      NewOffset = Offset.sadd_ov(Imm, Overflow);
    else if (Opcode == Instruction::Sub)
      NewOffset = Offset.ssub_ov(Imm, Overflow);
    break;
  case Instruction::Mul:
    if (ST->getLSCScaleMax() == 1)
      return nullptr;
    if (!Imm.isIntN(Scale.getBitWidth()))
      return nullptr;
    if (Imm.getBitWidth() > Scale.getBitWidth())
      Imm = Imm.trunc(Scale.getBitWidth());
    NewScale = Scale.umul_ov(Imm, Overflow);
    break;
  case Instruction::Shl:
    if (ST->getLSCScaleMax() == 1)
      return nullptr;
    NewScale = Scale.ushl_ov(Imm, Overflow);
    break;
  }

  if (Overflow)
    return nullptr;

  if (auto NewOffsetVal = NewOffset.getSExtValue();
      NewOffsetVal % OffsetAlignment != 0)
    return nullptr;

  if (auto NewScaleVal = NewScale.getZExtValue();
      NewScaleVal != AllowedScale && NewScaleVal != 1)
    return nullptr;

  Scale = std::move(NewScale);
  Offset = std::move(NewOffset);

  return NewOffsets;
}

Value *GenXLscAddrCalcFolding::applyLscAddrConstFolding(Value *Offsets,
                                                        APInt &Scale,
                                                        APInt &Offset) {
  IGC_ASSERT(ST->hasLSCMessages() && ST->hasLSCOffset());

  auto *Const = cast<ConstantDataVector>(Offsets);
  if (ST->getLSCScaleMax() == 1)
    return nullptr;

  auto *Ty = Const->getType()->getElementType();
  if (!Ty->isIntegerTy(32))
    return nullptr;
  if (Const->getSplatValue() != nullptr)
    return nullptr;

  // Try to fold 32-bit constant indices
  uint32_t Mask = 0;
  int32_t Min = std::numeric_limits<int32_t>::max();

  SmallVector<int32_t, 32> Values;
  for (unsigned I = 0; I < Const->getType()->getNumElements(); I++) {
    auto V = Const->getAggregateElement(I)->getUniqueInteger().getSExtValue();
    Values.push_back(V);
    Mask |= V;
    if (V < Min)
      Min = V;
  }

  auto Shift = IGCLLVM::countr_zero(Mask);
  IGC_ASSERT(Shift < 32);

  bool Overflow = false;

  APInt Imm(32, Min);
  Imm = Imm.smul_ov(Scale.sext(32), Overflow);
  if (Overflow)
    return nullptr;

  auto NewOffset = Offset.sadd_ov(Imm, Overflow);
  if (Overflow)
    return nullptr;

  Offset = std::move(NewOffset);

  auto NewScale = Scale.ushl_ov(APInt(16, Shift), Overflow);
  if (Overflow || NewScale.getZExtValue() > ST->getLSCScaleMax())
    Shift = 0;
  else
    Scale = std::move(NewScale);

  if (Min == 0 && Shift == 0)
    return nullptr;

  SmallVector<Constant *, 32> NewOffsets;
  transform(Values, std::back_inserter(NewOffsets), [&](uint32_t V) {
    return ConstantInt::getSigned(Ty, (V - Min) >> Shift);
  });

  return ConstantVector::get(NewOffsets);
}

bool GenXLscAddrCalcFolding::foldLscAddrExtend(CallInst &Inst) {
  IGC_ASSERT(vc::InternalIntrinsic::isInternalMemoryIntrinsic(&Inst));
  constexpr unsigned AddrIdx = 6;

  auto *Addr = Inst.getArgOperand(AddrIdx);
  auto *Ty = Addr->getType();
  if (!Ty->isIntOrIntVectorTy(64))
    return false;

  IRBuilder<> Builder(&Inst);

  auto NewAddrSize = LSC_ADDR_SIZE_INVALID;
  Value *NewAddr = nullptr;
  if (auto *Const = dyn_cast<ConstantDataVector>(Addr)) {
    // Try to fold 32-bit constant indices
    SmallVector<Constant *, 32> Values;
    for (unsigned I = 0; I < Const->getType()->getNumElements(); I++) {
      auto V = Const->getAggregateElement(I)->getUniqueInteger();
      if (V.getSignificantBits() > 32)
        return false;
      Values.push_back(Builder.getInt32(V.getSExtValue()));
    }
    NewAddrSize = LSC_ADDR_SIZE_32bS;
    NewAddr = ConstantVector::get(Values);
  } else {
    if (isa<SExtInst>(Addr))
      NewAddrSize = LSC_ADDR_SIZE_32bS;
    else if (isa<ZExtInst>(Addr))
      NewAddrSize = LSC_ADDR_SIZE_32bU;
    else
      return false;

    auto *Cast = cast<CastInst>(Addr);
    NewAddr = Cast->getOperand(0);
  }

  auto *NewTy = NewAddr->getType();
  if (!NewTy->isIntOrIntVectorTy(32))
    return false;

  auto IID = vc::getAnyIntrinsicID(&Inst);
  unsigned AddrSizeIdx = IID == vc::InternalIntrinsic::lsc_atomic_ugm ? 2 : 1;

  SmallVector<Type *, 3> Types;
  if (vc::InternalIntrinsic::isOverloadedRet(IID))
    Types.push_back(Inst.getType());

  for (unsigned I = 0; I < IGCLLVM::getNumArgOperands(&Inst); I++)
    if (vc::InternalIntrinsic::isOverloadedArg(IID, I))
      Types.push_back(I == AddrIdx ? NewTy : Inst.getArgOperand(I)->getType());

  auto *NewFunc = vc::getAnyDeclaration(Inst.getModule(), IID, Types);

  LLVM_DEBUG(dbgs() << "Folding LSC address extend for instruction: " << Inst
                    << "\n");
  Inst.setArgOperand(AddrSizeIdx, Builder.getInt8(NewAddrSize));
  Inst.setArgOperand(AddrIdx, NewAddr);
  Inst.setCalledFunction(NewFunc);
  LLVM_DEBUG(dbgs() << "Updated instruction: " << Inst << "\n");

  return true;
}

static Value *getBaseCandidate(Value *V) {
  if (isa<PtrToIntInst>(V))
    return V;

  // Check for splat shuffle
  if (auto *Shuffle = dyn_cast<ShuffleVectorInst>(V);
      Shuffle && Shuffle->isZeroEltSplat()) {
    auto *Src = Shuffle->getOperand(0);
    if (auto *Ins = dyn_cast<InsertElementInst>(Src)) {
      auto *Index = dyn_cast<ConstantInt>(Ins->getOperand(2));
      if (Index && Index->isZeroValue())
        return Ins->getOperand(1);
    }

    IRBuilder<> Builder(Shuffle);
    return Builder.CreateExtractElement(Src, Builder.getInt32(0));
  }

  if (!GenXIntrinsic::isRdRegion(V))
    return nullptr;

  auto *RdRegion = cast<CallInst>(V);
  auto *Src = RdRegion->getArgOperand(0);
  auto *VStride = cast<ConstantInt>(RdRegion->getArgOperand(1));
  auto *Stride = cast<ConstantInt>(RdRegion->getArgOperand(3));
  auto *Offset = RdRegion->getArgOperand(4);
  auto *OrigWidth = RdRegion->getArgOperand(5);
  auto *OffsetTy = Offset->getType();

  // Not a splat
  if (VStride->getZExtValue() != 0 || Stride->getZExtValue() != 0 ||
      !OffsetTy->isIntegerTy(16))
    return nullptr;

  auto *VTy = cast<IGCLLVM::FixedVectorType>(Src->getType());
  auto *ETy = VTy->getElementType();
  if (!ETy->isIntegerTy(64) && !ETy->isIntegerTy(32))
    return nullptr;

  IRBuilder<> Builder(RdRegion);
  auto *Cast = dyn_cast<BitCastInst>(Src);
  if (Cast &&
      (Cast->getSrcTy()->isIntegerTy(64) || Cast->getSrcTy()->isIntegerTy(32)))
    return Cast->getOperand(0);

  if (VTy->getNumElements() != 1) {
    auto IID = vc::getAnyIntrinsicID(RdRegion);
    auto *Func = vc::getAnyDeclaration(
        RdRegion->getModule(), IID,
        {VTy, IGCLLVM::FixedVectorType::get(ETy, 1), OffsetTy});
    Src = Builder.CreateCall(
        Func, {Src, VStride, Builder.getInt32(1), Stride, Offset, OrigWidth});
  }

  return Builder.CreateBitCast(Src, ETy);
}

bool GenXLscAddrCalcFolding::foldLscAddrBase(CallInst &Inst) {
  IGC_ASSERT(vc::InternalIntrinsic::isInternalMemoryIntrinsic(&Inst));
  constexpr unsigned BaseIdx = 5, AddrIdx = 6, ScaleIdx = 7, OffsetIndex = 8;

  // Check that base is not folded yet
  auto *OldBase = dyn_cast<ConstantInt>(Inst.getArgOperand(BaseIdx));
  if (!OldBase || OldBase->getZExtValue() != 0)
    return false;

  // Check that scale is not folded yet
  auto *Scale = cast<ConstantInt>(Inst.getArgOperand(ScaleIdx));
  if (Scale->getZExtValue() != 1)
    return false;

  // Check that address operand is an add instruction
  auto *Addr = dyn_cast<BinaryOperator>(Inst.getArgOperand(AddrIdx));
  if (!Addr || Addr->getOpcode() != Instruction::Add)
    return false;

  // Try to find scalar base
  auto *Base = Addr->getOperand(0);
  auto *Index = Addr->getOperand(1);

  if (auto *V = getBaseCandidate(Base)) {
    Base = V;
  } else {
    std::swap(Base, Index);
    Base = getBaseCandidate(Base);
  }

  if (!Base)
    return false;

  auto Offset = cast<ConstantInt>(Inst.getOperand(OffsetIndex))->getValue();
  if (ST->hasLSCOffset()) {
    auto *NewBase = Base;
    auto NewScale = Scale->getValue();
    auto NewOffset = Offset;
    for (; NewBase && NewScale.getZExtValue() == 1;
         NewBase = applyLscAddrFolding(Base, NewScale, NewOffset, &Inst)) {
      Base = NewBase;
      Offset = NewOffset;
      LLVM_DEBUG(dbgs() << "LSC address base folding found, base: " << *Base
                        << ", offset: " << Offset.getSExtValue() << "\n");
    }
  }

  LLVM_DEBUG(dbgs() << "Folding LSC base address for instruction: " << Inst
                    << "\n");
  IRBuilder<> Builder(&Inst);
  Inst.setArgOperand(BaseIdx, Base);
  Inst.setArgOperand(AddrIdx, Index);
  Inst.setArgOperand(OffsetIndex, Builder.getInt32(Offset.getSExtValue()));
  LLVM_DEBUG(dbgs() << "Updated instruction: " << Inst << "\n");

  return true;
}