xref: /freebsd/contrib/llvm-project/llvm/lib/Target/SystemZ/SystemZTargetTransformInfo.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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       return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args);
492     if ((SignedDivRem || UnsignedDivRem) && VF > 4)
493       // Temporary hack: disable high vectorization factors with integer
494       // division/remainder, which will get scalarized and handled with
495       // GR128 registers. The mischeduler is not clever enough to avoid
496       // spilling yet.
497       return 1000;
498 
499     // These FP operations are supported with a single vector instruction for
500     // double (base implementation assumes float generally costs 2). For
501     // FP128, the scalar cost is 1, and there is no overhead since the values
502     // are already in scalar registers.
503     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
504         Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
505       switch (ScalarBits) {
506       case 32: {
507         // The vector enhancements facility 1 provides v4f32 instructions.
508         if (ST->hasVectorEnhancements1())
509           return NumVectors;
510         // Return the cost of multiple scalar invocation plus the cost of
511         // inserting and extracting the values.
512         unsigned ScalarCost =
513             getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
514         unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(VTy, Args);
515         // FIXME: VF 2 for these FP operations are currently just as
516         // expensive as for VF 4.
517         if (VF == 2)
518           Cost *= 2;
519         return Cost;
520       }
521       case 64:
522       case 128:
523         return NumVectors;
524       default:
525         break;
526       }
527     }
528 
529     // There is no native support for FRem.
530     if (Opcode == Instruction::FRem) {
531       unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args);
532       // FIXME: VF 2 for float is currently just as expensive as for VF 4.
533       if (VF == 2 && ScalarBits == 32)
534         Cost *= 2;
535       return Cost;
536     }
537   }
538 
539   // Fallback to the default implementation.
540   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
541                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
542 }
543 
544 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
545                                    int Index, VectorType *SubTp) {
546   if (ST->hasVector()) {
547     unsigned NumVectors = getNumVectorRegs(Tp);
548 
549     // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
550 
551     // FP128 values are always in scalar registers, so there is no work
552     // involved with a shuffle, except for broadcast. In that case register
553     // moves are done with a single instruction per element.
554     if (Tp->getScalarType()->isFP128Ty())
555       return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
556 
557     switch (Kind) {
558     case  TargetTransformInfo::SK_ExtractSubvector:
559       // ExtractSubvector Index indicates start offset.
560 
561       // Extracting a subvector from first index is a noop.
562       return (Index == 0 ? 0 : NumVectors);
563 
564     case TargetTransformInfo::SK_Broadcast:
565       // Loop vectorizer calls here to figure out the extra cost of
566       // broadcasting a loaded value to all elements of a vector. Since vlrep
567       // loads and replicates with a single instruction, adjust the returned
568       // value.
569       return NumVectors - 1;
570 
571     default:
572 
573       // SystemZ supports single instruction permutation / replication.
574       return NumVectors;
575     }
576   }
577 
578   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
579 }
580 
581 // Return the log2 difference of the element sizes of the two vector types.
582 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
583   unsigned Bits0 = Ty0->getScalarSizeInBits();
584   unsigned Bits1 = Ty1->getScalarSizeInBits();
585 
586   if (Bits1 >  Bits0)
587     return (Log2_32(Bits1) - Log2_32(Bits0));
588 
589   return (Log2_32(Bits0) - Log2_32(Bits1));
590 }
591 
592 // Return the number of instructions needed to truncate SrcTy to DstTy.
593 unsigned SystemZTTIImpl::
594 getVectorTruncCost(Type *SrcTy, Type *DstTy) {
595   assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
596   assert(SrcTy->getPrimitiveSizeInBits().getFixedSize() >
597              DstTy->getPrimitiveSizeInBits().getFixedSize() &&
598          "Packing must reduce size of vector type.");
599   assert(cast<FixedVectorType>(SrcTy)->getNumElements() ==
600              cast<FixedVectorType>(DstTy)->getNumElements() &&
601          "Packing should not change number of elements.");
602 
603   // TODO: Since fp32 is expanded, the extract cost should always be 0.
604 
605   unsigned NumParts = getNumVectorRegs(SrcTy);
606   if (NumParts <= 2)
607     // Up to 2 vector registers can be truncated efficiently with pack or
608     // permute. The latter requires an immediate mask to be loaded, which
609     // typically gets hoisted out of a loop.  TODO: return a good value for
610     // BB-VECTORIZER that includes the immediate loads, which we do not want
611     // to count for the loop vectorizer.
612     return 1;
613 
614   unsigned Cost = 0;
615   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
616   unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements();
617   for (unsigned P = 0; P < Log2Diff; ++P) {
618     if (NumParts > 1)
619       NumParts /= 2;
620     Cost += NumParts;
621   }
622 
623   // Currently, a general mix of permutes and pack instructions is output by
624   // isel, which follow the cost computation above except for this case which
625   // is one instruction less:
626   if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
627       DstTy->getScalarSizeInBits() == 8)
628     Cost--;
629 
630   return Cost;
631 }
632 
633 // Return the cost of converting a vector bitmask produced by a compare
634 // (SrcTy), to the type of the select or extend instruction (DstTy).
635 unsigned SystemZTTIImpl::
636 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
637   assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
638           "Should only be called with vector types.");
639 
640   unsigned PackCost = 0;
641   unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
642   unsigned DstScalarBits = DstTy->getScalarSizeInBits();
643   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
644   if (SrcScalarBits > DstScalarBits)
645     // The bitmask will be truncated.
646     PackCost = getVectorTruncCost(SrcTy, DstTy);
647   else if (SrcScalarBits < DstScalarBits) {
648     unsigned DstNumParts = getNumVectorRegs(DstTy);
649     // Each vector select needs its part of the bitmask unpacked.
650     PackCost = Log2Diff * DstNumParts;
651     // Extra cost for moving part of mask before unpacking.
652     PackCost += DstNumParts - 1;
653   }
654 
655   return PackCost;
656 }
657 
658 // Return the type of the compared operands. This is needed to compute the
659 // cost for a Select / ZExt or SExt instruction.
660 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
661   Type *OpTy = nullptr;
662   if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
663     OpTy = CI->getOperand(0)->getType();
664   else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
665     if (LogicI->getNumOperands() == 2)
666       if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
667         if (isa<CmpInst>(LogicI->getOperand(1)))
668           OpTy = CI0->getOperand(0)->getType();
669 
670   if (OpTy != nullptr) {
671     if (VF == 1) {
672       assert (!OpTy->isVectorTy() && "Expected scalar type");
673       return OpTy;
674     }
675     // Return the potentially vectorized type based on 'I' and 'VF'.  'I' may
676     // be either scalar or already vectorized with a same or lesser VF.
677     Type *ElTy = OpTy->getScalarType();
678     return FixedVectorType::get(ElTy, VF);
679   }
680 
681   return nullptr;
682 }
683 
684 // Get the cost of converting a boolean vector to a vector with same width
685 // and element size as Dst, plus the cost of zero extending if needed.
686 unsigned SystemZTTIImpl::
687 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst,
688                               const Instruction *I) {
689   auto *DstVTy = cast<FixedVectorType>(Dst);
690   unsigned VF = DstVTy->getNumElements();
691   unsigned Cost = 0;
692   // If we know what the widths of the compared operands, get any cost of
693   // converting it to match Dst. Otherwise assume same widths.
694   Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
695   if (CmpOpTy != nullptr)
696     Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
697   if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
698     // One 'vn' per dst vector with an immediate mask.
699     Cost += getNumVectorRegs(Dst);
700   return Cost;
701 }
702 
703 int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
704                                      TTI::CastContextHint CCH,
705                                      TTI::TargetCostKind CostKind,
706                                      const Instruction *I) {
707   // FIXME: Can the logic below also be used for these cost kinds?
708   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) {
709     int BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
710     return BaseCost == 0 ? BaseCost : 1;
711   }
712 
713   unsigned DstScalarBits = Dst->getScalarSizeInBits();
714   unsigned SrcScalarBits = Src->getScalarSizeInBits();
715 
716   if (!Src->isVectorTy()) {
717     assert (!Dst->isVectorTy());
718 
719     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
720       if (SrcScalarBits >= 32 ||
721           (I != nullptr && isa<LoadInst>(I->getOperand(0))))
722         return 1;
723       return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
724     }
725 
726     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
727         Src->isIntegerTy(1)) {
728       if (ST->hasLoadStoreOnCond2())
729         return 2; // li 0; loc 1
730 
731       // This should be extension of a compare i1 result, which is done with
732       // ipm and a varying sequence of instructions.
733       unsigned Cost = 0;
734       if (Opcode == Instruction::SExt)
735         Cost = (DstScalarBits < 64 ? 3 : 4);
736       if (Opcode == Instruction::ZExt)
737         Cost = 3;
738       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
739       if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
740         // If operands of an fp-type was compared, this costs +1.
741         Cost++;
742       return Cost;
743     }
744   }
745   else if (ST->hasVector()) {
746     auto *SrcVecTy = cast<FixedVectorType>(Src);
747     auto *DstVecTy = cast<FixedVectorType>(Dst);
748     unsigned VF = SrcVecTy->getNumElements();
749     unsigned NumDstVectors = getNumVectorRegs(Dst);
750     unsigned NumSrcVectors = getNumVectorRegs(Src);
751 
752     if (Opcode == Instruction::Trunc) {
753       if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
754         return 0; // Check for NOOP conversions.
755       return getVectorTruncCost(Src, Dst);
756     }
757 
758     if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
759       if (SrcScalarBits >= 8) {
760         // ZExt/SExt will be handled with one unpack per doubling of width.
761         unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
762 
763         // For types that spans multiple vector registers, some additional
764         // instructions are used to setup the unpacking.
765         unsigned NumSrcVectorOps =
766           (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
767                           : (NumDstVectors / 2));
768 
769         return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
770       }
771       else if (SrcScalarBits == 1)
772         return getBoolVecToIntConversionCost(Opcode, Dst, I);
773     }
774 
775     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
776         Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
777       // TODO: Fix base implementation which could simplify things a bit here
778       // (seems to miss on differentiating on scalar/vector types).
779 
780       // Only 64 bit vector conversions are natively supported before z15.
781       if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) {
782         if (SrcScalarBits == DstScalarBits)
783           return NumDstVectors;
784 
785         if (SrcScalarBits == 1)
786           return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
787       }
788 
789       // Return the cost of multiple scalar invocation plus the cost of
790       // inserting and extracting the values. Base implementation does not
791       // realize float->int gets scalarized.
792       unsigned ScalarCost = getCastInstrCost(
793           Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
794       unsigned TotCost = VF * ScalarCost;
795       bool NeedsInserts = true, NeedsExtracts = true;
796       // FP128 registers do not get inserted or extracted.
797       if (DstScalarBits == 128 &&
798           (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
799         NeedsInserts = false;
800       if (SrcScalarBits == 128 &&
801           (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
802         NeedsExtracts = false;
803 
804       TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts);
805       TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false);
806 
807       // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
808       if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
809         TotCost *= 2;
810 
811       return TotCost;
812     }
813 
814     if (Opcode == Instruction::FPTrunc) {
815       if (SrcScalarBits == 128)  // fp128 -> double/float + inserts of elements.
816         return VF /*ldxbr/lexbr*/ +
817                getScalarizationOverhead(DstVecTy, true, false);
818       else // double -> float
819         return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
820     }
821 
822     if (Opcode == Instruction::FPExt) {
823       if (SrcScalarBits == 32 && DstScalarBits == 64) {
824         // float -> double is very rare and currently unoptimized. Instead of
825         // using vldeb, which can do two at a time, all conversions are
826         // scalarized.
827         return VF * 2;
828       }
829       // -> fp128.  VF * lxdb/lxeb + extraction of elements.
830       return VF + getScalarizationOverhead(SrcVecTy, false, true);
831     }
832   }
833 
834   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
835 }
836 
837 // Scalar i8 / i16 operations will typically be made after first extending
838 // the operands to i32.
839 static unsigned getOperandsExtensionCost(const Instruction *I) {
840   unsigned ExtCost = 0;
841   for (Value *Op : I->operands())
842     // A load of i8 or i16 sign/zero extends to i32.
843     if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op))
844       ExtCost++;
845 
846   return ExtCost;
847 }
848 
849 int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
850                                        Type *CondTy, CmpInst::Predicate VecPred,
851                                        TTI::TargetCostKind CostKind,
852                                        const Instruction *I) {
853   if (CostKind != TTI::TCK_RecipThroughput)
854     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
855 
856   if (!ValTy->isVectorTy()) {
857     switch (Opcode) {
858     case Instruction::ICmp: {
859       // A loaded value compared with 0 with multiple users becomes Load and
860       // Test. The load is then not foldable, so return 0 cost for the ICmp.
861       unsigned ScalarBits = ValTy->getScalarSizeInBits();
862       if (I != nullptr && ScalarBits >= 32)
863         if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
864           if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
865             if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
866                 C->isZero())
867               return 0;
868 
869       unsigned Cost = 1;
870       if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
871         Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
872       return Cost;
873     }
874     case Instruction::Select:
875       if (ValTy->isFloatingPointTy())
876         return 4; // No load on condition for FP - costs a conditional jump.
877       return 1; // Load On Condition / Select Register.
878     }
879   }
880   else if (ST->hasVector()) {
881     unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements();
882 
883     // Called with a compare instruction.
884     if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
885       unsigned PredicateExtraCost = 0;
886       if (I != nullptr) {
887         // Some predicates cost one or two extra instructions.
888         switch (cast<CmpInst>(I)->getPredicate()) {
889         case CmpInst::Predicate::ICMP_NE:
890         case CmpInst::Predicate::ICMP_UGE:
891         case CmpInst::Predicate::ICMP_ULE:
892         case CmpInst::Predicate::ICMP_SGE:
893         case CmpInst::Predicate::ICMP_SLE:
894           PredicateExtraCost = 1;
895           break;
896         case CmpInst::Predicate::FCMP_ONE:
897         case CmpInst::Predicate::FCMP_ORD:
898         case CmpInst::Predicate::FCMP_UEQ:
899         case CmpInst::Predicate::FCMP_UNO:
900           PredicateExtraCost = 2;
901           break;
902         default:
903           break;
904         }
905       }
906 
907       // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
908       // floats.  FIXME: <2 x float> generates same code as <4 x float>.
909       unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
910       unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
911 
912       unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
913       return Cost;
914     }
915     else { // Called with a select instruction.
916       assert (Opcode == Instruction::Select);
917 
918       // We can figure out the extra cost of packing / unpacking if the
919       // instruction was passed and the compare instruction is found.
920       unsigned PackCost = 0;
921       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
922       if (CmpOpTy != nullptr)
923         PackCost =
924           getVectorBitmaskConversionCost(CmpOpTy, ValTy);
925 
926       return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
927     }
928   }
929 
930   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind);
931 }
932 
933 int SystemZTTIImpl::
934 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
935   // vlvgp will insert two grs into a vector register, so only count half the
936   // number of instructions.
937   if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
938     return ((Index % 2 == 0) ? 1 : 0);
939 
940   if (Opcode == Instruction::ExtractElement) {
941     int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
942 
943     // Give a slight penalty for moving out of vector pipeline to FXU unit.
944     if (Index == 0 && Val->isIntOrIntVectorTy())
945       Cost += 1;
946 
947     return Cost;
948   }
949 
950   return BaseT::getVectorInstrCost(Opcode, Val, Index);
951 }
952 
953 // Check if a load may be folded as a memory operand in its user.
954 bool SystemZTTIImpl::
955 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) {
956   if (!Ld->hasOneUse())
957     return false;
958   FoldedValue = Ld;
959   const Instruction *UserI = cast<Instruction>(*Ld->user_begin());
960   unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
961   unsigned TruncBits = 0;
962   unsigned SExtBits = 0;
963   unsigned ZExtBits = 0;
964   if (UserI->hasOneUse()) {
965     unsigned UserBits = UserI->getType()->getScalarSizeInBits();
966     if (isa<TruncInst>(UserI))
967       TruncBits = UserBits;
968     else if (isa<SExtInst>(UserI))
969       SExtBits = UserBits;
970     else if (isa<ZExtInst>(UserI))
971       ZExtBits = UserBits;
972   }
973   if (TruncBits || SExtBits || ZExtBits) {
974     FoldedValue = UserI;
975     UserI = cast<Instruction>(*UserI->user_begin());
976     // Load (single use) -> trunc/extend (single use) -> UserI
977   }
978   if ((UserI->getOpcode() == Instruction::Sub ||
979        UserI->getOpcode() == Instruction::SDiv ||
980        UserI->getOpcode() == Instruction::UDiv) &&
981       UserI->getOperand(1) != FoldedValue)
982     return false; // Not commutative, only RHS foldable.
983   // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
984   // extension was made of the load.
985   unsigned LoadOrTruncBits =
986       ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
987   switch (UserI->getOpcode()) {
988   case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
989   case Instruction::Sub:
990   case Instruction::ICmp:
991     if (LoadedBits == 32 && ZExtBits == 64)
992       return true;
993     LLVM_FALLTHROUGH;
994   case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
995     if (UserI->getOpcode() != Instruction::ICmp) {
996       if (LoadedBits == 16 &&
997           (SExtBits == 32 ||
998            (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
999         return true;
1000       if (LoadOrTruncBits == 16)
1001         return true;
1002     }
1003     LLVM_FALLTHROUGH;
1004   case Instruction::SDiv:// SE: 32->64
1005     if (LoadedBits == 32 && SExtBits == 64)
1006       return true;
1007     LLVM_FALLTHROUGH;
1008   case Instruction::UDiv:
1009   case Instruction::And:
1010   case Instruction::Or:
1011   case Instruction::Xor:
1012     // This also makes sense for float operations, but disabled for now due
1013     // to regressions.
1014     // case Instruction::FCmp:
1015     // case Instruction::FAdd:
1016     // case Instruction::FSub:
1017     // case Instruction::FMul:
1018     // case Instruction::FDiv:
1019 
1020     // All possible extensions of memory checked above.
1021 
1022     // Comparison between memory and immediate.
1023     if (UserI->getOpcode() == Instruction::ICmp)
1024       if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
1025         if (CI->getValue().isIntN(16))
1026           return true;
1027     return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
1028     break;
1029   }
1030   return false;
1031 }
1032 
1033 static bool isBswapIntrinsicCall(const Value *V) {
1034   if (const Instruction *I = dyn_cast<Instruction>(V))
1035     if (auto *CI = dyn_cast<CallInst>(I))
1036       if (auto *F = CI->getCalledFunction())
1037         if (F->getIntrinsicID() == Intrinsic::bswap)
1038           return true;
1039   return false;
1040 }
1041 
1042 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1043                                     MaybeAlign Alignment, unsigned AddressSpace,
1044                                     TTI::TargetCostKind CostKind,
1045                                     const Instruction *I) {
1046   assert(!Src->isVoidTy() && "Invalid type");
1047 
1048   // TODO: Handle other cost kinds.
1049   if (CostKind != TTI::TCK_RecipThroughput)
1050     return 1;
1051 
1052   if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
1053     // Store the load or its truncated or extended value in FoldedValue.
1054     const Instruction *FoldedValue = nullptr;
1055     if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
1056       const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin());
1057       assert (UserI->getNumOperands() == 2 && "Expected a binop.");
1058 
1059       // UserI can't fold two loads, so in that case return 0 cost only
1060       // half of the time.
1061       for (unsigned i = 0; i < 2; ++i) {
1062         if (UserI->getOperand(i) == FoldedValue)
1063           continue;
1064 
1065         if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
1066           LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
1067           if (!OtherLoad &&
1068               (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
1069                isa<ZExtInst>(OtherOp)))
1070             OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
1071           if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1072             return i == 0; // Both operands foldable.
1073         }
1074       }
1075 
1076       return 0; // Only I is foldable in user.
1077     }
1078   }
1079 
1080   unsigned NumOps =
1081     (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
1082 
1083   // Store/Load reversed saves one instruction.
1084   if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) &&
1085       I != nullptr) {
1086     if (Opcode == Instruction::Load && I->hasOneUse()) {
1087       const Instruction *LdUser = cast<Instruction>(*I->user_begin());
1088       // In case of load -> bswap -> store, return normal cost for the load.
1089       if (isBswapIntrinsicCall(LdUser) &&
1090           (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1091         return 0;
1092     }
1093     else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1094       const Value *StoredVal = SI->getValueOperand();
1095       if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1096         return 0;
1097     }
1098   }
1099 
1100   if (Src->getScalarSizeInBits() == 128)
1101     // 128 bit scalars are held in a pair of two 64 bit registers.
1102     NumOps *= 2;
1103 
1104   return  NumOps;
1105 }
1106 
1107 // The generic implementation of getInterleavedMemoryOpCost() is based on
1108 // adding costs of the memory operations plus all the extracts and inserts
1109 // needed for using / defining the vector operands. The SystemZ version does
1110 // roughly the same but bases the computations on vector permutations
1111 // instead.
1112 int SystemZTTIImpl::getInterleavedMemoryOpCost(
1113     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1114     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1115     bool UseMaskForCond, bool UseMaskForGaps) {
1116   if (UseMaskForCond || UseMaskForGaps)
1117     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1118                                              Alignment, AddressSpace, CostKind,
1119                                              UseMaskForCond, UseMaskForGaps);
1120   assert(isa<VectorType>(VecTy) &&
1121          "Expect a vector type for interleaved memory op");
1122 
1123   // Return the ceiling of dividing A by B.
1124   auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
1125 
1126   unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1127   assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1128   unsigned VF = NumElts / Factor;
1129   unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1130   unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1131   unsigned NumPermutes = 0;
1132 
1133   if (Opcode == Instruction::Load) {
1134     // Loading interleave groups may have gaps, which may mean fewer
1135     // loads. Find out how many vectors will be loaded in total, and in how
1136     // many of them each value will be in.
1137     BitVector UsedInsts(NumVectorMemOps, false);
1138     std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1139     for (unsigned Index : Indices)
1140       for (unsigned Elt = 0; Elt < VF; ++Elt) {
1141         unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1142         UsedInsts.set(Vec);
1143         ValueVecs[Index].set(Vec);
1144       }
1145     NumVectorMemOps = UsedInsts.count();
1146 
1147     for (unsigned Index : Indices) {
1148       // Estimate that each loaded source vector containing this Index
1149       // requires one operation, except that vperm can handle two input
1150       // registers first time for each dst vector.
1151       unsigned NumSrcVecs = ValueVecs[Index].count();
1152       unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U);
1153       assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1154       NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1155     }
1156   } else {
1157     // Estimate the permutes for each stored vector as the smaller of the
1158     // number of elements and the number of source vectors. Subtract one per
1159     // dst vector for vperm (S.A.).
1160     unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1161     unsigned NumDstVecs = NumVectorMemOps;
1162     assert (NumSrcVecs > 1 && "Expected at least two source vectors.");
1163     NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1164   }
1165 
1166   // Cost of load/store operations and the permutations needed.
1167   return NumVectorMemOps + NumPermutes;
1168 }
1169 
1170 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) {
1171   if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1172     return getNumVectorRegs(RetTy); // VPERM
1173   return -1;
1174 }
1175 
1176 int SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1177                                           TTI::TargetCostKind CostKind) {
1178   int Cost = getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType());
1179   if (Cost != -1)
1180     return Cost;
1181   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1182 }
1183