1 //===-- SystemZTargetTransformInfo.cpp - SystemZ-specific TTI -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a TargetTransformInfo analysis pass specific to the
10 // SystemZ target machine. It uses the target's detailed information to provide
11 // more precise answers to certain TTI queries, while letting the target
12 // independent and default TTI implementations handle the rest.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "SystemZTargetTransformInfo.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/CodeGen/BasicTTIImpl.h"
19 #include "llvm/CodeGen/CostTable.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "systemztti"
26 
27 //===----------------------------------------------------------------------===//
28 //
29 // SystemZ cost model.
30 //
31 //===----------------------------------------------------------------------===//
32 
33 int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
34                                   TTI::TargetCostKind CostKind) {
35   assert(Ty->isIntegerTy());
36 
37   unsigned BitSize = Ty->getPrimitiveSizeInBits();
38   // There is no cost model for constants with a bit size of 0. Return TCC_Free
39   // here, so that constant hoisting will ignore this constant.
40   if (BitSize == 0)
41     return TTI::TCC_Free;
42   // No cost model for operations on integers larger than 64 bit implemented yet.
43   if (BitSize > 64)
44     return TTI::TCC_Free;
45 
46   if (Imm == 0)
47     return TTI::TCC_Free;
48 
49   if (Imm.getBitWidth() <= 64) {
50     // Constants loaded via lgfi.
51     if (isInt<32>(Imm.getSExtValue()))
52       return TTI::TCC_Basic;
53     // Constants loaded via llilf.
54     if (isUInt<32>(Imm.getZExtValue()))
55       return TTI::TCC_Basic;
56     // Constants loaded via llihf:
57     if ((Imm.getZExtValue() & 0xffffffff) == 0)
58       return TTI::TCC_Basic;
59 
60     return 2 * TTI::TCC_Basic;
61   }
62 
63   return 4 * TTI::TCC_Basic;
64 }
65 
66 int SystemZTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
67                                       const APInt &Imm, Type *Ty,
68                                       TTI::TargetCostKind CostKind,
69                                       Instruction *Inst) {
70   assert(Ty->isIntegerTy());
71 
72   unsigned BitSize = Ty->getPrimitiveSizeInBits();
73   // There is no cost model for constants with a bit size of 0. Return TCC_Free
74   // here, so that constant hoisting will ignore this constant.
75   if (BitSize == 0)
76     return TTI::TCC_Free;
77   // No cost model for operations on integers larger than 64 bit implemented yet.
78   if (BitSize > 64)
79     return TTI::TCC_Free;
80 
81   switch (Opcode) {
82   default:
83     return TTI::TCC_Free;
84   case Instruction::GetElementPtr:
85     // Always hoist the base address of a GetElementPtr. This prevents the
86     // creation of new constants for every base constant that gets constant
87     // folded with the offset.
88     if (Idx == 0)
89       return 2 * TTI::TCC_Basic;
90     return TTI::TCC_Free;
91   case Instruction::Store:
92     if (Idx == 0 && Imm.getBitWidth() <= 64) {
93       // Any 8-bit immediate store can by implemented via mvi.
94       if (BitSize == 8)
95         return TTI::TCC_Free;
96       // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi.
97       if (isInt<16>(Imm.getSExtValue()))
98         return TTI::TCC_Free;
99     }
100     break;
101   case Instruction::ICmp:
102     if (Idx == 1 && Imm.getBitWidth() <= 64) {
103       // Comparisons against signed 32-bit immediates implemented via cgfi.
104       if (isInt<32>(Imm.getSExtValue()))
105         return TTI::TCC_Free;
106       // Comparisons against unsigned 32-bit immediates implemented via clgfi.
107       if (isUInt<32>(Imm.getZExtValue()))
108         return TTI::TCC_Free;
109     }
110     break;
111   case Instruction::Add:
112   case Instruction::Sub:
113     if (Idx == 1 && Imm.getBitWidth() <= 64) {
114       // We use algfi/slgfi to add/subtract 32-bit unsigned immediates.
115       if (isUInt<32>(Imm.getZExtValue()))
116         return TTI::TCC_Free;
117       // Or their negation, by swapping addition vs. subtraction.
118       if (isUInt<32>(-Imm.getSExtValue()))
119         return TTI::TCC_Free;
120     }
121     break;
122   case Instruction::Mul:
123     if (Idx == 1 && Imm.getBitWidth() <= 64) {
124       // We use msgfi to multiply by 32-bit signed immediates.
125       if (isInt<32>(Imm.getSExtValue()))
126         return TTI::TCC_Free;
127     }
128     break;
129   case Instruction::Or:
130   case Instruction::Xor:
131     if (Idx == 1 && Imm.getBitWidth() <= 64) {
132       // Masks supported by oilf/xilf.
133       if (isUInt<32>(Imm.getZExtValue()))
134         return TTI::TCC_Free;
135       // Masks supported by oihf/xihf.
136       if ((Imm.getZExtValue() & 0xffffffff) == 0)
137         return TTI::TCC_Free;
138     }
139     break;
140   case Instruction::And:
141     if (Idx == 1 && Imm.getBitWidth() <= 64) {
142       // Any 32-bit AND operation can by implemented via nilf.
143       if (BitSize <= 32)
144         return TTI::TCC_Free;
145       // 64-bit masks supported by nilf.
146       if (isUInt<32>(~Imm.getZExtValue()))
147         return TTI::TCC_Free;
148       // 64-bit masks supported by nilh.
149       if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff)
150         return TTI::TCC_Free;
151       // Some 64-bit AND operations can be implemented via risbg.
152       const SystemZInstrInfo *TII = ST->getInstrInfo();
153       unsigned Start, End;
154       if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End))
155         return TTI::TCC_Free;
156     }
157     break;
158   case Instruction::Shl:
159   case Instruction::LShr:
160   case Instruction::AShr:
161     // Always return TCC_Free for the shift value of a shift instruction.
162     if (Idx == 1)
163       return TTI::TCC_Free;
164     break;
165   case Instruction::UDiv:
166   case Instruction::SDiv:
167   case Instruction::URem:
168   case Instruction::SRem:
169   case Instruction::Trunc:
170   case Instruction::ZExt:
171   case Instruction::SExt:
172   case Instruction::IntToPtr:
173   case Instruction::PtrToInt:
174   case Instruction::BitCast:
175   case Instruction::PHI:
176   case Instruction::Call:
177   case Instruction::Select:
178   case Instruction::Ret:
179   case Instruction::Load:
180     break;
181   }
182 
183   return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
184 }
185 
186 int SystemZTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
187                                         const APInt &Imm, Type *Ty,
188                                         TTI::TargetCostKind CostKind) {
189   assert(Ty->isIntegerTy());
190 
191   unsigned BitSize = Ty->getPrimitiveSizeInBits();
192   // There is no cost model for constants with a bit size of 0. Return TCC_Free
193   // here, so that constant hoisting will ignore this constant.
194   if (BitSize == 0)
195     return TTI::TCC_Free;
196   // No cost model for operations on integers larger than 64 bit implemented yet.
197   if (BitSize > 64)
198     return TTI::TCC_Free;
199 
200   switch (IID) {
201   default:
202     return TTI::TCC_Free;
203   case Intrinsic::sadd_with_overflow:
204   case Intrinsic::uadd_with_overflow:
205   case Intrinsic::ssub_with_overflow:
206   case Intrinsic::usub_with_overflow:
207     // These get expanded to include a normal addition/subtraction.
208     if (Idx == 1 && Imm.getBitWidth() <= 64) {
209       if (isUInt<32>(Imm.getZExtValue()))
210         return TTI::TCC_Free;
211       if (isUInt<32>(-Imm.getSExtValue()))
212         return TTI::TCC_Free;
213     }
214     break;
215   case Intrinsic::smul_with_overflow:
216   case Intrinsic::umul_with_overflow:
217     // These get expanded to include a normal multiplication.
218     if (Idx == 1 && Imm.getBitWidth() <= 64) {
219       if (isInt<32>(Imm.getSExtValue()))
220         return TTI::TCC_Free;
221     }
222     break;
223   case Intrinsic::experimental_stackmap:
224     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
225       return TTI::TCC_Free;
226     break;
227   case Intrinsic::experimental_patchpoint_void:
228   case Intrinsic::experimental_patchpoint_i64:
229     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
230       return TTI::TCC_Free;
231     break;
232   }
233   return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind);
234 }
235 
236 TargetTransformInfo::PopcntSupportKind
237 SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) {
238   assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2");
239   if (ST->hasPopulationCount() && TyWidth <= 64)
240     return TTI::PSK_FastHardware;
241   return TTI::PSK_Software;
242 }
243 
244 void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
245                                              TTI::UnrollingPreferences &UP) {
246   // Find out if L contains a call, what the machine instruction count
247   // estimate is, and how many stores there are.
248   bool HasCall = false;
249   unsigned NumStores = 0;
250   for (auto &BB : L->blocks())
251     for (auto &I : *BB) {
252       if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
253         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
254           if (isLoweredToCall(F))
255             HasCall = true;
256           if (F->getIntrinsicID() == Intrinsic::memcpy ||
257               F->getIntrinsicID() == Intrinsic::memset)
258             NumStores++;
259         } else { // indirect call.
260           HasCall = true;
261         }
262       }
263       if (isa<StoreInst>(&I)) {
264         Type *MemAccessTy = I.getOperand(0)->getType();
265         NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, None, 0,
266                                      TTI::TCK_RecipThroughput);
267       }
268     }
269 
270   // The z13 processor will run out of store tags if too many stores
271   // are fed into it too quickly. Therefore make sure there are not
272   // too many stores in the resulting unrolled loop.
273   unsigned const Max = (NumStores ? (12 / NumStores) : UINT_MAX);
274 
275   if (HasCall) {
276     // Only allow full unrolling if loop has any calls.
277     UP.FullUnrollMaxCount = Max;
278     UP.MaxCount = 1;
279     return;
280   }
281 
282   UP.MaxCount = Max;
283   if (UP.MaxCount <= 1)
284     return;
285 
286   // Allow partial and runtime trip count unrolling.
287   UP.Partial = UP.Runtime = true;
288 
289   UP.PartialThreshold = 75;
290   UP.DefaultUnrollRuntimeCount = 4;
291 
292   // Allow expensive instructions in the pre-header of the loop.
293   UP.AllowExpensiveTripCount = true;
294 
295   UP.Force = true;
296 }
297 
298 void SystemZTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
299                                            TTI::PeelingPreferences &PP) {
300   BaseT::getPeelingPreferences(L, SE, PP);
301 }
302 
303 bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
304                                    TargetTransformInfo::LSRCost &C2) {
305   // SystemZ specific: check instruction count (first), and don't care about
306   // ImmCost, since offsets are checked explicitly.
307   return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
308                   C1.NumIVMuls, C1.NumBaseAdds,
309                   C1.ScaleCost, C1.SetupCost) <
310     std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
311              C2.NumIVMuls, C2.NumBaseAdds,
312              C2.ScaleCost, C2.SetupCost);
313 }
314 
315 unsigned SystemZTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
316   bool Vector = (ClassID == 1);
317   if (!Vector)
318     // Discount the stack pointer.  Also leave out %r0, since it can't
319     // be used in an address.
320     return 14;
321   if (ST->hasVector())
322     return 32;
323   return 0;
324 }
325 
326 unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const {
327   if (!Vector)
328     return 64;
329   if (ST->hasVector())
330     return 128;
331   return 0;
332 }
333 
334 unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses,
335                                               unsigned NumStridedMemAccesses,
336                                               unsigned NumPrefetches,
337                                               bool HasCall) const {
338   // Don't prefetch a loop with many far apart accesses.
339   if (NumPrefetches > 16)
340     return UINT_MAX;
341 
342   // Emit prefetch instructions for smaller strides in cases where we think
343   // the hardware prefetcher might not be able to keep up.
344   if (NumStridedMemAccesses > 32 && !HasCall &&
345       (NumMemAccesses - NumStridedMemAccesses) * 32 <= NumStridedMemAccesses)
346     return 1;
347 
348   return ST->hasMiscellaneousExtensions3() ? 8192 : 2048;
349 }
350 
351 bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
352   EVT VT = TLI->getValueType(DL, DataType);
353   return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
354 }
355 
356 // Return the bit size for the scalar type or vector element
357 // type. getScalarSizeInBits() returns 0 for a pointer type.
358 static unsigned getScalarSizeInBits(Type *Ty) {
359   unsigned Size =
360     (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
361   assert(Size > 0 && "Element must have non-zero size.");
362   return Size;
363 }
364 
365 // getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
366 // type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
367 // 3.
368 static unsigned getNumVectorRegs(Type *Ty) {
369   auto *VTy = cast<FixedVectorType>(Ty);
370   unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements();
371   assert(WideBits > 0 && "Could not compute size of vector");
372   return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
373 }
374 
375 int SystemZTTIImpl::getArithmeticInstrCost(
376     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
377     TTI::OperandValueKind Op1Info,
378     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
379     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
380     const Instruction *CxtI) {
381 
382   // TODO: Handle more cost kinds.
383   if (CostKind != TTI::TCK_RecipThroughput)
384     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
385                                          Op2Info, Opd1PropInfo,
386                                          Opd2PropInfo, Args, CxtI);
387 
388   // TODO: return a good value for BB-VECTORIZER that includes the
389   // immediate loads, which we do not want to count for the loop
390   // vectorizer, since they are hopefully hoisted out of the loop. This
391   // would require a new parameter 'InLoop', but not sure if constant
392   // args are common enough to motivate this.
393 
394   unsigned ScalarBits = Ty->getScalarSizeInBits();
395 
396   // There are thre cases of division and remainder: Dividing with a register
397   // needs a divide instruction. A divisor which is a power of two constant
398   // can be implemented with a sequence of shifts. Any other constant needs a
399   // multiply and shifts.
400   const unsigned DivInstrCost = 20;
401   const unsigned DivMulSeqCost = 10;
402   const unsigned SDivPow2Cost = 4;
403 
404   bool SignedDivRem =
405       Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
406   bool UnsignedDivRem =
407       Opcode == Instruction::UDiv || Opcode == Instruction::URem;
408 
409   // Check for a constant divisor.
410   bool DivRemConst = false;
411   bool DivRemConstPow2 = false;
412   if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
413     if (const Constant *C = dyn_cast<Constant>(Args[1])) {
414       const ConstantInt *CVal =
415           (C->getType()->isVectorTy()
416                ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
417                : dyn_cast<const ConstantInt>(C));
418       if (CVal != nullptr &&
419           (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2()))
420         DivRemConstPow2 = true;
421       else
422         DivRemConst = true;
423     }
424   }
425 
426   if (!Ty->isVectorTy()) {
427     // These FP operations are supported with a dedicated instruction for
428     // float, double and fp128 (base implementation assumes float generally
429     // costs 2).
430     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
431         Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
432       return 1;
433 
434     // There is no native support for FRem.
435     if (Opcode == Instruction::FRem)
436       return LIBCALL_COST;
437 
438     // Give discount for some combined logical operations if supported.
439     if (Args.size() == 2 && ST->hasMiscellaneousExtensions3()) {
440       if (Opcode == Instruction::Xor) {
441         for (const Value *A : Args) {
442           if (const Instruction *I = dyn_cast<Instruction>(A))
443             if (I->hasOneUse() &&
444                 (I->getOpcode() == Instruction::And ||
445                  I->getOpcode() == Instruction::Or ||
446                  I->getOpcode() == Instruction::Xor))
447               return 0;
448         }
449       }
450       else if (Opcode == Instruction::Or || Opcode == Instruction::And) {
451         for (const Value *A : Args) {
452           if (const Instruction *I = dyn_cast<Instruction>(A))
453             if (I->hasOneUse() && I->getOpcode() == Instruction::Xor)
454               return 0;
455         }
456       }
457     }
458 
459     // Or requires one instruction, although it has custom handling for i64.
460     if (Opcode == Instruction::Or)
461       return 1;
462 
463     if (Opcode == Instruction::Xor && ScalarBits == 1) {
464       if (ST->hasLoadStoreOnCond2())
465         return 5; // 2 * (li 0; loc 1); xor
466       return 7; // 2 * ipm sequences ; xor ; shift ; compare
467     }
468 
469     if (DivRemConstPow2)
470       return (SignedDivRem ? SDivPow2Cost : 1);
471     if (DivRemConst)
472       return DivMulSeqCost;
473     if (SignedDivRem || UnsignedDivRem)
474       return DivInstrCost;
475   }
476   else if (ST->hasVector()) {
477     auto *VTy = cast<FixedVectorType>(Ty);
478     unsigned VF = VTy->getNumElements();
479     unsigned NumVectors = getNumVectorRegs(Ty);
480 
481     // These vector operations are custom handled, but are still supported
482     // with one instruction per vector, regardless of element size.
483     if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
484         Opcode == Instruction::AShr) {
485       return NumVectors;
486     }
487 
488     if (DivRemConstPow2)
489       return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1));
490     if (DivRemConst) {
491       SmallVector<Type *> Tys(Args.size(), Ty);
492       return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args, Tys);
493     }
494     if ((SignedDivRem || UnsignedDivRem) && VF > 4)
495       // Temporary hack: disable high vectorization factors with integer
496       // division/remainder, which will get scalarized and handled with
497       // GR128 registers. The mischeduler is not clever enough to avoid
498       // spilling yet.
499       return 1000;
500 
501     // These FP operations are supported with a single vector instruction for
502     // double (base implementation assumes float generally costs 2). For
503     // FP128, the scalar cost is 1, and there is no overhead since the values
504     // are already in scalar registers.
505     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
506         Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
507       switch (ScalarBits) {
508       case 32: {
509         // The vector enhancements facility 1 provides v4f32 instructions.
510         if (ST->hasVectorEnhancements1())
511           return NumVectors;
512         // Return the cost of multiple scalar invocation plus the cost of
513         // inserting and extracting the values.
514         unsigned ScalarCost =
515             getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
516         SmallVector<Type *> Tys(Args.size(), Ty);
517         unsigned Cost =
518             (VF * ScalarCost) + getScalarizationOverhead(VTy, Args, Tys);
519         // FIXME: VF 2 for these FP operations are currently just as
520         // expensive as for VF 4.
521         if (VF == 2)
522           Cost *= 2;
523         return Cost;
524       }
525       case 64:
526       case 128:
527         return NumVectors;
528       default:
529         break;
530       }
531     }
532 
533     // There is no native support for FRem.
534     if (Opcode == Instruction::FRem) {
535       SmallVector<Type *> Tys(Args.size(), Ty);
536       unsigned Cost =
537           (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args, Tys);
538       // FIXME: VF 2 for float is currently just as expensive as for VF 4.
539       if (VF == 2 && ScalarBits == 32)
540         Cost *= 2;
541       return Cost;
542     }
543   }
544 
545   // Fallback to the default implementation.
546   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
547                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
548 }
549 
550 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
551                                    ArrayRef<int> Mask, int Index,
552                                    VectorType *SubTp) {
553   if (ST->hasVector()) {
554     unsigned NumVectors = getNumVectorRegs(Tp);
555 
556     // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
557 
558     // FP128 values are always in scalar registers, so there is no work
559     // involved with a shuffle, except for broadcast. In that case register
560     // moves are done with a single instruction per element.
561     if (Tp->getScalarType()->isFP128Ty())
562       return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
563 
564     switch (Kind) {
565     case  TargetTransformInfo::SK_ExtractSubvector:
566       // ExtractSubvector Index indicates start offset.
567 
568       // Extracting a subvector from first index is a noop.
569       return (Index == 0 ? 0 : NumVectors);
570 
571     case TargetTransformInfo::SK_Broadcast:
572       // Loop vectorizer calls here to figure out the extra cost of
573       // broadcasting a loaded value to all elements of a vector. Since vlrep
574       // loads and replicates with a single instruction, adjust the returned
575       // value.
576       return NumVectors - 1;
577 
578     default:
579 
580       // SystemZ supports single instruction permutation / replication.
581       return NumVectors;
582     }
583   }
584 
585   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
586 }
587 
588 // Return the log2 difference of the element sizes of the two vector types.
589 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
590   unsigned Bits0 = Ty0->getScalarSizeInBits();
591   unsigned Bits1 = Ty1->getScalarSizeInBits();
592 
593   if (Bits1 >  Bits0)
594     return (Log2_32(Bits1) - Log2_32(Bits0));
595 
596   return (Log2_32(Bits0) - Log2_32(Bits1));
597 }
598 
599 // Return the number of instructions needed to truncate SrcTy to DstTy.
600 unsigned SystemZTTIImpl::
601 getVectorTruncCost(Type *SrcTy, Type *DstTy) {
602   assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
603   assert(SrcTy->getPrimitiveSizeInBits().getFixedSize() >
604              DstTy->getPrimitiveSizeInBits().getFixedSize() &&
605          "Packing must reduce size of vector type.");
606   assert(cast<FixedVectorType>(SrcTy)->getNumElements() ==
607              cast<FixedVectorType>(DstTy)->getNumElements() &&
608          "Packing should not change number of elements.");
609 
610   // TODO: Since fp32 is expanded, the extract cost should always be 0.
611 
612   unsigned NumParts = getNumVectorRegs(SrcTy);
613   if (NumParts <= 2)
614     // Up to 2 vector registers can be truncated efficiently with pack or
615     // permute. The latter requires an immediate mask to be loaded, which
616     // typically gets hoisted out of a loop.  TODO: return a good value for
617     // BB-VECTORIZER that includes the immediate loads, which we do not want
618     // to count for the loop vectorizer.
619     return 1;
620 
621   unsigned Cost = 0;
622   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
623   unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements();
624   for (unsigned P = 0; P < Log2Diff; ++P) {
625     if (NumParts > 1)
626       NumParts /= 2;
627     Cost += NumParts;
628   }
629 
630   // Currently, a general mix of permutes and pack instructions is output by
631   // isel, which follow the cost computation above except for this case which
632   // is one instruction less:
633   if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
634       DstTy->getScalarSizeInBits() == 8)
635     Cost--;
636 
637   return Cost;
638 }
639 
640 // Return the cost of converting a vector bitmask produced by a compare
641 // (SrcTy), to the type of the select or extend instruction (DstTy).
642 unsigned SystemZTTIImpl::
643 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
644   assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
645           "Should only be called with vector types.");
646 
647   unsigned PackCost = 0;
648   unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
649   unsigned DstScalarBits = DstTy->getScalarSizeInBits();
650   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
651   if (SrcScalarBits > DstScalarBits)
652     // The bitmask will be truncated.
653     PackCost = getVectorTruncCost(SrcTy, DstTy);
654   else if (SrcScalarBits < DstScalarBits) {
655     unsigned DstNumParts = getNumVectorRegs(DstTy);
656     // Each vector select needs its part of the bitmask unpacked.
657     PackCost = Log2Diff * DstNumParts;
658     // Extra cost for moving part of mask before unpacking.
659     PackCost += DstNumParts - 1;
660   }
661 
662   return PackCost;
663 }
664 
665 // Return the type of the compared operands. This is needed to compute the
666 // cost for a Select / ZExt or SExt instruction.
667 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
668   Type *OpTy = nullptr;
669   if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
670     OpTy = CI->getOperand(0)->getType();
671   else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
672     if (LogicI->getNumOperands() == 2)
673       if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
674         if (isa<CmpInst>(LogicI->getOperand(1)))
675           OpTy = CI0->getOperand(0)->getType();
676 
677   if (OpTy != nullptr) {
678     if (VF == 1) {
679       assert (!OpTy->isVectorTy() && "Expected scalar type");
680       return OpTy;
681     }
682     // Return the potentially vectorized type based on 'I' and 'VF'.  'I' may
683     // be either scalar or already vectorized with a same or lesser VF.
684     Type *ElTy = OpTy->getScalarType();
685     return FixedVectorType::get(ElTy, VF);
686   }
687 
688   return nullptr;
689 }
690 
691 // Get the cost of converting a boolean vector to a vector with same width
692 // and element size as Dst, plus the cost of zero extending if needed.
693 unsigned SystemZTTIImpl::
694 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst,
695                               const Instruction *I) {
696   auto *DstVTy = cast<FixedVectorType>(Dst);
697   unsigned VF = DstVTy->getNumElements();
698   unsigned Cost = 0;
699   // If we know what the widths of the compared operands, get any cost of
700   // converting it to match Dst. Otherwise assume same widths.
701   Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
702   if (CmpOpTy != nullptr)
703     Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
704   if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
705     // One 'vn' per dst vector with an immediate mask.
706     Cost += getNumVectorRegs(Dst);
707   return Cost;
708 }
709 
710 int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
711                                      TTI::CastContextHint CCH,
712                                      TTI::TargetCostKind CostKind,
713                                      const Instruction *I) {
714   // FIXME: Can the logic below also be used for these cost kinds?
715   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) {
716     int BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
717     return BaseCost == 0 ? BaseCost : 1;
718   }
719 
720   unsigned DstScalarBits = Dst->getScalarSizeInBits();
721   unsigned SrcScalarBits = Src->getScalarSizeInBits();
722 
723   if (!Src->isVectorTy()) {
724     assert (!Dst->isVectorTy());
725 
726     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
727       if (SrcScalarBits >= 32 ||
728           (I != nullptr && isa<LoadInst>(I->getOperand(0))))
729         return 1;
730       return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
731     }
732 
733     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
734         Src->isIntegerTy(1)) {
735       if (ST->hasLoadStoreOnCond2())
736         return 2; // li 0; loc 1
737 
738       // This should be extension of a compare i1 result, which is done with
739       // ipm and a varying sequence of instructions.
740       unsigned Cost = 0;
741       if (Opcode == Instruction::SExt)
742         Cost = (DstScalarBits < 64 ? 3 : 4);
743       if (Opcode == Instruction::ZExt)
744         Cost = 3;
745       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
746       if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
747         // If operands of an fp-type was compared, this costs +1.
748         Cost++;
749       return Cost;
750     }
751   }
752   else if (ST->hasVector()) {
753     auto *SrcVecTy = cast<FixedVectorType>(Src);
754     auto *DstVecTy = cast<FixedVectorType>(Dst);
755     unsigned VF = SrcVecTy->getNumElements();
756     unsigned NumDstVectors = getNumVectorRegs(Dst);
757     unsigned NumSrcVectors = getNumVectorRegs(Src);
758 
759     if (Opcode == Instruction::Trunc) {
760       if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
761         return 0; // Check for NOOP conversions.
762       return getVectorTruncCost(Src, Dst);
763     }
764 
765     if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
766       if (SrcScalarBits >= 8) {
767         // ZExt/SExt will be handled with one unpack per doubling of width.
768         unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
769 
770         // For types that spans multiple vector registers, some additional
771         // instructions are used to setup the unpacking.
772         unsigned NumSrcVectorOps =
773           (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
774                           : (NumDstVectors / 2));
775 
776         return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
777       }
778       else if (SrcScalarBits == 1)
779         return getBoolVecToIntConversionCost(Opcode, Dst, I);
780     }
781 
782     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
783         Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
784       // TODO: Fix base implementation which could simplify things a bit here
785       // (seems to miss on differentiating on scalar/vector types).
786 
787       // Only 64 bit vector conversions are natively supported before z15.
788       if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) {
789         if (SrcScalarBits == DstScalarBits)
790           return NumDstVectors;
791 
792         if (SrcScalarBits == 1)
793           return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
794       }
795 
796       // Return the cost of multiple scalar invocation plus the cost of
797       // inserting and extracting the values. Base implementation does not
798       // realize float->int gets scalarized.
799       unsigned ScalarCost = getCastInstrCost(
800           Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
801       unsigned TotCost = VF * ScalarCost;
802       bool NeedsInserts = true, NeedsExtracts = true;
803       // FP128 registers do not get inserted or extracted.
804       if (DstScalarBits == 128 &&
805           (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
806         NeedsInserts = false;
807       if (SrcScalarBits == 128 &&
808           (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
809         NeedsExtracts = false;
810 
811       TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts);
812       TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false);
813 
814       // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
815       if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
816         TotCost *= 2;
817 
818       return TotCost;
819     }
820 
821     if (Opcode == Instruction::FPTrunc) {
822       if (SrcScalarBits == 128)  // fp128 -> double/float + inserts of elements.
823         return VF /*ldxbr/lexbr*/ +
824                getScalarizationOverhead(DstVecTy, true, false);
825       else // double -> float
826         return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
827     }
828 
829     if (Opcode == Instruction::FPExt) {
830       if (SrcScalarBits == 32 && DstScalarBits == 64) {
831         // float -> double is very rare and currently unoptimized. Instead of
832         // using vldeb, which can do two at a time, all conversions are
833         // scalarized.
834         return VF * 2;
835       }
836       // -> fp128.  VF * lxdb/lxeb + extraction of elements.
837       return VF + getScalarizationOverhead(SrcVecTy, false, true);
838     }
839   }
840 
841   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
842 }
843 
844 // Scalar i8 / i16 operations will typically be made after first extending
845 // the operands to i32.
846 static unsigned getOperandsExtensionCost(const Instruction *I) {
847   unsigned ExtCost = 0;
848   for (Value *Op : I->operands())
849     // A load of i8 or i16 sign/zero extends to i32.
850     if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op))
851       ExtCost++;
852 
853   return ExtCost;
854 }
855 
856 int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
857                                        Type *CondTy, CmpInst::Predicate VecPred,
858                                        TTI::TargetCostKind CostKind,
859                                        const Instruction *I) {
860   if (CostKind != TTI::TCK_RecipThroughput)
861     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
862 
863   if (!ValTy->isVectorTy()) {
864     switch (Opcode) {
865     case Instruction::ICmp: {
866       // A loaded value compared with 0 with multiple users becomes Load and
867       // Test. The load is then not foldable, so return 0 cost for the ICmp.
868       unsigned ScalarBits = ValTy->getScalarSizeInBits();
869       if (I != nullptr && ScalarBits >= 32)
870         if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
871           if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
872             if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
873                 C->isZero())
874               return 0;
875 
876       unsigned Cost = 1;
877       if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
878         Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
879       return Cost;
880     }
881     case Instruction::Select:
882       if (ValTy->isFloatingPointTy())
883         return 4; // No load on condition for FP - costs a conditional jump.
884       return 1; // Load On Condition / Select Register.
885     }
886   }
887   else if (ST->hasVector()) {
888     unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements();
889 
890     // Called with a compare instruction.
891     if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
892       unsigned PredicateExtraCost = 0;
893       if (I != nullptr) {
894         // Some predicates cost one or two extra instructions.
895         switch (cast<CmpInst>(I)->getPredicate()) {
896         case CmpInst::Predicate::ICMP_NE:
897         case CmpInst::Predicate::ICMP_UGE:
898         case CmpInst::Predicate::ICMP_ULE:
899         case CmpInst::Predicate::ICMP_SGE:
900         case CmpInst::Predicate::ICMP_SLE:
901           PredicateExtraCost = 1;
902           break;
903         case CmpInst::Predicate::FCMP_ONE:
904         case CmpInst::Predicate::FCMP_ORD:
905         case CmpInst::Predicate::FCMP_UEQ:
906         case CmpInst::Predicate::FCMP_UNO:
907           PredicateExtraCost = 2;
908           break;
909         default:
910           break;
911         }
912       }
913 
914       // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
915       // floats.  FIXME: <2 x float> generates same code as <4 x float>.
916       unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
917       unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
918 
919       unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
920       return Cost;
921     }
922     else { // Called with a select instruction.
923       assert (Opcode == Instruction::Select);
924 
925       // We can figure out the extra cost of packing / unpacking if the
926       // instruction was passed and the compare instruction is found.
927       unsigned PackCost = 0;
928       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
929       if (CmpOpTy != nullptr)
930         PackCost =
931           getVectorBitmaskConversionCost(CmpOpTy, ValTy);
932 
933       return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
934     }
935   }
936 
937   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
938 }
939 
940 int SystemZTTIImpl::
941 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
942   // vlvgp will insert two grs into a vector register, so only count half the
943   // number of instructions.
944   if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
945     return ((Index % 2 == 0) ? 1 : 0);
946 
947   if (Opcode == Instruction::ExtractElement) {
948     int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
949 
950     // Give a slight penalty for moving out of vector pipeline to FXU unit.
951     if (Index == 0 && Val->isIntOrIntVectorTy())
952       Cost += 1;
953 
954     return Cost;
955   }
956 
957   return BaseT::getVectorInstrCost(Opcode, Val, Index);
958 }
959 
960 // Check if a load may be folded as a memory operand in its user.
961 bool SystemZTTIImpl::
962 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) {
963   if (!Ld->hasOneUse())
964     return false;
965   FoldedValue = Ld;
966   const Instruction *UserI = cast<Instruction>(*Ld->user_begin());
967   unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
968   unsigned TruncBits = 0;
969   unsigned SExtBits = 0;
970   unsigned ZExtBits = 0;
971   if (UserI->hasOneUse()) {
972     unsigned UserBits = UserI->getType()->getScalarSizeInBits();
973     if (isa<TruncInst>(UserI))
974       TruncBits = UserBits;
975     else if (isa<SExtInst>(UserI))
976       SExtBits = UserBits;
977     else if (isa<ZExtInst>(UserI))
978       ZExtBits = UserBits;
979   }
980   if (TruncBits || SExtBits || ZExtBits) {
981     FoldedValue = UserI;
982     UserI = cast<Instruction>(*UserI->user_begin());
983     // Load (single use) -> trunc/extend (single use) -> UserI
984   }
985   if ((UserI->getOpcode() == Instruction::Sub ||
986        UserI->getOpcode() == Instruction::SDiv ||
987        UserI->getOpcode() == Instruction::UDiv) &&
988       UserI->getOperand(1) != FoldedValue)
989     return false; // Not commutative, only RHS foldable.
990   // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
991   // extension was made of the load.
992   unsigned LoadOrTruncBits =
993       ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
994   switch (UserI->getOpcode()) {
995   case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
996   case Instruction::Sub:
997   case Instruction::ICmp:
998     if (LoadedBits == 32 && ZExtBits == 64)
999       return true;
1000     LLVM_FALLTHROUGH;
1001   case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
1002     if (UserI->getOpcode() != Instruction::ICmp) {
1003       if (LoadedBits == 16 &&
1004           (SExtBits == 32 ||
1005            (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
1006         return true;
1007       if (LoadOrTruncBits == 16)
1008         return true;
1009     }
1010     LLVM_FALLTHROUGH;
1011   case Instruction::SDiv:// SE: 32->64
1012     if (LoadedBits == 32 && SExtBits == 64)
1013       return true;
1014     LLVM_FALLTHROUGH;
1015   case Instruction::UDiv:
1016   case Instruction::And:
1017   case Instruction::Or:
1018   case Instruction::Xor:
1019     // This also makes sense for float operations, but disabled for now due
1020     // to regressions.
1021     // case Instruction::FCmp:
1022     // case Instruction::FAdd:
1023     // case Instruction::FSub:
1024     // case Instruction::FMul:
1025     // case Instruction::FDiv:
1026 
1027     // All possible extensions of memory checked above.
1028 
1029     // Comparison between memory and immediate.
1030     if (UserI->getOpcode() == Instruction::ICmp)
1031       if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
1032         if (CI->getValue().isIntN(16))
1033           return true;
1034     return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
1035     break;
1036   }
1037   return false;
1038 }
1039 
1040 static bool isBswapIntrinsicCall(const Value *V) {
1041   if (const Instruction *I = dyn_cast<Instruction>(V))
1042     if (auto *CI = dyn_cast<CallInst>(I))
1043       if (auto *F = CI->getCalledFunction())
1044         if (F->getIntrinsicID() == Intrinsic::bswap)
1045           return true;
1046   return false;
1047 }
1048 
1049 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1050                                     MaybeAlign Alignment, unsigned AddressSpace,
1051                                     TTI::TargetCostKind CostKind,
1052                                     const Instruction *I) {
1053   assert(!Src->isVoidTy() && "Invalid type");
1054 
1055   // TODO: Handle other cost kinds.
1056   if (CostKind != TTI::TCK_RecipThroughput)
1057     return 1;
1058 
1059   if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
1060     // Store the load or its truncated or extended value in FoldedValue.
1061     const Instruction *FoldedValue = nullptr;
1062     if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
1063       const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin());
1064       assert (UserI->getNumOperands() == 2 && "Expected a binop.");
1065 
1066       // UserI can't fold two loads, so in that case return 0 cost only
1067       // half of the time.
1068       for (unsigned i = 0; i < 2; ++i) {
1069         if (UserI->getOperand(i) == FoldedValue)
1070           continue;
1071 
1072         if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
1073           LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
1074           if (!OtherLoad &&
1075               (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
1076                isa<ZExtInst>(OtherOp)))
1077             OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
1078           if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1079             return i == 0; // Both operands foldable.
1080         }
1081       }
1082 
1083       return 0; // Only I is foldable in user.
1084     }
1085   }
1086 
1087   unsigned NumOps =
1088     (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
1089 
1090   // Store/Load reversed saves one instruction.
1091   if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) &&
1092       I != nullptr) {
1093     if (Opcode == Instruction::Load && I->hasOneUse()) {
1094       const Instruction *LdUser = cast<Instruction>(*I->user_begin());
1095       // In case of load -> bswap -> store, return normal cost for the load.
1096       if (isBswapIntrinsicCall(LdUser) &&
1097           (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1098         return 0;
1099     }
1100     else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1101       const Value *StoredVal = SI->getValueOperand();
1102       if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1103         return 0;
1104     }
1105   }
1106 
1107   if (Src->getScalarSizeInBits() == 128)
1108     // 128 bit scalars are held in a pair of two 64 bit registers.
1109     NumOps *= 2;
1110 
1111   return  NumOps;
1112 }
1113 
1114 // The generic implementation of getInterleavedMemoryOpCost() is based on
1115 // adding costs of the memory operations plus all the extracts and inserts
1116 // needed for using / defining the vector operands. The SystemZ version does
1117 // roughly the same but bases the computations on vector permutations
1118 // instead.
1119 int SystemZTTIImpl::getInterleavedMemoryOpCost(
1120     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1121     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1122     bool UseMaskForCond, bool UseMaskForGaps) {
1123   if (UseMaskForCond || UseMaskForGaps)
1124     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1125                                              Alignment, AddressSpace, CostKind,
1126                                              UseMaskForCond, UseMaskForGaps);
1127   assert(isa<VectorType>(VecTy) &&
1128          "Expect a vector type for interleaved memory op");
1129 
1130   // Return the ceiling of dividing A by B.
1131   auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
1132 
1133   unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1134   assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1135   unsigned VF = NumElts / Factor;
1136   unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1137   unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1138   unsigned NumPermutes = 0;
1139 
1140   if (Opcode == Instruction::Load) {
1141     // Loading interleave groups may have gaps, which may mean fewer
1142     // loads. Find out how many vectors will be loaded in total, and in how
1143     // many of them each value will be in.
1144     BitVector UsedInsts(NumVectorMemOps, false);
1145     std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1146     for (unsigned Index : Indices)
1147       for (unsigned Elt = 0; Elt < VF; ++Elt) {
1148         unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1149         UsedInsts.set(Vec);
1150         ValueVecs[Index].set(Vec);
1151       }
1152     NumVectorMemOps = UsedInsts.count();
1153 
1154     for (unsigned Index : Indices) {
1155       // Estimate that each loaded source vector containing this Index
1156       // requires one operation, except that vperm can handle two input
1157       // registers first time for each dst vector.
1158       unsigned NumSrcVecs = ValueVecs[Index].count();
1159       unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U);
1160       assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1161       NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1162     }
1163   } else {
1164     // Estimate the permutes for each stored vector as the smaller of the
1165     // number of elements and the number of source vectors. Subtract one per
1166     // dst vector for vperm (S.A.).
1167     unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1168     unsigned NumDstVecs = NumVectorMemOps;
1169     assert (NumSrcVecs > 1 && "Expected at least two source vectors.");
1170     NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1171   }
1172 
1173   // Cost of load/store operations and the permutations needed.
1174   return NumVectorMemOps + NumPermutes;
1175 }
1176 
1177 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) {
1178   if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1179     return getNumVectorRegs(RetTy); // VPERM
1180   return -1;
1181 }
1182 
1183 int SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1184                                           TTI::TargetCostKind CostKind) {
1185   int Cost = getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType());
1186   if (Cost != -1)
1187     return Cost;
1188   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1189 }
1190