blob: f52c9ca6e491c5b205f8a296c65a284d55071bd1 [file] [log] [blame]
Ulrich Weigand1f6666a2015-03-31 12:52:27 +00001//===-- 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"
David Blaikieb3bde2e2017-11-17 01:07:10 +000020#include "llvm/CodeGen/CostTable.h"
21#include "llvm/CodeGen/TargetLowering.h"
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000022#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/Support/Debug.h"
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000024using namespace llvm;
25
26#define DEBUG_TYPE "systemztti"
27
28//===----------------------------------------------------------------------===//
29//
30// SystemZ cost model.
31//
32//===----------------------------------------------------------------------===//
33
Chandler Carruth93205eb2015-08-05 18:08:10 +000034int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000035 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
Chandler Carruth93205eb2015-08-05 18:08:10 +000066int SystemZTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx,
67 const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000068 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
Chandler Carruth93205eb2015-08-05 18:08:10 +0000184int SystemZTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
185 const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +0000186 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}
Ulrich Weigandb4012182015-03-31 12:56:33 +0000232
233TargetTransformInfo::PopcntSupportKind
234SystemZTTIImpl::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
Geoff Berry66d9bdb2017-06-28 15:53:17 +0000241void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000242 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)) {
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000262 Type *MemAccessTy = I.getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000263 NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, 0, 0);
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000264 }
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
Jonas Paulsson024e3192017-07-21 11:59:37 +0000295
296bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
297 TargetTransformInfo::LSRCost &C2) {
298 // SystemZ specific: check instruction count (first), and don't care about
299 // ImmCost, since offsets are checked explicitly.
300 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
301 C1.NumIVMuls, C1.NumBaseAdds,
302 C1.ScaleCost, C1.SetupCost) <
303 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
304 C2.NumIVMuls, C2.NumBaseAdds,
305 C2.ScaleCost, C2.SetupCost);
306}
307
Ulrich Weigandce4c1092015-05-05 19:25:42 +0000308unsigned SystemZTTIImpl::getNumberOfRegisters(bool Vector) {
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
Daniel Neilsonc0112ae2017-06-12 14:22:21 +0000318unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const {
Ulrich Weigandce4c1092015-05-05 19:25:42 +0000319 if (!Vector)
320 return 64;
321 if (ST->hasVector())
322 return 128;
323 return 0;
324}
325
Jonas Paulssone54cc1a2017-11-06 13:10:31 +0000326bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
327 EVT VT = TLI->getValueType(DL, DataType);
328 return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
329}
330
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000331// Return the bit size for the scalar type or vector element
332// type. getScalarSizeInBits() returns 0 for a pointer type.
333static unsigned getScalarSizeInBits(Type *Ty) {
334 unsigned Size =
335 (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
336 assert(Size > 0 && "Element must have non-zero size.");
337 return Size;
338}
339
340// getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
341// type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
342// 3.
343static unsigned getNumVectorRegs(Type *Ty) {
344 assert(Ty->isVectorTy() && "Expected vector type");
345 unsigned WideBits = getScalarSizeInBits(Ty) * Ty->getVectorNumElements();
346 assert(WideBits > 0 && "Could not compute size of vector");
347 return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
348}
349
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000350int SystemZTTIImpl::getArithmeticInstrCost(
Fangrui Songf78650a2018-07-30 19:41:25 +0000351 unsigned Opcode, Type *Ty,
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000352 TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
353 TTI::OperandValueProperties Opd1PropInfo,
354 TTI::OperandValueProperties Opd2PropInfo,
355 ArrayRef<const Value *> Args) {
356
357 // TODO: return a good value for BB-VECTORIZER that includes the
358 // immediate loads, which we do not want to count for the loop
359 // vectorizer, since they are hopefully hoisted out of the loop. This
360 // would require a new parameter 'InLoop', but not sure if constant
361 // args are common enough to motivate this.
362
363 unsigned ScalarBits = Ty->getScalarSizeInBits();
364
Jonas Paulsson46457112018-10-25 21:47:22 +0000365 // There are thre cases of division and remainder: Dividing with a register
366 // needs a divide instruction. A divisor which is a power of two constant
367 // can be implemented with a sequence of shifts. Any other constant needs a
368 // multiply and shifts.
369 const unsigned DivInstrCost = 20;
370 const unsigned DivMulSeqCost = 10;
371 const unsigned SDivPow2Cost = 4;
372
373 bool SignedDivRem =
374 Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
375 bool UnsignedDivRem =
376 Opcode == Instruction::UDiv || Opcode == Instruction::URem;
377
378 // Check for a constant divisor.
379 bool DivRemConst = false;
380 bool DivRemConstPow2 = false;
381 if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000382 if (const Constant *C = dyn_cast<Constant>(Args[1])) {
Jonas Paulsson46457112018-10-25 21:47:22 +0000383 const ConstantInt *CVal =
384 (C->getType()->isVectorTy()
385 ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
386 : dyn_cast<const ConstantInt>(C));
387 if (CVal != nullptr &&
388 (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2()))
389 DivRemConstPow2 = true;
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000390 else
Jonas Paulsson46457112018-10-25 21:47:22 +0000391 DivRemConst = true;
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000392 }
393 }
394
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000395 if (Ty->isVectorTy()) {
396 assert (ST->hasVector() && "getArithmeticInstrCost() called with vector type.");
397 unsigned VF = Ty->getVectorNumElements();
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000398 unsigned NumVectors = getNumVectorRegs(Ty);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000399
400 // These vector operations are custom handled, but are still supported
401 // with one instruction per vector, regardless of element size.
402 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
Jonas Paulsson46457112018-10-25 21:47:22 +0000403 Opcode == Instruction::AShr) {
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000404 return NumVectors;
405 }
406
Jonas Paulsson46457112018-10-25 21:47:22 +0000407 if (DivRemConstPow2)
408 return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1));
409 if (DivRemConst)
410 return VF * DivMulSeqCost + getScalarizationOverhead(Ty, Args);
411 if ((SignedDivRem || UnsignedDivRem) && VF > 4)
412 // Temporary hack: disable high vectorization factors with integer
413 // division/remainder, which will get scalarized and handled with
414 // GR128 registers. The mischeduler is not clever enough to avoid
415 // spilling yet.
Jonas Paulssonbf66f382018-10-10 09:30:29 +0000416 return 1000;
417
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000418 // These FP operations are supported with a single vector instruction for
419 // double (base implementation assumes float generally costs 2). For
420 // FP128, the scalar cost is 1, and there is no overhead since the values
421 // are already in scalar registers.
422 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
423 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
424 switch (ScalarBits) {
425 case 32: {
Ulrich Weigand33435c42017-07-17 17:42:48 +0000426 // The vector enhancements facility 1 provides v4f32 instructions.
427 if (ST->hasVectorEnhancements1())
428 return NumVectors;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000429 // Return the cost of multiple scalar invocation plus the cost of
430 // inserting and extracting the values.
431 unsigned ScalarCost = getArithmeticInstrCost(Opcode, Ty->getScalarType());
432 unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(Ty, Args);
433 // FIXME: VF 2 for these FP operations are currently just as
434 // expensive as for VF 4.
435 if (VF == 2)
436 Cost *= 2;
437 return Cost;
438 }
439 case 64:
440 case 128:
441 return NumVectors;
442 default:
443 break;
444 }
445 }
446
447 // There is no native support for FRem.
448 if (Opcode == Instruction::FRem) {
449 unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(Ty, Args);
450 // FIXME: VF 2 for float is currently just as expensive as for VF 4.
451 if (VF == 2 && ScalarBits == 32)
452 Cost *= 2;
453 return Cost;
454 }
455 }
456 else { // Scalar:
457 // These FP operations are supported with a dedicated instruction for
458 // float, double and fp128 (base implementation assumes float generally
459 // costs 2).
460 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
461 Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
462 return 1;
463
464 // There is no native support for FRem.
465 if (Opcode == Instruction::FRem)
466 return LIBCALL_COST;
467
468 if (Opcode == Instruction::LShr || Opcode == Instruction::AShr)
469 return (ScalarBits >= 32 ? 1 : 2 /*ext*/);
470
471 // Or requires one instruction, although it has custom handling for i64.
472 if (Opcode == Instruction::Or)
473 return 1;
474
Jonas Paulsson77df2f22018-09-14 06:46:55 +0000475 if (Opcode == Instruction::Xor && ScalarBits == 1) {
476 if (ST->hasLoadStoreOnCond2())
477 return 5; // 2 * (li 0; loc 1); xor
478 return 7; // 2 * ipm sequences ; xor ; shift ; compare
479 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000480
Jonas Paulsson46457112018-10-25 21:47:22 +0000481 if (DivRemConstPow2)
482 return (SignedDivRem ? SDivPow2Cost : 1);
483 if (DivRemConst)
484 return DivMulSeqCost;
485 if (SignedDivRem)
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000486 // sext of op(s) for narrow types
Jonas Paulsson46457112018-10-25 21:47:22 +0000487 return DivInstrCost + (ScalarBits < 32 ? 3 : (ScalarBits == 32 ? 1 : 0));
488 if (UnsignedDivRem)
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000489 // Clearing of low 64 bit reg + sext of op(s) for narrow types + dl[g]r
Jonas Paulsson46457112018-10-25 21:47:22 +0000490 return DivInstrCost + (ScalarBits < 32 ? 3 : 1);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000491 }
492
493 // Fallback to the default implementation.
494 return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
495 Opd1PropInfo, Opd2PropInfo, Args);
496}
497
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000498int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
499 Type *SubTp) {
500 assert (Tp->isVectorTy());
501 assert (ST->hasVector() && "getShuffleCost() called.");
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000502 unsigned NumVectors = getNumVectorRegs(Tp);
Fangrui Songf78650a2018-07-30 19:41:25 +0000503
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000504 // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
505
506 // FP128 values are always in scalar registers, so there is no work
507 // involved with a shuffle, except for broadcast. In that case register
508 // moves are done with a single instruction per element.
509 if (Tp->getScalarType()->isFP128Ty())
510 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
511
512 switch (Kind) {
513 case TargetTransformInfo::SK_ExtractSubvector:
514 // ExtractSubvector Index indicates start offset.
515
516 // Extracting a subvector from first index is a noop.
517 return (Index == 0 ? 0 : NumVectors);
518
519 case TargetTransformInfo::SK_Broadcast:
520 // Loop vectorizer calls here to figure out the extra cost of
521 // broadcasting a loaded value to all elements of a vector. Since vlrep
522 // loads and replicates with a single instruction, adjust the returned
523 // value.
524 return NumVectors - 1;
525
526 default:
527
528 // SystemZ supports single instruction permutation / replication.
529 return NumVectors;
530 }
531
532 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
533}
534
535// Return the log2 difference of the element sizes of the two vector types.
536static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
537 unsigned Bits0 = Ty0->getScalarSizeInBits();
538 unsigned Bits1 = Ty1->getScalarSizeInBits();
539
540 if (Bits1 > Bits0)
541 return (Log2_32(Bits1) - Log2_32(Bits0));
542
543 return (Log2_32(Bits0) - Log2_32(Bits1));
544}
545
546// Return the number of instructions needed to truncate SrcTy to DstTy.
547unsigned SystemZTTIImpl::
548getVectorTruncCost(Type *SrcTy, Type *DstTy) {
549 assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
550 assert (SrcTy->getPrimitiveSizeInBits() > DstTy->getPrimitiveSizeInBits() &&
551 "Packing must reduce size of vector type.");
552 assert (SrcTy->getVectorNumElements() == DstTy->getVectorNumElements() &&
553 "Packing should not change number of elements.");
554
555 // TODO: Since fp32 is expanded, the extract cost should always be 0.
556
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000557 unsigned NumParts = getNumVectorRegs(SrcTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000558 if (NumParts <= 2)
559 // Up to 2 vector registers can be truncated efficiently with pack or
560 // permute. The latter requires an immediate mask to be loaded, which
561 // typically gets hoisted out of a loop. TODO: return a good value for
562 // BB-VECTORIZER that includes the immediate loads, which we do not want
563 // to count for the loop vectorizer.
564 return 1;
565
566 unsigned Cost = 0;
567 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
568 unsigned VF = SrcTy->getVectorNumElements();
569 for (unsigned P = 0; P < Log2Diff; ++P) {
570 if (NumParts > 1)
571 NumParts /= 2;
572 Cost += NumParts;
573 }
574
575 // Currently, a general mix of permutes and pack instructions is output by
576 // isel, which follow the cost computation above except for this case which
577 // is one instruction less:
578 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
579 DstTy->getScalarSizeInBits() == 8)
580 Cost--;
581
582 return Cost;
583}
584
585// Return the cost of converting a vector bitmask produced by a compare
586// (SrcTy), to the type of the select or extend instruction (DstTy).
587unsigned SystemZTTIImpl::
588getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
589 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
590 "Should only be called with vector types.");
591
592 unsigned PackCost = 0;
593 unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
594 unsigned DstScalarBits = DstTy->getScalarSizeInBits();
595 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
596 if (SrcScalarBits > DstScalarBits)
597 // The bitmask will be truncated.
598 PackCost = getVectorTruncCost(SrcTy, DstTy);
599 else if (SrcScalarBits < DstScalarBits) {
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000600 unsigned DstNumParts = getNumVectorRegs(DstTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000601 // Each vector select needs its part of the bitmask unpacked.
602 PackCost = Log2Diff * DstNumParts;
603 // Extra cost for moving part of mask before unpacking.
604 PackCost += DstNumParts - 1;
605 }
606
607 return PackCost;
608}
609
610// Return the type of the compared operands. This is needed to compute the
611// cost for a Select / ZExt or SExt instruction.
612static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
613 Type *OpTy = nullptr;
614 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
615 OpTy = CI->getOperand(0)->getType();
616 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
Jonas Paulssonf40eac52017-05-03 13:33:45 +0000617 if (LogicI->getNumOperands() == 2)
618 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
619 if (isa<CmpInst>(LogicI->getOperand(1)))
620 OpTy = CI0->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000621
622 if (OpTy != nullptr) {
623 if (VF == 1) {
624 assert (!OpTy->isVectorTy() && "Expected scalar type");
625 return OpTy;
626 }
627 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may
628 // be either scalar or already vectorized with a same or lesser VF.
629 Type *ElTy = OpTy->getScalarType();
630 return VectorType::get(ElTy, VF);
631 }
632
633 return nullptr;
634}
635
636int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
637 const Instruction *I) {
638 unsigned DstScalarBits = Dst->getScalarSizeInBits();
639 unsigned SrcScalarBits = Src->getScalarSizeInBits();
640
641 if (Src->isVectorTy()) {
642 assert (ST->hasVector() && "getCastInstrCost() called with vector type.");
643 assert (Dst->isVectorTy());
644 unsigned VF = Src->getVectorNumElements();
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000645 unsigned NumDstVectors = getNumVectorRegs(Dst);
646 unsigned NumSrcVectors = getNumVectorRegs(Src);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000647
648 if (Opcode == Instruction::Trunc) {
649 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
650 return 0; // Check for NOOP conversions.
651 return getVectorTruncCost(Src, Dst);
652 }
653
654 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
655 if (SrcScalarBits >= 8) {
656 // ZExt/SExt will be handled with one unpack per doubling of width.
657 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
658
659 // For types that spans multiple vector registers, some additional
660 // instructions are used to setup the unpacking.
661 unsigned NumSrcVectorOps =
662 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
663 : (NumDstVectors / 2));
664
665 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
666 }
667 else if (SrcScalarBits == 1) {
668 // This should be extension of a compare i1 result.
669 // If we know what the widths of the compared operands, get the
670 // cost of converting it to Dst. Otherwise assume same widths.
671 unsigned Cost = 0;
672 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
673 if (CmpOpTy != nullptr)
674 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
675 if (Opcode == Instruction::ZExt)
676 // One 'vn' per dst vector with an immediate mask.
677 Cost += NumDstVectors;
678 return Cost;
679 }
680 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000681
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000682 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
683 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
684 // TODO: Fix base implementation which could simplify things a bit here
685 // (seems to miss on differentiating on scalar/vector types).
686
687 // Only 64 bit vector conversions are natively supported.
688 if (SrcScalarBits == 64 && DstScalarBits == 64)
689 return NumDstVectors;
690
691 // Return the cost of multiple scalar invocation plus the cost of
692 // inserting and extracting the values. Base implementation does not
693 // realize float->int gets scalarized.
694 unsigned ScalarCost = getCastInstrCost(Opcode, Dst->getScalarType(),
695 Src->getScalarType());
696 unsigned TotCost = VF * ScalarCost;
697 bool NeedsInserts = true, NeedsExtracts = true;
698 // FP128 registers do not get inserted or extracted.
699 if (DstScalarBits == 128 &&
700 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
701 NeedsInserts = false;
702 if (SrcScalarBits == 128 &&
703 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
704 NeedsExtracts = false;
705
706 TotCost += getScalarizationOverhead(Dst, NeedsInserts, NeedsExtracts);
707
708 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
709 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
710 TotCost *= 2;
711
712 return TotCost;
713 }
714
715 if (Opcode == Instruction::FPTrunc) {
716 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements.
717 return VF /*ldxbr/lexbr*/ + getScalarizationOverhead(Dst, true, false);
718 else // double -> float
719 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
720 }
721
722 if (Opcode == Instruction::FPExt) {
723 if (SrcScalarBits == 32 && DstScalarBits == 64) {
724 // float -> double is very rare and currently unoptimized. Instead of
725 // using vldeb, which can do two at a time, all conversions are
726 // scalarized.
727 return VF * 2;
728 }
729 // -> fp128. VF * lxdb/lxeb + extraction of elements.
730 return VF + getScalarizationOverhead(Src, false, true);
731 }
732 }
733 else { // Scalar
734 assert (!Dst->isVectorTy());
735
736 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP)
737 return (SrcScalarBits >= 32 ? 1 : 2 /*i8/i16 extend*/);
Fangrui Songf78650a2018-07-30 19:41:25 +0000738
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000739 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
740 Src->isIntegerTy(1)) {
Jonas Paulsson77df2f22018-09-14 06:46:55 +0000741 if (ST->hasLoadStoreOnCond2())
742 return 2; // li 0; loc 1
743
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000744 // This should be extension of a compare i1 result, which is done with
745 // ipm and a varying sequence of instructions.
746 unsigned Cost = 0;
747 if (Opcode == Instruction::SExt)
748 Cost = (DstScalarBits < 64 ? 3 : 4);
749 if (Opcode == Instruction::ZExt)
750 Cost = 3;
751 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
752 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
753 // If operands of an fp-type was compared, this costs +1.
754 Cost++;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000755 return Cost;
756 }
757 }
758
759 return BaseT::getCastInstrCost(Opcode, Dst, Src, I);
760}
761
762int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
763 const Instruction *I) {
764 if (ValTy->isVectorTy()) {
765 assert (ST->hasVector() && "getCmpSelInstrCost() called with vector type.");
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000766 unsigned VF = ValTy->getVectorNumElements();
767
768 // Called with a compare instruction.
769 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
770 unsigned PredicateExtraCost = 0;
771 if (I != nullptr) {
772 // Some predicates cost one or two extra instructions.
Craig Topper781aa182018-05-05 01:57:00 +0000773 switch (cast<CmpInst>(I)->getPredicate()) {
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000774 case CmpInst::Predicate::ICMP_NE:
775 case CmpInst::Predicate::ICMP_UGE:
776 case CmpInst::Predicate::ICMP_ULE:
777 case CmpInst::Predicate::ICMP_SGE:
778 case CmpInst::Predicate::ICMP_SLE:
779 PredicateExtraCost = 1;
780 break;
781 case CmpInst::Predicate::FCMP_ONE:
782 case CmpInst::Predicate::FCMP_ORD:
783 case CmpInst::Predicate::FCMP_UEQ:
784 case CmpInst::Predicate::FCMP_UNO:
785 PredicateExtraCost = 2;
786 break;
787 default:
788 break;
789 }
790 }
791
792 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
793 // floats. FIXME: <2 x float> generates same code as <4 x float>.
794 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000795 unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000796
797 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
798 return Cost;
799 }
800 else { // Called with a select instruction.
801 assert (Opcode == Instruction::Select);
802
803 // We can figure out the extra cost of packing / unpacking if the
804 // instruction was passed and the compare instruction is found.
805 unsigned PackCost = 0;
806 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
807 if (CmpOpTy != nullptr)
808 PackCost =
809 getVectorBitmaskConversionCost(CmpOpTy, ValTy);
810
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000811 return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000812 }
813 }
814 else { // Scalar
815 switch (Opcode) {
816 case Instruction::ICmp: {
817 unsigned Cost = 1;
818 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
819 Cost += 2; // extend both operands
820 return Cost;
821 }
822 case Instruction::Select:
823 if (ValTy->isFloatingPointTy())
824 return 4; // No load on condition for FP, so this costs a conditional jump.
825 return 1; // Load On Condition.
826 }
827 }
828
829 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, nullptr);
830}
831
832int SystemZTTIImpl::
833getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
834 // vlvgp will insert two grs into a vector register, so only count half the
835 // number of instructions.
Craig Topperfde47232017-07-09 07:04:03 +0000836 if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000837 return ((Index % 2 == 0) ? 1 : 0);
838
839 if (Opcode == Instruction::ExtractElement) {
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000840 int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000841
842 // Give a slight penalty for moving out of vector pipeline to FXU unit.
Craig Topper95d23472017-07-09 07:04:00 +0000843 if (Index == 0 && Val->isIntOrIntVectorTy())
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000844 Cost += 1;
845
846 return Cost;
847 }
848
849 return BaseT::getVectorInstrCost(Opcode, Val, Index);
850}
851
852int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
853 unsigned Alignment, unsigned AddressSpace,
854 const Instruction *I) {
855 assert(!Src->isVoidTy() && "Invalid type");
856
857 if (!Src->isVectorTy() && Opcode == Instruction::Load &&
858 I != nullptr && I->hasOneUse()) {
859 const Instruction *UserI = cast<Instruction>(*I->user_begin());
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000860 unsigned Bits = getScalarSizeInBits(Src);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000861 bool FoldsLoad = false;
862 switch (UserI->getOpcode()) {
863 case Instruction::ICmp:
864 case Instruction::Add:
865 case Instruction::Sub:
866 case Instruction::Mul:
867 case Instruction::SDiv:
868 case Instruction::UDiv:
869 case Instruction::And:
870 case Instruction::Or:
871 case Instruction::Xor:
872 // This also makes sense for float operations, but disabled for now due
873 // to regressions.
874 // case Instruction::FCmp:
875 // case Instruction::FAdd:
876 // case Instruction::FSub:
877 // case Instruction::FMul:
878 // case Instruction::FDiv:
879 FoldsLoad = (Bits == 32 || Bits == 64);
880 break;
881 }
882
883 if (FoldsLoad) {
884 assert (UserI->getNumOperands() == 2 &&
885 "Expected to only handle binops.");
886
887 // UserI can't fold two loads, so in that case return 0 cost only
888 // half of the time.
889 for (unsigned i = 0; i < 2; ++i) {
890 if (UserI->getOperand(i) == I)
891 continue;
892 if (LoadInst *LI = dyn_cast<LoadInst>(UserI->getOperand(i))) {
893 if (LI->hasOneUse())
894 return i == 0;
895 }
896 }
897
898 return 0;
899 }
900 }
901
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000902 unsigned NumOps =
903 (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000904
905 if (Src->getScalarSizeInBits() == 128)
906 // 128 bit scalars are held in a pair of two 64 bit registers.
907 NumOps *= 2;
908
909 return NumOps;
910}
911
912int SystemZTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
913 unsigned Factor,
914 ArrayRef<unsigned> Indices,
915 unsigned Alignment,
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000916 unsigned AddressSpace,
917 bool IsMasked) {
918 if (IsMasked)
919 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
920 Alignment, AddressSpace, IsMasked);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000921 assert(isa<VectorType>(VecTy) &&
922 "Expect a vector type for interleaved memory op");
923
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000924 int NumWideParts = getNumVectorRegs(VecTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000925
926 // How many source vectors are handled to produce a vectorized operand?
927 int NumElsPerVector = (VecTy->getVectorNumElements() / NumWideParts);
928 int NumSrcParts =
929 ((NumWideParts > NumElsPerVector) ? NumElsPerVector : NumWideParts);
930
931 // A Load group may have gaps.
932 unsigned NumOperands =
933 ((Opcode == Instruction::Load) ? Indices.size() : Factor);
934
935 // Each needed permute takes two vectors as input.
936 if (NumSrcParts > 1)
937 NumSrcParts--;
938 int NumPermutes = NumSrcParts * NumOperands;
939
940 // Cost of load/store operations and the permutations needed.
941 return NumWideParts + NumPermutes;
942}