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