1 //===-- SystemZTargetTransformInfo.cpp - SystemZ-specific TTI -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a TargetTransformInfo analysis pass specific to the
11 // SystemZ target machine. It uses the target's detailed information to provide
12 // more precise answers to certain TTI queries, while letting the target
13 // independent and default TTI implementations handle the rest.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "SystemZTargetTransformInfo.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/CodeGen/BasicTTIImpl.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/CostTable.h"
23 #include "llvm/Target/TargetLowering.h"
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "systemztti"
27 
28 //===----------------------------------------------------------------------===//
29 //
30 // SystemZ cost model.
31 //
32 //===----------------------------------------------------------------------===//
33 
34 int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
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::getIntImmCost(unsigned Opcode, unsigned Idx,
67                                   const APInt &Imm, Type *Ty) {
68   assert(Ty->isIntegerTy());
69 
70   unsigned BitSize = Ty->getPrimitiveSizeInBits();
71   // There is no cost model for constants with a bit size of 0. Return TCC_Free
72   // here, so that constant hoisting will ignore this constant.
73   if (BitSize == 0)
74     return TTI::TCC_Free;
75   // No cost model for operations on integers larger than 64 bit implemented yet.
76   if (BitSize > 64)
77     return TTI::TCC_Free;
78 
79   switch (Opcode) {
80   default:
81     return TTI::TCC_Free;
82   case Instruction::GetElementPtr:
83     // Always hoist the base address of a GetElementPtr. This prevents the
84     // creation of new constants for every base constant that gets constant
85     // folded with the offset.
86     if (Idx == 0)
87       return 2 * TTI::TCC_Basic;
88     return TTI::TCC_Free;
89   case Instruction::Store:
90     if (Idx == 0 && Imm.getBitWidth() <= 64) {
91       // Any 8-bit immediate store can by implemented via mvi.
92       if (BitSize == 8)
93         return TTI::TCC_Free;
94       // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi.
95       if (isInt<16>(Imm.getSExtValue()))
96         return TTI::TCC_Free;
97     }
98     break;
99   case Instruction::ICmp:
100     if (Idx == 1 && Imm.getBitWidth() <= 64) {
101       // Comparisons against signed 32-bit immediates implemented via cgfi.
102       if (isInt<32>(Imm.getSExtValue()))
103         return TTI::TCC_Free;
104       // Comparisons against unsigned 32-bit immediates implemented via clgfi.
105       if (isUInt<32>(Imm.getZExtValue()))
106         return TTI::TCC_Free;
107     }
108     break;
109   case Instruction::Add:
110   case Instruction::Sub:
111     if (Idx == 1 && Imm.getBitWidth() <= 64) {
112       // We use algfi/slgfi to add/subtract 32-bit unsigned immediates.
113       if (isUInt<32>(Imm.getZExtValue()))
114         return TTI::TCC_Free;
115       // Or their negation, by swapping addition vs. subtraction.
116       if (isUInt<32>(-Imm.getSExtValue()))
117         return TTI::TCC_Free;
118     }
119     break;
120   case Instruction::Mul:
121     if (Idx == 1 && Imm.getBitWidth() <= 64) {
122       // We use msgfi to multiply by 32-bit signed immediates.
123       if (isInt<32>(Imm.getSExtValue()))
124         return TTI::TCC_Free;
125     }
126     break;
127   case Instruction::Or:
128   case Instruction::Xor:
129     if (Idx == 1 && Imm.getBitWidth() <= 64) {
130       // Masks supported by oilf/xilf.
131       if (isUInt<32>(Imm.getZExtValue()))
132         return TTI::TCC_Free;
133       // Masks supported by oihf/xihf.
134       if ((Imm.getZExtValue() & 0xffffffff) == 0)
135         return TTI::TCC_Free;
136     }
137     break;
138   case Instruction::And:
139     if (Idx == 1 && Imm.getBitWidth() <= 64) {
140       // Any 32-bit AND operation can by implemented via nilf.
141       if (BitSize <= 32)
142         return TTI::TCC_Free;
143       // 64-bit masks supported by nilf.
144       if (isUInt<32>(~Imm.getZExtValue()))
145         return TTI::TCC_Free;
146       // 64-bit masks supported by nilh.
147       if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff)
148         return TTI::TCC_Free;
149       // Some 64-bit AND operations can be implemented via risbg.
150       const SystemZInstrInfo *TII = ST->getInstrInfo();
151       unsigned Start, End;
152       if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End))
153         return TTI::TCC_Free;
154     }
155     break;
156   case Instruction::Shl:
157   case Instruction::LShr:
158   case Instruction::AShr:
159     // Always return TCC_Free for the shift value of a shift instruction.
160     if (Idx == 1)
161       return TTI::TCC_Free;
162     break;
163   case Instruction::UDiv:
164   case Instruction::SDiv:
165   case Instruction::URem:
166   case Instruction::SRem:
167   case Instruction::Trunc:
168   case Instruction::ZExt:
169   case Instruction::SExt:
170   case Instruction::IntToPtr:
171   case Instruction::PtrToInt:
172   case Instruction::BitCast:
173   case Instruction::PHI:
174   case Instruction::Call:
175   case Instruction::Select:
176   case Instruction::Ret:
177   case Instruction::Load:
178     break;
179   }
180 
181   return SystemZTTIImpl::getIntImmCost(Imm, Ty);
182 }
183 
184 int SystemZTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
185                                   const APInt &Imm, Type *Ty) {
186   assert(Ty->isIntegerTy());
187 
188   unsigned BitSize = Ty->getPrimitiveSizeInBits();
189   // There is no cost model for constants with a bit size of 0. Return TCC_Free
190   // here, so that constant hoisting will ignore this constant.
191   if (BitSize == 0)
192     return TTI::TCC_Free;
193   // No cost model for operations on integers larger than 64 bit implemented yet.
194   if (BitSize > 64)
195     return TTI::TCC_Free;
196 
197   switch (IID) {
198   default:
199     return TTI::TCC_Free;
200   case Intrinsic::sadd_with_overflow:
201   case Intrinsic::uadd_with_overflow:
202   case Intrinsic::ssub_with_overflow:
203   case Intrinsic::usub_with_overflow:
204     // These get expanded to include a normal addition/subtraction.
205     if (Idx == 1 && Imm.getBitWidth() <= 64) {
206       if (isUInt<32>(Imm.getZExtValue()))
207         return TTI::TCC_Free;
208       if (isUInt<32>(-Imm.getSExtValue()))
209         return TTI::TCC_Free;
210     }
211     break;
212   case Intrinsic::smul_with_overflow:
213   case Intrinsic::umul_with_overflow:
214     // These get expanded to include a normal multiplication.
215     if (Idx == 1 && Imm.getBitWidth() <= 64) {
216       if (isInt<32>(Imm.getSExtValue()))
217         return TTI::TCC_Free;
218     }
219     break;
220   case Intrinsic::experimental_stackmap:
221     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
222       return TTI::TCC_Free;
223     break;
224   case Intrinsic::experimental_patchpoint_void:
225   case Intrinsic::experimental_patchpoint_i64:
226     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
227       return TTI::TCC_Free;
228     break;
229   }
230   return SystemZTTIImpl::getIntImmCost(Imm, Ty);
231 }
232 
233 TargetTransformInfo::PopcntSupportKind
234 SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) {
235   assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2");
236   if (ST->hasPopulationCount() && TyWidth <= 64)
237     return TTI::PSK_FastHardware;
238   return TTI::PSK_Software;
239 }
240 
241 void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
242                                              TTI::UnrollingPreferences &UP) {
243   // Find out if L contains a call, what the machine instruction count
244   // estimate is, and how many stores there are.
245   bool HasCall = false;
246   unsigned NumStores = 0;
247   for (auto &BB : L->blocks())
248     for (auto &I : *BB) {
249       if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
250         ImmutableCallSite CS(&I);
251         if (const Function *F = CS.getCalledFunction()) {
252           if (isLoweredToCall(F))
253             HasCall = true;
254           if (F->getIntrinsicID() == Intrinsic::memcpy ||
255               F->getIntrinsicID() == Intrinsic::memset)
256             NumStores++;
257         } else { // indirect call.
258           HasCall = true;
259         }
260       }
261       if (isa<StoreInst>(&I)) {
262         Type *MemAccessTy = I.getOperand(0)->getType();
263         NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, 0, 0);
264       }
265     }
266 
267   // The z13 processor will run out of store tags if too many stores
268   // are fed into it too quickly. Therefore make sure there are not
269   // too many stores in the resulting unrolled loop.
270   unsigned const Max = (NumStores ? (12 / NumStores) : UINT_MAX);
271 
272   if (HasCall) {
273     // Only allow full unrolling if loop has any calls.
274     UP.FullUnrollMaxCount = Max;
275     UP.MaxCount = 1;
276     return;
277   }
278 
279   UP.MaxCount = Max;
280   if (UP.MaxCount <= 1)
281     return;
282 
283   // Allow partial and runtime trip count unrolling.
284   UP.Partial = UP.Runtime = true;
285 
286   UP.PartialThreshold = 75;
287   UP.DefaultUnrollRuntimeCount = 4;
288 
289   // Allow expensive instructions in the pre-header of the loop.
290   UP.AllowExpensiveTripCount = true;
291 
292   UP.Force = true;
293 }
294 
295 unsigned SystemZTTIImpl::getNumberOfRegisters(bool Vector) {
296   if (!Vector)
297     // Discount the stack pointer.  Also leave out %r0, since it can't
298     // be used in an address.
299     return 14;
300   if (ST->hasVector())
301     return 32;
302   return 0;
303 }
304 
305 unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const {
306   if (!Vector)
307     return 64;
308   if (ST->hasVector())
309     return 128;
310   return 0;
311 }
312 
313 int SystemZTTIImpl::getArithmeticInstrCost(
314     unsigned Opcode, Type *Ty,
315     TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
316     TTI::OperandValueProperties Opd1PropInfo,
317     TTI::OperandValueProperties Opd2PropInfo,
318     ArrayRef<const Value *> Args) {
319 
320   // TODO: return a good value for BB-VECTORIZER that includes the
321   // immediate loads, which we do not want to count for the loop
322   // vectorizer, since they are hopefully hoisted out of the loop. This
323   // would require a new parameter 'InLoop', but not sure if constant
324   // args are common enough to motivate this.
325 
326   unsigned ScalarBits = Ty->getScalarSizeInBits();
327 
328   // Div with a constant which is a power of 2 will be converted by
329   // DAGCombiner to use shifts. With vector shift-element instructions, a
330   // vector sdiv costs about as much as a scalar one.
331   const unsigned SDivCostEstimate = 4;
332   bool SDivPow2 = false;
333   bool UDivPow2 = false;
334   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv) &&
335       Args.size() == 2) {
336     const ConstantInt *CI = nullptr;
337     if (const Constant *C = dyn_cast<Constant>(Args[1])) {
338       if (C->getType()->isVectorTy())
339         CI = dyn_cast_or_null<const ConstantInt>(C->getSplatValue());
340       else
341         CI = dyn_cast<const ConstantInt>(C);
342     }
343     if (CI != nullptr &&
344         (CI->getValue().isPowerOf2() || (-CI->getValue()).isPowerOf2())) {
345       if (Opcode == Instruction::SDiv)
346         SDivPow2 = true;
347       else
348         UDivPow2 = true;
349     }
350   }
351 
352   if (Ty->isVectorTy()) {
353     assert (ST->hasVector() && "getArithmeticInstrCost() called with vector type.");
354     unsigned VF = Ty->getVectorNumElements();
355     unsigned NumVectors = getNumberOfParts(Ty);
356 
357     // These vector operations are custom handled, but are still supported
358     // with one instruction per vector, regardless of element size.
359     if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
360         Opcode == Instruction::AShr || UDivPow2) {
361       return NumVectors;
362     }
363 
364     if (SDivPow2)
365       return (NumVectors * SDivCostEstimate);
366 
367     // These FP operations are supported with a single vector instruction for
368     // double (base implementation assumes float generally costs 2). For
369     // FP128, the scalar cost is 1, and there is no overhead since the values
370     // are already in scalar registers.
371     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
372         Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
373       switch (ScalarBits) {
374       case 32: {
375         // The vector enhancements facility 1 provides v4f32 instructions.
376         if (ST->hasVectorEnhancements1())
377           return NumVectors;
378         // Return the cost of multiple scalar invocation plus the cost of
379         // inserting and extracting the values.
380         unsigned ScalarCost = getArithmeticInstrCost(Opcode, Ty->getScalarType());
381         unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(Ty, Args);
382         // FIXME: VF 2 for these FP operations are currently just as
383         // expensive as for VF 4.
384         if (VF == 2)
385           Cost *= 2;
386         return Cost;
387       }
388       case 64:
389       case 128:
390         return NumVectors;
391       default:
392         break;
393       }
394     }
395 
396     // There is no native support for FRem.
397     if (Opcode == Instruction::FRem) {
398       unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(Ty, Args);
399       // FIXME: VF 2 for float is currently just as expensive as for VF 4.
400       if (VF == 2 && ScalarBits == 32)
401         Cost *= 2;
402       return Cost;
403     }
404   }
405   else {  // Scalar:
406     // These FP operations are supported with a dedicated instruction for
407     // float, double and fp128 (base implementation assumes float generally
408     // costs 2).
409     if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
410         Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
411       return 1;
412 
413     // There is no native support for FRem.
414     if (Opcode == Instruction::FRem)
415       return LIBCALL_COST;
416 
417     if (Opcode == Instruction::LShr || Opcode == Instruction::AShr)
418       return (ScalarBits >= 32 ? 1 : 2 /*ext*/);
419 
420     // Or requires one instruction, although it has custom handling for i64.
421     if (Opcode == Instruction::Or)
422       return 1;
423 
424     if (Opcode == Instruction::Xor && ScalarBits == 1)
425       // 2 * ipm sequences ; xor ; shift ; compare
426       return 7;
427 
428     if (UDivPow2)
429       return 1;
430     if (SDivPow2)
431       return SDivCostEstimate;
432 
433     // An extra extension for narrow types is needed.
434     if ((Opcode == Instruction::SDiv || Opcode == Instruction::SRem))
435       // sext of op(s) for narrow types
436       return (ScalarBits < 32 ? 4 : (ScalarBits == 32 ? 2 : 1));
437 
438     if (Opcode == Instruction::UDiv || Opcode == Instruction::URem)
439       // Clearing of low 64 bit reg + sext of op(s) for narrow types + dl[g]r
440       return (ScalarBits < 32 ? 4 : 2);
441   }
442 
443   // Fallback to the default implementation.
444   return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
445                                        Opd1PropInfo, Opd2PropInfo, Args);
446 }
447 
448 
449 int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
450                                    Type *SubTp) {
451   assert (Tp->isVectorTy());
452   assert (ST->hasVector() && "getShuffleCost() called.");
453   unsigned NumVectors = getNumberOfParts(Tp);
454 
455   // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
456 
457   // FP128 values are always in scalar registers, so there is no work
458   // involved with a shuffle, except for broadcast. In that case register
459   // moves are done with a single instruction per element.
460   if (Tp->getScalarType()->isFP128Ty())
461     return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
462 
463   switch (Kind) {
464   case  TargetTransformInfo::SK_ExtractSubvector:
465     // ExtractSubvector Index indicates start offset.
466 
467     // Extracting a subvector from first index is a noop.
468     return (Index == 0 ? 0 : NumVectors);
469 
470   case TargetTransformInfo::SK_Broadcast:
471     // Loop vectorizer calls here to figure out the extra cost of
472     // broadcasting a loaded value to all elements of a vector. Since vlrep
473     // loads and replicates with a single instruction, adjust the returned
474     // value.
475     return NumVectors - 1;
476 
477   default:
478 
479     // SystemZ supports single instruction permutation / replication.
480     return NumVectors;
481   }
482 
483   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
484 }
485 
486 // Return the log2 difference of the element sizes of the two vector types.
487 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
488   unsigned Bits0 = Ty0->getScalarSizeInBits();
489   unsigned Bits1 = Ty1->getScalarSizeInBits();
490 
491   if (Bits1 >  Bits0)
492     return (Log2_32(Bits1) - Log2_32(Bits0));
493 
494   return (Log2_32(Bits0) - Log2_32(Bits1));
495 }
496 
497 // Return the number of instructions needed to truncate SrcTy to DstTy.
498 unsigned SystemZTTIImpl::
499 getVectorTruncCost(Type *SrcTy, Type *DstTy) {
500   assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
501   assert (SrcTy->getPrimitiveSizeInBits() > DstTy->getPrimitiveSizeInBits() &&
502           "Packing must reduce size of vector type.");
503   assert (SrcTy->getVectorNumElements() == DstTy->getVectorNumElements() &&
504           "Packing should not change number of elements.");
505 
506   // TODO: Since fp32 is expanded, the extract cost should always be 0.
507 
508   unsigned NumParts = getNumberOfParts(SrcTy);
509   if (NumParts <= 2)
510     // Up to 2 vector registers can be truncated efficiently with pack or
511     // permute. The latter requires an immediate mask to be loaded, which
512     // typically gets hoisted out of a loop.  TODO: return a good value for
513     // BB-VECTORIZER that includes the immediate loads, which we do not want
514     // to count for the loop vectorizer.
515     return 1;
516 
517   unsigned Cost = 0;
518   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
519   unsigned VF = SrcTy->getVectorNumElements();
520   for (unsigned P = 0; P < Log2Diff; ++P) {
521     if (NumParts > 1)
522       NumParts /= 2;
523     Cost += NumParts;
524   }
525 
526   // Currently, a general mix of permutes and pack instructions is output by
527   // isel, which follow the cost computation above except for this case which
528   // is one instruction less:
529   if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
530       DstTy->getScalarSizeInBits() == 8)
531     Cost--;
532 
533   return Cost;
534 }
535 
536 // Return the cost of converting a vector bitmask produced by a compare
537 // (SrcTy), to the type of the select or extend instruction (DstTy).
538 unsigned SystemZTTIImpl::
539 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
540   assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
541           "Should only be called with vector types.");
542 
543   unsigned PackCost = 0;
544   unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
545   unsigned DstScalarBits = DstTy->getScalarSizeInBits();
546   unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
547   if (SrcScalarBits > DstScalarBits)
548     // The bitmask will be truncated.
549     PackCost = getVectorTruncCost(SrcTy, DstTy);
550   else if (SrcScalarBits < DstScalarBits) {
551     unsigned DstNumParts = getNumberOfParts(DstTy);
552     // Each vector select needs its part of the bitmask unpacked.
553     PackCost = Log2Diff * DstNumParts;
554     // Extra cost for moving part of mask before unpacking.
555     PackCost += DstNumParts - 1;
556   }
557 
558   return PackCost;
559 }
560 
561 // Return the type of the compared operands. This is needed to compute the
562 // cost for a Select / ZExt or SExt instruction.
563 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
564   Type *OpTy = nullptr;
565   if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
566     OpTy = CI->getOperand(0)->getType();
567   else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
568     if (LogicI->getNumOperands() == 2)
569       if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
570         if (isa<CmpInst>(LogicI->getOperand(1)))
571           OpTy = CI0->getOperand(0)->getType();
572 
573   if (OpTy != nullptr) {
574     if (VF == 1) {
575       assert (!OpTy->isVectorTy() && "Expected scalar type");
576       return OpTy;
577     }
578     // Return the potentially vectorized type based on 'I' and 'VF'.  'I' may
579     // be either scalar or already vectorized with a same or lesser VF.
580     Type *ElTy = OpTy->getScalarType();
581     return VectorType::get(ElTy, VF);
582   }
583 
584   return nullptr;
585 }
586 
587 int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
588                                      const Instruction *I) {
589   unsigned DstScalarBits = Dst->getScalarSizeInBits();
590   unsigned SrcScalarBits = Src->getScalarSizeInBits();
591 
592   if (Src->isVectorTy()) {
593     assert (ST->hasVector() && "getCastInstrCost() called with vector type.");
594     assert (Dst->isVectorTy());
595     unsigned VF = Src->getVectorNumElements();
596     unsigned NumDstVectors = getNumberOfParts(Dst);
597     unsigned NumSrcVectors = getNumberOfParts(Src);
598 
599     if (Opcode == Instruction::Trunc) {
600       if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
601         return 0; // Check for NOOP conversions.
602       return getVectorTruncCost(Src, Dst);
603     }
604 
605     if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
606       if (SrcScalarBits >= 8) {
607         // ZExt/SExt will be handled with one unpack per doubling of width.
608         unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
609 
610         // For types that spans multiple vector registers, some additional
611         // instructions are used to setup the unpacking.
612         unsigned NumSrcVectorOps =
613           (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
614                           : (NumDstVectors / 2));
615 
616         return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
617       }
618       else if (SrcScalarBits == 1) {
619         // This should be extension of a compare i1 result.
620         // If we know what the widths of the compared operands, get the
621         // cost of converting it to Dst. Otherwise assume same widths.
622         unsigned Cost = 0;
623         Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
624         if (CmpOpTy != nullptr)
625           Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
626         if (Opcode == Instruction::ZExt)
627           // One 'vn' per dst vector with an immediate mask.
628           Cost += NumDstVectors;
629         return Cost;
630       }
631     }
632 
633     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
634         Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
635       // TODO: Fix base implementation which could simplify things a bit here
636       // (seems to miss on differentiating on scalar/vector types).
637 
638       // Only 64 bit vector conversions are natively supported.
639       if (SrcScalarBits == 64 && DstScalarBits == 64)
640         return NumDstVectors;
641 
642       // Return the cost of multiple scalar invocation plus the cost of
643       // inserting and extracting the values. Base implementation does not
644       // realize float->int gets scalarized.
645       unsigned ScalarCost = getCastInstrCost(Opcode, Dst->getScalarType(),
646                                              Src->getScalarType());
647       unsigned TotCost = VF * ScalarCost;
648       bool NeedsInserts = true, NeedsExtracts = true;
649       // FP128 registers do not get inserted or extracted.
650       if (DstScalarBits == 128 &&
651           (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
652         NeedsInserts = false;
653       if (SrcScalarBits == 128 &&
654           (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
655         NeedsExtracts = false;
656 
657       TotCost += getScalarizationOverhead(Dst, NeedsInserts, NeedsExtracts);
658 
659       // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
660       if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
661         TotCost *= 2;
662 
663       return TotCost;
664     }
665 
666     if (Opcode == Instruction::FPTrunc) {
667       if (SrcScalarBits == 128)  // fp128 -> double/float + inserts of elements.
668         return VF /*ldxbr/lexbr*/ + getScalarizationOverhead(Dst, true, false);
669       else // double -> float
670         return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
671     }
672 
673     if (Opcode == Instruction::FPExt) {
674       if (SrcScalarBits == 32 && DstScalarBits == 64) {
675         // float -> double is very rare and currently unoptimized. Instead of
676         // using vldeb, which can do two at a time, all conversions are
677         // scalarized.
678         return VF * 2;
679       }
680       // -> fp128.  VF * lxdb/lxeb + extraction of elements.
681       return VF + getScalarizationOverhead(Src, false, true);
682     }
683   }
684   else { // Scalar
685     assert (!Dst->isVectorTy());
686 
687     if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP)
688       return (SrcScalarBits >= 32 ? 1 : 2 /*i8/i16 extend*/);
689 
690     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
691         Src->isIntegerTy(1)) {
692       // This should be extension of a compare i1 result, which is done with
693       // ipm and a varying sequence of instructions.
694       unsigned Cost = 0;
695       if (Opcode == Instruction::SExt)
696         Cost = (DstScalarBits < 64 ? 3 : 4);
697       if (Opcode == Instruction::ZExt)
698         Cost = 3;
699       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
700       if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
701         // If operands of an fp-type was compared, this costs +1.
702         Cost++;
703 
704       return Cost;
705     }
706   }
707 
708   return BaseT::getCastInstrCost(Opcode, Dst, Src, I);
709 }
710 
711 int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
712                                        const Instruction *I) {
713   if (ValTy->isVectorTy()) {
714     assert (ST->hasVector() && "getCmpSelInstrCost() called with vector type.");
715     unsigned VF = ValTy->getVectorNumElements();
716 
717     // Called with a compare instruction.
718     if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
719       unsigned PredicateExtraCost = 0;
720       if (I != nullptr) {
721         // Some predicates cost one or two extra instructions.
722         switch (dyn_cast<CmpInst>(I)->getPredicate()) {
723         case CmpInst::Predicate::ICMP_NE:
724         case CmpInst::Predicate::ICMP_UGE:
725         case CmpInst::Predicate::ICMP_ULE:
726         case CmpInst::Predicate::ICMP_SGE:
727         case CmpInst::Predicate::ICMP_SLE:
728           PredicateExtraCost = 1;
729           break;
730         case CmpInst::Predicate::FCMP_ONE:
731         case CmpInst::Predicate::FCMP_ORD:
732         case CmpInst::Predicate::FCMP_UEQ:
733         case CmpInst::Predicate::FCMP_UNO:
734           PredicateExtraCost = 2;
735           break;
736         default:
737           break;
738         }
739       }
740 
741       // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
742       // floats.  FIXME: <2 x float> generates same code as <4 x float>.
743       unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
744       unsigned NumVecs_cmp = getNumberOfParts(ValTy);
745 
746       unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
747       return Cost;
748     }
749     else { // Called with a select instruction.
750       assert (Opcode == Instruction::Select);
751 
752       // We can figure out the extra cost of packing / unpacking if the
753       // instruction was passed and the compare instruction is found.
754       unsigned PackCost = 0;
755       Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
756       if (CmpOpTy != nullptr)
757         PackCost =
758           getVectorBitmaskConversionCost(CmpOpTy, ValTy);
759 
760       return getNumberOfParts(ValTy) /*vsel*/ + PackCost;
761     }
762   }
763   else { // Scalar
764     switch (Opcode) {
765     case Instruction::ICmp: {
766       unsigned Cost = 1;
767       if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
768         Cost += 2; // extend both operands
769       return Cost;
770     }
771     case Instruction::Select:
772       if (ValTy->isFloatingPointTy())
773         return 4; // No load on condition for FP, so this costs a conditional jump.
774       return 1; // Load On Condition.
775     }
776   }
777 
778   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, nullptr);
779 }
780 
781 int SystemZTTIImpl::
782 getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
783   // vlvgp will insert two grs into a vector register, so only count half the
784   // number of instructions.
785   if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
786     return ((Index % 2 == 0) ? 1 : 0);
787 
788   if (Opcode == Instruction::ExtractElement) {
789     int Cost = ((Val->getScalarSizeInBits() == 1) ? 2 /*+test-under-mask*/ : 1);
790 
791     // Give a slight penalty for moving out of vector pipeline to FXU unit.
792     if (Index == 0 && Val->isIntOrIntVectorTy())
793       Cost += 1;
794 
795     return Cost;
796   }
797 
798   return BaseT::getVectorInstrCost(Opcode, Val, Index);
799 }
800 
801 int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
802                                     unsigned Alignment, unsigned AddressSpace,
803                                     const Instruction *I) {
804   assert(!Src->isVoidTy() && "Invalid type");
805 
806   if (!Src->isVectorTy() && Opcode == Instruction::Load &&
807       I != nullptr && I->hasOneUse()) {
808       const Instruction *UserI = cast<Instruction>(*I->user_begin());
809       unsigned Bits = Src->getScalarSizeInBits();
810       bool FoldsLoad = false;
811       switch (UserI->getOpcode()) {
812       case Instruction::ICmp:
813       case Instruction::Add:
814       case Instruction::Sub:
815       case Instruction::Mul:
816       case Instruction::SDiv:
817       case Instruction::UDiv:
818       case Instruction::And:
819       case Instruction::Or:
820       case Instruction::Xor:
821       // This also makes sense for float operations, but disabled for now due
822       // to regressions.
823       // case Instruction::FCmp:
824       // case Instruction::FAdd:
825       // case Instruction::FSub:
826       // case Instruction::FMul:
827       // case Instruction::FDiv:
828         FoldsLoad = (Bits == 32 || Bits == 64);
829         break;
830       }
831 
832       if (FoldsLoad) {
833         assert (UserI->getNumOperands() == 2 &&
834                 "Expected to only handle binops.");
835 
836         // UserI can't fold two loads, so in that case return 0 cost only
837         // half of the time.
838         for (unsigned i = 0; i < 2; ++i) {
839           if (UserI->getOperand(i) == I)
840             continue;
841           if (LoadInst *LI = dyn_cast<LoadInst>(UserI->getOperand(i))) {
842             if (LI->hasOneUse())
843               return i == 0;
844           }
845         }
846 
847         return 0;
848       }
849   }
850 
851   unsigned NumOps = getNumberOfParts(Src);
852 
853   if (Src->getScalarSizeInBits() == 128)
854     // 128 bit scalars are held in a pair of two 64 bit registers.
855     NumOps *= 2;
856 
857   return  NumOps;
858 }
859 
860 int SystemZTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
861                                                unsigned Factor,
862                                                ArrayRef<unsigned> Indices,
863                                                unsigned Alignment,
864                                                unsigned AddressSpace) {
865   assert(isa<VectorType>(VecTy) &&
866          "Expect a vector type for interleaved memory op");
867 
868   unsigned WideBits = (VecTy->isPtrOrPtrVectorTy() ?
869      (64U * VecTy->getVectorNumElements()) : VecTy->getPrimitiveSizeInBits());
870   assert (WideBits > 0 && "Could not compute size of vector");
871   int NumWideParts =
872     ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
873 
874   // How many source vectors are handled to produce a vectorized operand?
875   int NumElsPerVector = (VecTy->getVectorNumElements() / NumWideParts);
876   int NumSrcParts =
877     ((NumWideParts > NumElsPerVector) ? NumElsPerVector : NumWideParts);
878 
879   // A Load group may have gaps.
880   unsigned NumOperands =
881     ((Opcode == Instruction::Load) ? Indices.size() : Factor);
882 
883   // Each needed permute takes two vectors as input.
884   if (NumSrcParts > 1)
885     NumSrcParts--;
886   int NumPermutes = NumSrcParts * NumOperands;
887 
888   // Cost of load/store operations and the permutations needed.
889   return NumWideParts + NumPermutes;
890 }
891