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