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