blob: a4d9421e08aba272f41b049d91e4d6ed3f678cc7 [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"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Target/CostTable.h"
23#include "llvm/Target/TargetLowering.h"
24using 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 Paulssonfccc7d62017-04-12 11:49:08 +0000326int SystemZTTIImpl::getArithmeticInstrCost(
327 unsigned Opcode, Type *Ty,
328 TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
329 TTI::OperandValueProperties Opd1PropInfo,
330 TTI::OperandValueProperties Opd2PropInfo,
331 ArrayRef<const Value *> Args) {
332
333 // TODO: return a good value for BB-VECTORIZER that includes the
334 // immediate loads, which we do not want to count for the loop
335 // vectorizer, since they are hopefully hoisted out of the loop. This
336 // would require a new parameter 'InLoop', but not sure if constant
337 // args are common enough to motivate this.
338
339 unsigned ScalarBits = Ty->getScalarSizeInBits();
340
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000341 // Div with a constant which is a power of 2 will be converted by
342 // DAGCombiner to use shifts. With vector shift-element instructions, a
343 // vector sdiv costs about as much as a scalar one.
344 const unsigned SDivCostEstimate = 4;
345 bool SDivPow2 = false;
346 bool UDivPow2 = false;
347 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv) &&
348 Args.size() == 2) {
349 const ConstantInt *CI = nullptr;
350 if (const Constant *C = dyn_cast<Constant>(Args[1])) {
351 if (C->getType()->isVectorTy())
352 CI = dyn_cast_or_null<const ConstantInt>(C->getSplatValue());
353 else
354 CI = dyn_cast<const ConstantInt>(C);
355 }
356 if (CI != nullptr &&
357 (CI->getValue().isPowerOf2() || (-CI->getValue()).isPowerOf2())) {
358 if (Opcode == Instruction::SDiv)
359 SDivPow2 = true;
360 else
361 UDivPow2 = true;
362 }
363 }
364
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000365 if (Ty->isVectorTy()) {
366 assert (ST->hasVector() && "getArithmeticInstrCost() called with vector type.");
367 unsigned VF = Ty->getVectorNumElements();
368 unsigned NumVectors = getNumberOfParts(Ty);
369
370 // These vector operations are custom handled, but are still supported
371 // with one instruction per vector, regardless of element size.
372 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000373 Opcode == Instruction::AShr || UDivPow2) {
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000374 return NumVectors;
375 }
376
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000377 if (SDivPow2)
378 return (NumVectors * SDivCostEstimate);
379
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000380 // These FP operations are supported with a single vector instruction for
381 // double (base implementation assumes float generally costs 2). For
382 // FP128, the scalar cost is 1, and there is no overhead since the values
383 // are already in scalar registers.
384 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
385 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) {
386 switch (ScalarBits) {
387 case 32: {
Ulrich Weigand33435c42017-07-17 17:42:48 +0000388 // The vector enhancements facility 1 provides v4f32 instructions.
389 if (ST->hasVectorEnhancements1())
390 return NumVectors;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000391 // Return the cost of multiple scalar invocation plus the cost of
392 // inserting and extracting the values.
393 unsigned ScalarCost = getArithmeticInstrCost(Opcode, Ty->getScalarType());
394 unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(Ty, Args);
395 // FIXME: VF 2 for these FP operations are currently just as
396 // expensive as for VF 4.
397 if (VF == 2)
398 Cost *= 2;
399 return Cost;
400 }
401 case 64:
402 case 128:
403 return NumVectors;
404 default:
405 break;
406 }
407 }
408
409 // There is no native support for FRem.
410 if (Opcode == Instruction::FRem) {
411 unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(Ty, Args);
412 // FIXME: VF 2 for float is currently just as expensive as for VF 4.
413 if (VF == 2 && ScalarBits == 32)
414 Cost *= 2;
415 return Cost;
416 }
417 }
418 else { // Scalar:
419 // These FP operations are supported with a dedicated instruction for
420 // float, double and fp128 (base implementation assumes float generally
421 // costs 2).
422 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
423 Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
424 return 1;
425
426 // There is no native support for FRem.
427 if (Opcode == Instruction::FRem)
428 return LIBCALL_COST;
429
430 if (Opcode == Instruction::LShr || Opcode == Instruction::AShr)
431 return (ScalarBits >= 32 ? 1 : 2 /*ext*/);
432
433 // Or requires one instruction, although it has custom handling for i64.
434 if (Opcode == Instruction::Or)
435 return 1;
436
437 if (Opcode == Instruction::Xor && ScalarBits == 1)
438 // 2 * ipm sequences ; xor ; shift ; compare
439 return 7;
440
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000441 if (UDivPow2)
442 return 1;
443 if (SDivPow2)
444 return SDivCostEstimate;
445
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000446 // An extra extension for narrow types is needed.
447 if ((Opcode == Instruction::SDiv || Opcode == Instruction::SRem))
448 // sext of op(s) for narrow types
449 return (ScalarBits < 32 ? 4 : (ScalarBits == 32 ? 2 : 1));
450
451 if (Opcode == Instruction::UDiv || Opcode == Instruction::URem)
452 // Clearing of low 64 bit reg + sext of op(s) for narrow types + dl[g]r
453 return (ScalarBits < 32 ? 4 : 2);
454 }
455
456 // Fallback to the default implementation.
457 return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
458 Opd1PropInfo, Opd2PropInfo, Args);
459}
460
461
462int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
463 Type *SubTp) {
464 assert (Tp->isVectorTy());
465 assert (ST->hasVector() && "getShuffleCost() called.");
466 unsigned NumVectors = getNumberOfParts(Tp);
467
468 // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
469
470 // FP128 values are always in scalar registers, so there is no work
471 // involved with a shuffle, except for broadcast. In that case register
472 // moves are done with a single instruction per element.
473 if (Tp->getScalarType()->isFP128Ty())
474 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
475
476 switch (Kind) {
477 case TargetTransformInfo::SK_ExtractSubvector:
478 // ExtractSubvector Index indicates start offset.
479
480 // Extracting a subvector from first index is a noop.
481 return (Index == 0 ? 0 : NumVectors);
482
483 case TargetTransformInfo::SK_Broadcast:
484 // Loop vectorizer calls here to figure out the extra cost of
485 // broadcasting a loaded value to all elements of a vector. Since vlrep
486 // loads and replicates with a single instruction, adjust the returned
487 // value.
488 return NumVectors - 1;
489
490 default:
491
492 // SystemZ supports single instruction permutation / replication.
493 return NumVectors;
494 }
495
496 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
497}
498
499// Return the log2 difference of the element sizes of the two vector types.
500static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
501 unsigned Bits0 = Ty0->getScalarSizeInBits();
502 unsigned Bits1 = Ty1->getScalarSizeInBits();
503
504 if (Bits1 > Bits0)
505 return (Log2_32(Bits1) - Log2_32(Bits0));
506
507 return (Log2_32(Bits0) - Log2_32(Bits1));
508}
509
510// Return the number of instructions needed to truncate SrcTy to DstTy.
511unsigned SystemZTTIImpl::
512getVectorTruncCost(Type *SrcTy, Type *DstTy) {
513 assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
514 assert (SrcTy->getPrimitiveSizeInBits() > DstTy->getPrimitiveSizeInBits() &&
515 "Packing must reduce size of vector type.");
516 assert (SrcTy->getVectorNumElements() == DstTy->getVectorNumElements() &&
517 "Packing should not change number of elements.");
518
519 // TODO: Since fp32 is expanded, the extract cost should always be 0.
520
521 unsigned NumParts = getNumberOfParts(SrcTy);
522 if (NumParts <= 2)
523 // Up to 2 vector registers can be truncated efficiently with pack or
524 // permute. The latter requires an immediate mask to be loaded, which
525 // typically gets hoisted out of a loop. TODO: return a good value for
526 // BB-VECTORIZER that includes the immediate loads, which we do not want
527 // to count for the loop vectorizer.
528 return 1;
529
530 unsigned Cost = 0;
531 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
532 unsigned VF = SrcTy->getVectorNumElements();
533 for (unsigned P = 0; P < Log2Diff; ++P) {
534 if (NumParts > 1)
535 NumParts /= 2;
536 Cost += NumParts;
537 }
538
539 // Currently, a general mix of permutes and pack instructions is output by
540 // isel, which follow the cost computation above except for this case which
541 // is one instruction less:
542 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
543 DstTy->getScalarSizeInBits() == 8)
544 Cost--;
545
546 return Cost;
547}
548
549// Return the cost of converting a vector bitmask produced by a compare
550// (SrcTy), to the type of the select or extend instruction (DstTy).
551unsigned SystemZTTIImpl::
552getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
553 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
554 "Should only be called with vector types.");
555
556 unsigned PackCost = 0;
557 unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
558 unsigned DstScalarBits = DstTy->getScalarSizeInBits();
559 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
560 if (SrcScalarBits > DstScalarBits)
561 // The bitmask will be truncated.
562 PackCost = getVectorTruncCost(SrcTy, DstTy);
563 else if (SrcScalarBits < DstScalarBits) {
564 unsigned DstNumParts = getNumberOfParts(DstTy);
565 // Each vector select needs its part of the bitmask unpacked.
566 PackCost = Log2Diff * DstNumParts;
567 // Extra cost for moving part of mask before unpacking.
568 PackCost += DstNumParts - 1;
569 }
570
571 return PackCost;
572}
573
574// Return the type of the compared operands. This is needed to compute the
575// cost for a Select / ZExt or SExt instruction.
576static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
577 Type *OpTy = nullptr;
578 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
579 OpTy = CI->getOperand(0)->getType();
580 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
Jonas Paulssonf40eac52017-05-03 13:33:45 +0000581 if (LogicI->getNumOperands() == 2)
582 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
583 if (isa<CmpInst>(LogicI->getOperand(1)))
584 OpTy = CI0->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000585
586 if (OpTy != nullptr) {
587 if (VF == 1) {
588 assert (!OpTy->isVectorTy() && "Expected scalar type");
589 return OpTy;
590 }
591 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may
592 // be either scalar or already vectorized with a same or lesser VF.
593 Type *ElTy = OpTy->getScalarType();
594 return VectorType::get(ElTy, VF);
595 }
596
597 return nullptr;
598}
599
600int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
601 const Instruction *I) {
602 unsigned DstScalarBits = Dst->getScalarSizeInBits();
603 unsigned SrcScalarBits = Src->getScalarSizeInBits();
604
605 if (Src->isVectorTy()) {
606 assert (ST->hasVector() && "getCastInstrCost() called with vector type.");
607 assert (Dst->isVectorTy());
608 unsigned VF = Src->getVectorNumElements();
609 unsigned NumDstVectors = getNumberOfParts(Dst);
610 unsigned NumSrcVectors = getNumberOfParts(Src);
611
612 if (Opcode == Instruction::Trunc) {
613 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
614 return 0; // Check for NOOP conversions.
615 return getVectorTruncCost(Src, Dst);
616 }
617
618 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
619 if (SrcScalarBits >= 8) {
620 // ZExt/SExt will be handled with one unpack per doubling of width.
621 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
622
623 // For types that spans multiple vector registers, some additional
624 // instructions are used to setup the unpacking.
625 unsigned NumSrcVectorOps =
626 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
627 : (NumDstVectors / 2));
628
629 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
630 }
631 else if (SrcScalarBits == 1) {
632 // This should be extension of a compare i1 result.
633 // If we know what the widths of the compared operands, get the
634 // cost of converting it to Dst. Otherwise assume same widths.
635 unsigned Cost = 0;
636 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
637 if (CmpOpTy != nullptr)
638 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
639 if (Opcode == Instruction::ZExt)
640 // One 'vn' per dst vector with an immediate mask.
641 Cost += NumDstVectors;
642 return Cost;
643 }
644 }
645
646 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
647 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
648 // TODO: Fix base implementation which could simplify things a bit here
649 // (seems to miss on differentiating on scalar/vector types).
650
651 // Only 64 bit vector conversions are natively supported.
652 if (SrcScalarBits == 64 && DstScalarBits == 64)
653 return NumDstVectors;
654
655 // Return the cost of multiple scalar invocation plus the cost of
656 // inserting and extracting the values. Base implementation does not
657 // realize float->int gets scalarized.
658 unsigned ScalarCost = getCastInstrCost(Opcode, Dst->getScalarType(),
659 Src->getScalarType());
660 unsigned TotCost = VF * ScalarCost;
661 bool NeedsInserts = true, NeedsExtracts = true;
662 // FP128 registers do not get inserted or extracted.
663 if (DstScalarBits == 128 &&
664 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
665 NeedsInserts = false;
666 if (SrcScalarBits == 128 &&
667 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
668 NeedsExtracts = false;
669
670 TotCost += getScalarizationOverhead(Dst, NeedsInserts, NeedsExtracts);
671
672 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
673 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
674 TotCost *= 2;
675
676 return TotCost;
677 }
678
679 if (Opcode == Instruction::FPTrunc) {
680 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements.
681 return VF /*ldxbr/lexbr*/ + getScalarizationOverhead(Dst, true, false);
682 else // double -> float
683 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
684 }
685
686 if (Opcode == Instruction::FPExt) {
687 if (SrcScalarBits == 32 && DstScalarBits == 64) {
688 // float -> double is very rare and currently unoptimized. Instead of
689 // using vldeb, which can do two at a time, all conversions are
690 // scalarized.
691 return VF * 2;
692 }
693 // -> fp128. VF * lxdb/lxeb + extraction of elements.
694 return VF + getScalarizationOverhead(Src, false, true);
695 }
696 }
697 else { // Scalar
698 assert (!Dst->isVectorTy());
699
700 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP)
701 return (SrcScalarBits >= 32 ? 1 : 2 /*i8/i16 extend*/);
702
703 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
704 Src->isIntegerTy(1)) {
705 // This should be extension of a compare i1 result, which is done with
706 // ipm and a varying sequence of instructions.
707 unsigned Cost = 0;
708 if (Opcode == Instruction::SExt)
709 Cost = (DstScalarBits < 64 ? 3 : 4);
710 if (Opcode == Instruction::ZExt)
711 Cost = 3;
712 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
713 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
714 // If operands of an fp-type was compared, this costs +1.
715 Cost++;
716
717 return Cost;
718 }
719 }
720
721 return BaseT::getCastInstrCost(Opcode, Dst, Src, I);
722}
723
724int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
725 const Instruction *I) {
726 if (ValTy->isVectorTy()) {
727 assert (ST->hasVector() && "getCmpSelInstrCost() called with vector type.");
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000728 unsigned VF = ValTy->getVectorNumElements();
729
730 // Called with a compare instruction.
731 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
732 unsigned PredicateExtraCost = 0;
733 if (I != nullptr) {
734 // Some predicates cost one or two extra instructions.
735 switch (dyn_cast<CmpInst>(I)->getPredicate()) {
736 case CmpInst::Predicate::ICMP_NE:
737 case CmpInst::Predicate::ICMP_UGE:
738 case CmpInst::Predicate::ICMP_ULE:
739 case CmpInst::Predicate::ICMP_SGE:
740 case CmpInst::Predicate::ICMP_SLE:
741 PredicateExtraCost = 1;
742 break;
743 case CmpInst::Predicate::FCMP_ONE:
744 case CmpInst::Predicate::FCMP_ORD:
745 case CmpInst::Predicate::FCMP_UEQ:
746 case CmpInst::Predicate::FCMP_UNO:
747 PredicateExtraCost = 2;
748 break;
749 default:
750 break;
751 }
752 }
753
754 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
755 // floats. FIXME: <2 x float> generates same code as <4 x float>.
756 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
757 unsigned NumVecs_cmp = getNumberOfParts(ValTy);
758
759 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
760 return Cost;
761 }
762 else { // Called with a select instruction.
763 assert (Opcode == Instruction::Select);
764
765 // We can figure out the extra cost of packing / unpacking if the
766 // instruction was passed and the compare instruction is found.
767 unsigned PackCost = 0;
768 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
769 if (CmpOpTy != nullptr)
770 PackCost =
771 getVectorBitmaskConversionCost(CmpOpTy, ValTy);
772
773 return getNumberOfParts(ValTy) /*vsel*/ + PackCost;
774 }
775 }
776 else { // Scalar
777 switch (Opcode) {
778 case Instruction::ICmp: {
779 unsigned Cost = 1;
780 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
781 Cost += 2; // extend both operands
782 return Cost;
783 }
784 case Instruction::Select:
785 if (ValTy->isFloatingPointTy())
786 return 4; // No load on condition for FP, so this costs a conditional jump.
787 return 1; // Load On Condition.
788 }
789 }
790
791 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, nullptr);
792}
793
794int SystemZTTIImpl::
795getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
796 // vlvgp will insert two grs into a vector register, so only count half the
797 // number of instructions.
Craig Topperfde47232017-07-09 07:04:03 +0000798 if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000799 return ((Index % 2 == 0) ? 1 : 0);
800
801 if (Opcode == Instruction::ExtractElement) {
802 int Cost = ((Val->getScalarSizeInBits() == 1) ? 2 /*+test-under-mask*/ : 1);
803
804 // Give a slight penalty for moving out of vector pipeline to FXU unit.
Craig Topper95d23472017-07-09 07:04:00 +0000805 if (Index == 0 && Val->isIntOrIntVectorTy())
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000806 Cost += 1;
807
808 return Cost;
809 }
810
811 return BaseT::getVectorInstrCost(Opcode, Val, Index);
812}
813
814int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
815 unsigned Alignment, unsigned AddressSpace,
816 const Instruction *I) {
817 assert(!Src->isVoidTy() && "Invalid type");
818
819 if (!Src->isVectorTy() && Opcode == Instruction::Load &&
820 I != nullptr && I->hasOneUse()) {
821 const Instruction *UserI = cast<Instruction>(*I->user_begin());
822 unsigned Bits = Src->getScalarSizeInBits();
823 bool FoldsLoad = false;
824 switch (UserI->getOpcode()) {
825 case Instruction::ICmp:
826 case Instruction::Add:
827 case Instruction::Sub:
828 case Instruction::Mul:
829 case Instruction::SDiv:
830 case Instruction::UDiv:
831 case Instruction::And:
832 case Instruction::Or:
833 case Instruction::Xor:
834 // This also makes sense for float operations, but disabled for now due
835 // to regressions.
836 // case Instruction::FCmp:
837 // case Instruction::FAdd:
838 // case Instruction::FSub:
839 // case Instruction::FMul:
840 // case Instruction::FDiv:
841 FoldsLoad = (Bits == 32 || Bits == 64);
842 break;
843 }
844
845 if (FoldsLoad) {
846 assert (UserI->getNumOperands() == 2 &&
847 "Expected to only handle binops.");
848
849 // UserI can't fold two loads, so in that case return 0 cost only
850 // half of the time.
851 for (unsigned i = 0; i < 2; ++i) {
852 if (UserI->getOperand(i) == I)
853 continue;
854 if (LoadInst *LI = dyn_cast<LoadInst>(UserI->getOperand(i))) {
855 if (LI->hasOneUse())
856 return i == 0;
857 }
858 }
859
860 return 0;
861 }
862 }
863
864 unsigned NumOps = getNumberOfParts(Src);
865
866 if (Src->getScalarSizeInBits() == 128)
867 // 128 bit scalars are held in a pair of two 64 bit registers.
868 NumOps *= 2;
869
870 return NumOps;
871}
872
873int SystemZTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
874 unsigned Factor,
875 ArrayRef<unsigned> Indices,
876 unsigned Alignment,
877 unsigned AddressSpace) {
878 assert(isa<VectorType>(VecTy) &&
879 "Expect a vector type for interleaved memory op");
880
881 unsigned WideBits = (VecTy->isPtrOrPtrVectorTy() ?
882 (64U * VecTy->getVectorNumElements()) : VecTy->getPrimitiveSizeInBits());
883 assert (WideBits > 0 && "Could not compute size of vector");
884 int NumWideParts =
885 ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
886
887 // How many source vectors are handled to produce a vectorized operand?
888 int NumElsPerVector = (VecTy->getVectorNumElements() / NumWideParts);
889 int NumSrcParts =
890 ((NumWideParts > NumElsPerVector) ? NumElsPerVector : NumWideParts);
891
892 // A Load group may have gaps.
893 unsigned NumOperands =
894 ((Opcode == Instruction::Load) ? Indices.size() : Factor);
895
896 // Each needed permute takes two vectors as input.
897 if (NumSrcParts > 1)
898 NumSrcParts--;
899 int NumPermutes = NumSrcParts * NumOperands;
900
901 // Cost of load/store operations and the permutations needed.
902 return NumWideParts + NumPermutes;
903}