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