blob: 304ee79d2b2eae0a2949e54f720d1bb1e4cdb186 [file] [log] [blame]
Ulrich Weigand1f6666a2015-03-31 12:52:27 +00001//===-- SystemZTargetTransformInfo.cpp - SystemZ-specific TTI -------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ulrich Weigand1f6666a2015-03-31 12:52:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a TargetTransformInfo analysis pass specific to the
10// SystemZ target machine. It uses the target's detailed information to provide
11// more precise answers to certain TTI queries, while letting the target
12// independent and default TTI implementations handle the rest.
13//
14//===----------------------------------------------------------------------===//
15
16#include "SystemZTargetTransformInfo.h"
17#include "llvm/Analysis/TargetTransformInfo.h"
18#include "llvm/CodeGen/BasicTTIImpl.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000019#include "llvm/CodeGen/CostTable.h"
20#include "llvm/CodeGen/TargetLowering.h"
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000021#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/Support/Debug.h"
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000023using namespace llvm;
24
25#define DEBUG_TYPE "systemztti"
26
27//===----------------------------------------------------------------------===//
28//
29// SystemZ cost model.
30//
31//===----------------------------------------------------------------------===//
32
Chandler Carruth93205eb2015-08-05 18:08:10 +000033int SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000034 assert(Ty->isIntegerTy());
35
36 unsigned BitSize = Ty->getPrimitiveSizeInBits();
37 // There is no cost model for constants with a bit size of 0. Return TCC_Free
38 // here, so that constant hoisting will ignore this constant.
39 if (BitSize == 0)
40 return TTI::TCC_Free;
41 // No cost model for operations on integers larger than 64 bit implemented yet.
42 if (BitSize > 64)
43 return TTI::TCC_Free;
44
45 if (Imm == 0)
46 return TTI::TCC_Free;
47
48 if (Imm.getBitWidth() <= 64) {
49 // Constants loaded via lgfi.
50 if (isInt<32>(Imm.getSExtValue()))
51 return TTI::TCC_Basic;
52 // Constants loaded via llilf.
53 if (isUInt<32>(Imm.getZExtValue()))
54 return TTI::TCC_Basic;
55 // Constants loaded via llihf:
56 if ((Imm.getZExtValue() & 0xffffffff) == 0)
57 return TTI::TCC_Basic;
58
59 return 2 * TTI::TCC_Basic;
60 }
61
62 return 4 * TTI::TCC_Basic;
63}
64
Chandler Carruth93205eb2015-08-05 18:08:10 +000065int SystemZTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx,
66 const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +000067 assert(Ty->isIntegerTy());
68
69 unsigned BitSize = Ty->getPrimitiveSizeInBits();
70 // There is no cost model for constants with a bit size of 0. Return TCC_Free
71 // here, so that constant hoisting will ignore this constant.
72 if (BitSize == 0)
73 return TTI::TCC_Free;
74 // No cost model for operations on integers larger than 64 bit implemented yet.
75 if (BitSize > 64)
76 return TTI::TCC_Free;
77
78 switch (Opcode) {
79 default:
80 return TTI::TCC_Free;
81 case Instruction::GetElementPtr:
82 // Always hoist the base address of a GetElementPtr. This prevents the
83 // creation of new constants for every base constant that gets constant
84 // folded with the offset.
85 if (Idx == 0)
86 return 2 * TTI::TCC_Basic;
87 return TTI::TCC_Free;
88 case Instruction::Store:
89 if (Idx == 0 && Imm.getBitWidth() <= 64) {
90 // Any 8-bit immediate store can by implemented via mvi.
91 if (BitSize == 8)
92 return TTI::TCC_Free;
93 // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi.
94 if (isInt<16>(Imm.getSExtValue()))
95 return TTI::TCC_Free;
96 }
97 break;
98 case Instruction::ICmp:
99 if (Idx == 1 && Imm.getBitWidth() <= 64) {
100 // Comparisons against signed 32-bit immediates implemented via cgfi.
101 if (isInt<32>(Imm.getSExtValue()))
102 return TTI::TCC_Free;
103 // Comparisons against unsigned 32-bit immediates implemented via clgfi.
104 if (isUInt<32>(Imm.getZExtValue()))
105 return TTI::TCC_Free;
106 }
107 break;
108 case Instruction::Add:
109 case Instruction::Sub:
110 if (Idx == 1 && Imm.getBitWidth() <= 64) {
111 // We use algfi/slgfi to add/subtract 32-bit unsigned immediates.
112 if (isUInt<32>(Imm.getZExtValue()))
113 return TTI::TCC_Free;
114 // Or their negation, by swapping addition vs. subtraction.
115 if (isUInt<32>(-Imm.getSExtValue()))
116 return TTI::TCC_Free;
117 }
118 break;
119 case Instruction::Mul:
120 if (Idx == 1 && Imm.getBitWidth() <= 64) {
121 // We use msgfi to multiply by 32-bit signed immediates.
122 if (isInt<32>(Imm.getSExtValue()))
123 return TTI::TCC_Free;
124 }
125 break;
126 case Instruction::Or:
127 case Instruction::Xor:
128 if (Idx == 1 && Imm.getBitWidth() <= 64) {
129 // Masks supported by oilf/xilf.
130 if (isUInt<32>(Imm.getZExtValue()))
131 return TTI::TCC_Free;
132 // Masks supported by oihf/xihf.
133 if ((Imm.getZExtValue() & 0xffffffff) == 0)
134 return TTI::TCC_Free;
135 }
136 break;
137 case Instruction::And:
138 if (Idx == 1 && Imm.getBitWidth() <= 64) {
139 // Any 32-bit AND operation can by implemented via nilf.
140 if (BitSize <= 32)
141 return TTI::TCC_Free;
142 // 64-bit masks supported by nilf.
143 if (isUInt<32>(~Imm.getZExtValue()))
144 return TTI::TCC_Free;
145 // 64-bit masks supported by nilh.
146 if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff)
147 return TTI::TCC_Free;
148 // Some 64-bit AND operations can be implemented via risbg.
149 const SystemZInstrInfo *TII = ST->getInstrInfo();
150 unsigned Start, End;
151 if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End))
152 return TTI::TCC_Free;
153 }
154 break;
155 case Instruction::Shl:
156 case Instruction::LShr:
157 case Instruction::AShr:
158 // Always return TCC_Free for the shift value of a shift instruction.
159 if (Idx == 1)
160 return TTI::TCC_Free;
161 break;
162 case Instruction::UDiv:
163 case Instruction::SDiv:
164 case Instruction::URem:
165 case Instruction::SRem:
166 case Instruction::Trunc:
167 case Instruction::ZExt:
168 case Instruction::SExt:
169 case Instruction::IntToPtr:
170 case Instruction::PtrToInt:
171 case Instruction::BitCast:
172 case Instruction::PHI:
173 case Instruction::Call:
174 case Instruction::Select:
175 case Instruction::Ret:
176 case Instruction::Load:
177 break;
178 }
179
180 return SystemZTTIImpl::getIntImmCost(Imm, Ty);
181}
182
Chandler Carruth93205eb2015-08-05 18:08:10 +0000183int SystemZTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
184 const APInt &Imm, Type *Ty) {
Ulrich Weigand1f6666a2015-03-31 12:52:27 +0000185 assert(Ty->isIntegerTy());
186
187 unsigned BitSize = Ty->getPrimitiveSizeInBits();
188 // There is no cost model for constants with a bit size of 0. Return TCC_Free
189 // here, so that constant hoisting will ignore this constant.
190 if (BitSize == 0)
191 return TTI::TCC_Free;
192 // No cost model for operations on integers larger than 64 bit implemented yet.
193 if (BitSize > 64)
194 return TTI::TCC_Free;
195
196 switch (IID) {
197 default:
198 return TTI::TCC_Free;
199 case Intrinsic::sadd_with_overflow:
200 case Intrinsic::uadd_with_overflow:
201 case Intrinsic::ssub_with_overflow:
202 case Intrinsic::usub_with_overflow:
203 // These get expanded to include a normal addition/subtraction.
204 if (Idx == 1 && Imm.getBitWidth() <= 64) {
205 if (isUInt<32>(Imm.getZExtValue()))
206 return TTI::TCC_Free;
207 if (isUInt<32>(-Imm.getSExtValue()))
208 return TTI::TCC_Free;
209 }
210 break;
211 case Intrinsic::smul_with_overflow:
212 case Intrinsic::umul_with_overflow:
213 // These get expanded to include a normal multiplication.
214 if (Idx == 1 && Imm.getBitWidth() <= 64) {
215 if (isInt<32>(Imm.getSExtValue()))
216 return TTI::TCC_Free;
217 }
218 break;
219 case Intrinsic::experimental_stackmap:
220 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
221 return TTI::TCC_Free;
222 break;
223 case Intrinsic::experimental_patchpoint_void:
224 case Intrinsic::experimental_patchpoint_i64:
225 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
226 return TTI::TCC_Free;
227 break;
228 }
229 return SystemZTTIImpl::getIntImmCost(Imm, Ty);
230}
Ulrich Weigandb4012182015-03-31 12:56:33 +0000231
232TargetTransformInfo::PopcntSupportKind
233SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) {
234 assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2");
235 if (ST->hasPopulationCount() && TyWidth <= 64)
236 return TTI::PSK_FastHardware;
237 return TTI::PSK_Software;
238}
239
Geoff Berry66d9bdb2017-06-28 15:53:17 +0000240void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000241 TTI::UnrollingPreferences &UP) {
242 // Find out if L contains a call, what the machine instruction count
243 // estimate is, and how many stores there are.
244 bool HasCall = false;
245 unsigned NumStores = 0;
246 for (auto &BB : L->blocks())
247 for (auto &I : *BB) {
248 if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
249 ImmutableCallSite CS(&I);
250 if (const Function *F = CS.getCalledFunction()) {
251 if (isLoweredToCall(F))
252 HasCall = true;
253 if (F->getIntrinsicID() == Intrinsic::memcpy ||
254 F->getIntrinsicID() == Intrinsic::memset)
255 NumStores++;
256 } else { // indirect call.
257 HasCall = true;
258 }
259 }
260 if (isa<StoreInst>(&I)) {
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000261 Type *MemAccessTy = I.getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000262 NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, 0, 0);
Jonas Paulsson58c5a7f2016-09-28 09:41:38 +0000263 }
264 }
265
266 // The z13 processor will run out of store tags if too many stores
267 // are fed into it too quickly. Therefore make sure there are not
268 // too many stores in the resulting unrolled loop.
269 unsigned const Max = (NumStores ? (12 / NumStores) : UINT_MAX);
270
271 if (HasCall) {
272 // Only allow full unrolling if loop has any calls.
273 UP.FullUnrollMaxCount = Max;
274 UP.MaxCount = 1;
275 return;
276 }
277
278 UP.MaxCount = Max;
279 if (UP.MaxCount <= 1)
280 return;
281
282 // Allow partial and runtime trip count unrolling.
283 UP.Partial = UP.Runtime = true;
284
285 UP.PartialThreshold = 75;
286 UP.DefaultUnrollRuntimeCount = 4;
287
288 // Allow expensive instructions in the pre-header of the loop.
289 UP.AllowExpensiveTripCount = true;
290
291 UP.Force = true;
292}
293
Jonas Paulsson024e3192017-07-21 11:59:37 +0000294
295bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
296 TargetTransformInfo::LSRCost &C2) {
297 // SystemZ specific: check instruction count (first), and don't care about
298 // ImmCost, since offsets are checked explicitly.
299 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
300 C1.NumIVMuls, C1.NumBaseAdds,
301 C1.ScaleCost, C1.SetupCost) <
302 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
303 C2.NumIVMuls, C2.NumBaseAdds,
304 C2.ScaleCost, C2.SetupCost);
305}
306
Ulrich Weigandce4c1092015-05-05 19:25:42 +0000307unsigned SystemZTTIImpl::getNumberOfRegisters(bool Vector) {
308 if (!Vector)
309 // Discount the stack pointer. Also leave out %r0, since it can't
310 // be used in an address.
311 return 14;
312 if (ST->hasVector())
313 return 32;
314 return 0;
315}
316
Daniel Neilsonc0112ae2017-06-12 14:22:21 +0000317unsigned SystemZTTIImpl::getRegisterBitWidth(bool Vector) const {
Ulrich Weigandce4c1092015-05-05 19:25:42 +0000318 if (!Vector)
319 return 64;
320 if (ST->hasVector())
321 return 128;
322 return 0;
323}
324
Jonas Paulssone54cc1a2017-11-06 13:10:31 +0000325bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
326 EVT VT = TLI->getValueType(DL, DataType);
327 return (VT.isScalarInteger() && TLI->isTypeLegal(VT));
328}
329
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000330// Return the bit size for the scalar type or vector element
331// type. getScalarSizeInBits() returns 0 for a pointer type.
332static unsigned getScalarSizeInBits(Type *Ty) {
333 unsigned Size =
334 (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits());
335 assert(Size > 0 && "Element must have non-zero size.");
336 return Size;
337}
338
339// getNumberOfParts() calls getTypeLegalizationCost() which splits the vector
340// type until it is legal. This would e.g. return 4 for <6 x i64>, instead of
341// 3.
342static unsigned getNumVectorRegs(Type *Ty) {
343 assert(Ty->isVectorTy() && "Expected vector type");
344 unsigned WideBits = getScalarSizeInBits(Ty) * Ty->getVectorNumElements();
345 assert(WideBits > 0 && "Could not compute size of vector");
346 return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U));
347}
348
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000349int SystemZTTIImpl::getArithmeticInstrCost(
Fangrui Songf78650a2018-07-30 19:41:25 +0000350 unsigned Opcode, Type *Ty,
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000351 TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
352 TTI::OperandValueProperties Opd1PropInfo,
353 TTI::OperandValueProperties Opd2PropInfo,
354 ArrayRef<const Value *> Args) {
355
356 // TODO: return a good value for BB-VECTORIZER that includes the
357 // immediate loads, which we do not want to count for the loop
358 // vectorizer, since they are hopefully hoisted out of the loop. This
359 // would require a new parameter 'InLoop', but not sure if constant
360 // args are common enough to motivate this.
361
362 unsigned ScalarBits = Ty->getScalarSizeInBits();
363
Jonas Paulsson46457112018-10-25 21:47:22 +0000364 // There are thre cases of division and remainder: Dividing with a register
365 // needs a divide instruction. A divisor which is a power of two constant
366 // can be implemented with a sequence of shifts. Any other constant needs a
367 // multiply and shifts.
368 const unsigned DivInstrCost = 20;
369 const unsigned DivMulSeqCost = 10;
370 const unsigned SDivPow2Cost = 4;
371
372 bool SignedDivRem =
373 Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
374 bool UnsignedDivRem =
375 Opcode == Instruction::UDiv || Opcode == Instruction::URem;
376
377 // Check for a constant divisor.
378 bool DivRemConst = false;
379 bool DivRemConstPow2 = false;
380 if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) {
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000381 if (const Constant *C = dyn_cast<Constant>(Args[1])) {
Jonas Paulsson46457112018-10-25 21:47:22 +0000382 const ConstantInt *CVal =
383 (C->getType()->isVectorTy()
384 ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue())
385 : dyn_cast<const ConstantInt>(C));
386 if (CVal != nullptr &&
387 (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2()))
388 DivRemConstPow2 = true;
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000389 else
Jonas Paulsson46457112018-10-25 21:47:22 +0000390 DivRemConst = true;
Jonas Paulsson8722ade2017-05-17 12:46:26 +0000391 }
392 }
393
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000394 if (Ty->isVectorTy()) {
Jonas Paulsson2b280ea2018-10-25 22:53:27 +0000395 assert(ST->hasVector() &&
396 "getArithmeticInstrCost() called with vector type.");
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000397 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.
Jonas Paulsson2b280ea2018-10-25 22:53:27 +0000431 unsigned ScalarCost =
432 getArithmeticInstrCost(Opcode, Ty->getScalarType());
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000433 unsigned Cost = (VF * ScalarCost) + getScalarizationOverhead(Ty, Args);
434 // FIXME: VF 2 for these FP operations are currently just as
435 // expensive as for VF 4.
436 if (VF == 2)
437 Cost *= 2;
438 return Cost;
439 }
440 case 64:
441 case 128:
442 return NumVectors;
443 default:
444 break;
445 }
446 }
447
448 // There is no native support for FRem.
449 if (Opcode == Instruction::FRem) {
450 unsigned Cost = (VF * LIBCALL_COST) + getScalarizationOverhead(Ty, Args);
451 // FIXME: VF 2 for float is currently just as expensive as for VF 4.
452 if (VF == 2 && ScalarBits == 32)
453 Cost *= 2;
454 return Cost;
455 }
456 }
457 else { // Scalar:
458 // These FP operations are supported with a dedicated instruction for
459 // float, double and fp128 (base implementation assumes float generally
460 // costs 2).
461 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
462 Opcode == Instruction::FMul || Opcode == Instruction::FDiv)
463 return 1;
464
465 // There is no native support for FRem.
466 if (Opcode == Instruction::FRem)
467 return LIBCALL_COST;
468
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000469 // Or requires one instruction, although it has custom handling for i64.
470 if (Opcode == Instruction::Or)
471 return 1;
472
Jonas Paulsson77df2f22018-09-14 06:46:55 +0000473 if (Opcode == Instruction::Xor && ScalarBits == 1) {
474 if (ST->hasLoadStoreOnCond2())
475 return 5; // 2 * (li 0; loc 1); xor
476 return 7; // 2 * ipm sequences ; xor ; shift ; compare
477 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000478
Jonas Paulsson46457112018-10-25 21:47:22 +0000479 if (DivRemConstPow2)
480 return (SignedDivRem ? SDivPow2Cost : 1);
481 if (DivRemConst)
482 return DivMulSeqCost;
Jonas Paulssonb1d01482018-11-30 07:09:34 +0000483 if (SignedDivRem || UnsignedDivRem)
484 return DivInstrCost;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000485 }
486
487 // Fallback to the default implementation.
488 return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
489 Opd1PropInfo, Opd2PropInfo, Args);
490}
491
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000492int SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
493 Type *SubTp) {
494 assert (Tp->isVectorTy());
495 assert (ST->hasVector() && "getShuffleCost() called.");
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000496 unsigned NumVectors = getNumVectorRegs(Tp);
Fangrui Songf78650a2018-07-30 19:41:25 +0000497
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000498 // TODO: Since fp32 is expanded, the shuffle cost should always be 0.
499
500 // FP128 values are always in scalar registers, so there is no work
501 // involved with a shuffle, except for broadcast. In that case register
502 // moves are done with a single instruction per element.
503 if (Tp->getScalarType()->isFP128Ty())
504 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0);
505
506 switch (Kind) {
507 case TargetTransformInfo::SK_ExtractSubvector:
508 // ExtractSubvector Index indicates start offset.
509
510 // Extracting a subvector from first index is a noop.
511 return (Index == 0 ? 0 : NumVectors);
512
513 case TargetTransformInfo::SK_Broadcast:
514 // Loop vectorizer calls here to figure out the extra cost of
515 // broadcasting a loaded value to all elements of a vector. Since vlrep
516 // loads and replicates with a single instruction, adjust the returned
517 // value.
518 return NumVectors - 1;
519
520 default:
521
522 // SystemZ supports single instruction permutation / replication.
523 return NumVectors;
524 }
525
526 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
527}
528
529// Return the log2 difference of the element sizes of the two vector types.
530static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) {
531 unsigned Bits0 = Ty0->getScalarSizeInBits();
532 unsigned Bits1 = Ty1->getScalarSizeInBits();
533
534 if (Bits1 > Bits0)
535 return (Log2_32(Bits1) - Log2_32(Bits0));
536
537 return (Log2_32(Bits0) - Log2_32(Bits1));
538}
539
540// Return the number of instructions needed to truncate SrcTy to DstTy.
541unsigned SystemZTTIImpl::
542getVectorTruncCost(Type *SrcTy, Type *DstTy) {
543 assert (SrcTy->isVectorTy() && DstTy->isVectorTy());
544 assert (SrcTy->getPrimitiveSizeInBits() > DstTy->getPrimitiveSizeInBits() &&
545 "Packing must reduce size of vector type.");
546 assert (SrcTy->getVectorNumElements() == DstTy->getVectorNumElements() &&
547 "Packing should not change number of elements.");
548
549 // TODO: Since fp32 is expanded, the extract cost should always be 0.
550
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000551 unsigned NumParts = getNumVectorRegs(SrcTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000552 if (NumParts <= 2)
553 // Up to 2 vector registers can be truncated efficiently with pack or
554 // permute. The latter requires an immediate mask to be loaded, which
555 // typically gets hoisted out of a loop. TODO: return a good value for
556 // BB-VECTORIZER that includes the immediate loads, which we do not want
557 // to count for the loop vectorizer.
558 return 1;
559
560 unsigned Cost = 0;
561 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
562 unsigned VF = SrcTy->getVectorNumElements();
563 for (unsigned P = 0; P < Log2Diff; ++P) {
564 if (NumParts > 1)
565 NumParts /= 2;
566 Cost += NumParts;
567 }
568
569 // Currently, a general mix of permutes and pack instructions is output by
570 // isel, which follow the cost computation above except for this case which
571 // is one instruction less:
572 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 &&
573 DstTy->getScalarSizeInBits() == 8)
574 Cost--;
575
576 return Cost;
577}
578
579// Return the cost of converting a vector bitmask produced by a compare
580// (SrcTy), to the type of the select or extend instruction (DstTy).
581unsigned SystemZTTIImpl::
582getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) {
583 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() &&
584 "Should only be called with vector types.");
585
586 unsigned PackCost = 0;
587 unsigned SrcScalarBits = SrcTy->getScalarSizeInBits();
588 unsigned DstScalarBits = DstTy->getScalarSizeInBits();
589 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy);
590 if (SrcScalarBits > DstScalarBits)
591 // The bitmask will be truncated.
592 PackCost = getVectorTruncCost(SrcTy, DstTy);
593 else if (SrcScalarBits < DstScalarBits) {
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000594 unsigned DstNumParts = getNumVectorRegs(DstTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000595 // Each vector select needs its part of the bitmask unpacked.
596 PackCost = Log2Diff * DstNumParts;
597 // Extra cost for moving part of mask before unpacking.
598 PackCost += DstNumParts - 1;
599 }
600
601 return PackCost;
602}
603
604// Return the type of the compared operands. This is needed to compute the
605// cost for a Select / ZExt or SExt instruction.
606static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) {
607 Type *OpTy = nullptr;
608 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0)))
609 OpTy = CI->getOperand(0)->getType();
610 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0)))
Jonas Paulssonf40eac52017-05-03 13:33:45 +0000611 if (LogicI->getNumOperands() == 2)
612 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0)))
613 if (isa<CmpInst>(LogicI->getOperand(1)))
614 OpTy = CI0->getOperand(0)->getType();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000615
616 if (OpTy != nullptr) {
617 if (VF == 1) {
618 assert (!OpTy->isVectorTy() && "Expected scalar type");
619 return OpTy;
620 }
621 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may
622 // be either scalar or already vectorized with a same or lesser VF.
623 Type *ElTy = OpTy->getScalarType();
624 return VectorType::get(ElTy, VF);
625 }
626
627 return nullptr;
628}
629
Jonas Paulssonf15a53b2018-11-01 09:01:51 +0000630// Get the cost of converting a boolean vector to a vector with same width
631// and element size as Dst, plus the cost of zero extending if needed.
632unsigned SystemZTTIImpl::
633getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst,
634 const Instruction *I) {
635 assert (Dst->isVectorTy());
636 unsigned VF = Dst->getVectorNumElements();
637 unsigned Cost = 0;
638 // If we know what the widths of the compared operands, get any cost of
639 // converting it to match Dst. Otherwise assume same widths.
640 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
641 if (CmpOpTy != nullptr)
642 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst);
643 if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP)
644 // One 'vn' per dst vector with an immediate mask.
645 Cost += getNumVectorRegs(Dst);
646 return Cost;
647}
648
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000649int SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
650 const Instruction *I) {
651 unsigned DstScalarBits = Dst->getScalarSizeInBits();
652 unsigned SrcScalarBits = Src->getScalarSizeInBits();
653
654 if (Src->isVectorTy()) {
655 assert (ST->hasVector() && "getCastInstrCost() called with vector type.");
656 assert (Dst->isVectorTy());
657 unsigned VF = Src->getVectorNumElements();
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000658 unsigned NumDstVectors = getNumVectorRegs(Dst);
659 unsigned NumSrcVectors = getNumVectorRegs(Src);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000660
661 if (Opcode == Instruction::Trunc) {
662 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits())
663 return 0; // Check for NOOP conversions.
664 return getVectorTruncCost(Src, Dst);
665 }
666
667 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
668 if (SrcScalarBits >= 8) {
669 // ZExt/SExt will be handled with one unpack per doubling of width.
670 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst);
671
672 // For types that spans multiple vector registers, some additional
673 // instructions are used to setup the unpacking.
674 unsigned NumSrcVectorOps =
675 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors)
676 : (NumDstVectors / 2));
677
678 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps;
679 }
Jonas Paulssonf15a53b2018-11-01 09:01:51 +0000680 else if (SrcScalarBits == 1)
681 return getBoolVecToIntConversionCost(Opcode, Dst, I);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000682 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000683
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000684 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP ||
685 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) {
686 // TODO: Fix base implementation which could simplify things a bit here
687 // (seems to miss on differentiating on scalar/vector types).
688
689 // Only 64 bit vector conversions are natively supported.
Jonas Paulssonf15a53b2018-11-01 09:01:51 +0000690 if (DstScalarBits == 64) {
691 if (SrcScalarBits == 64)
692 return NumDstVectors;
693
694 if (SrcScalarBits == 1)
695 return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors;
696 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000697
698 // Return the cost of multiple scalar invocation plus the cost of
699 // inserting and extracting the values. Base implementation does not
700 // realize float->int gets scalarized.
701 unsigned ScalarCost = getCastInstrCost(Opcode, Dst->getScalarType(),
702 Src->getScalarType());
703 unsigned TotCost = VF * ScalarCost;
704 bool NeedsInserts = true, NeedsExtracts = true;
705 // FP128 registers do not get inserted or extracted.
706 if (DstScalarBits == 128 &&
707 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP))
708 NeedsInserts = false;
709 if (SrcScalarBits == 128 &&
710 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI))
711 NeedsExtracts = false;
712
Jonas Paulsson5cea85d2018-11-12 15:32:27 +0000713 TotCost += getScalarizationOverhead(Src, false, NeedsExtracts);
714 TotCost += getScalarizationOverhead(Dst, NeedsInserts, false);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000715
716 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4.
717 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32)
718 TotCost *= 2;
719
720 return TotCost;
721 }
722
723 if (Opcode == Instruction::FPTrunc) {
724 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements.
725 return VF /*ldxbr/lexbr*/ + getScalarizationOverhead(Dst, true, false);
726 else // double -> float
727 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/);
728 }
729
730 if (Opcode == Instruction::FPExt) {
731 if (SrcScalarBits == 32 && DstScalarBits == 64) {
732 // float -> double is very rare and currently unoptimized. Instead of
733 // using vldeb, which can do two at a time, all conversions are
734 // scalarized.
735 return VF * 2;
736 }
737 // -> fp128. VF * lxdb/lxeb + extraction of elements.
738 return VF + getScalarizationOverhead(Src, false, true);
739 }
740 }
741 else { // Scalar
742 assert (!Dst->isVectorTy());
743
Jonas Paulssoncced2a22018-11-02 17:53:31 +0000744 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) {
745 if (SrcScalarBits >= 32 ||
746 (I != nullptr && isa<LoadInst>(I->getOperand(0))))
747 return 1;
748 return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/;
749 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000750
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000751 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
752 Src->isIntegerTy(1)) {
Jonas Paulsson77df2f22018-09-14 06:46:55 +0000753 if (ST->hasLoadStoreOnCond2())
754 return 2; // li 0; loc 1
755
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000756 // This should be extension of a compare i1 result, which is done with
757 // ipm and a varying sequence of instructions.
758 unsigned Cost = 0;
759 if (Opcode == Instruction::SExt)
760 Cost = (DstScalarBits < 64 ? 3 : 4);
761 if (Opcode == Instruction::ZExt)
762 Cost = 3;
763 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr);
764 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy())
765 // If operands of an fp-type was compared, this costs +1.
766 Cost++;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000767 return Cost;
768 }
769 }
770
771 return BaseT::getCastInstrCost(Opcode, Dst, Src, I);
772}
773
Jonas Paulssonb1d01482018-11-30 07:09:34 +0000774// Scalar i8 / i16 operations will typically be made after first extending
775// the operands to i32.
776static unsigned getOperandsExtensionCost(const Instruction *I) {
777 unsigned ExtCost = 0;
778 for (Value *Op : I->operands())
779 // A load of i8 or i16 sign/zero extends to i32.
780 if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op))
781 ExtCost++;
782
783 return ExtCost;
784}
785
Jonas Paulsson2b280ea2018-10-25 22:53:27 +0000786int SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
787 Type *CondTy, const Instruction *I) {
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000788 if (ValTy->isVectorTy()) {
789 assert (ST->hasVector() && "getCmpSelInstrCost() called with vector type.");
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000790 unsigned VF = ValTy->getVectorNumElements();
791
792 // Called with a compare instruction.
793 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
794 unsigned PredicateExtraCost = 0;
795 if (I != nullptr) {
796 // Some predicates cost one or two extra instructions.
Craig Topper781aa182018-05-05 01:57:00 +0000797 switch (cast<CmpInst>(I)->getPredicate()) {
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000798 case CmpInst::Predicate::ICMP_NE:
799 case CmpInst::Predicate::ICMP_UGE:
800 case CmpInst::Predicate::ICMP_ULE:
801 case CmpInst::Predicate::ICMP_SGE:
802 case CmpInst::Predicate::ICMP_SLE:
803 PredicateExtraCost = 1;
804 break;
805 case CmpInst::Predicate::FCMP_ONE:
806 case CmpInst::Predicate::FCMP_ORD:
807 case CmpInst::Predicate::FCMP_UEQ:
808 case CmpInst::Predicate::FCMP_UNO:
809 PredicateExtraCost = 2;
810 break;
811 default:
812 break;
813 }
814 }
815
816 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of
817 // floats. FIXME: <2 x float> generates same code as <4 x float>.
818 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1);
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000819 unsigned NumVecs_cmp = getNumVectorRegs(ValTy);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000820
821 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost));
822 return Cost;
823 }
824 else { // Called with a select instruction.
825 assert (Opcode == Instruction::Select);
826
827 // We can figure out the extra cost of packing / unpacking if the
828 // instruction was passed and the compare instruction is found.
829 unsigned PackCost = 0;
830 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr);
831 if (CmpOpTy != nullptr)
832 PackCost =
833 getVectorBitmaskConversionCost(CmpOpTy, ValTy);
834
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000835 return getNumVectorRegs(ValTy) /*vsel*/ + PackCost;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000836 }
837 }
838 else { // Scalar
839 switch (Opcode) {
840 case Instruction::ICmp: {
Jonas Paulsson8ae0f882018-12-03 14:30:18 +0000841 // A loaded value compared with 0 with multiple users becomes Load and
842 // Test. The load is then not foldable, so return 0 cost for the ICmp.
843 unsigned ScalarBits = ValTy->getScalarSizeInBits();
844 if (I != nullptr && ScalarBits >= 32)
845 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0)))
846 if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
847 if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() &&
848 C->getZExtValue() == 0)
849 return 0;
850
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000851 unsigned Cost = 1;
Jonas Paulssonb1d01482018-11-30 07:09:34 +0000852 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16)
853 Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000854 return Cost;
855 }
856 case Instruction::Select:
857 if (ValTy->isFloatingPointTy())
Jonas Paulsson2b280ea2018-10-25 22:53:27 +0000858 return 4; // No load on condition for FP - costs a conditional jump.
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000859 return 1; // Load On Condition.
860 }
861 }
862
863 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, nullptr);
864}
865
866int SystemZTTIImpl::
867getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
868 // vlvgp will insert two grs into a vector register, so only count half the
869 // number of instructions.
Craig Topperfde47232017-07-09 07:04:03 +0000870 if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64))
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000871 return ((Index % 2 == 0) ? 1 : 0);
872
873 if (Opcode == Instruction::ExtractElement) {
Jonas Paulsson2c8b3372018-10-10 07:36:27 +0000874 int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000875
876 // Give a slight penalty for moving out of vector pipeline to FXU unit.
Craig Topper95d23472017-07-09 07:04:00 +0000877 if (Index == 0 && Val->isIntOrIntVectorTy())
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000878 Cost += 1;
879
880 return Cost;
881 }
882
883 return BaseT::getVectorInstrCost(Opcode, Val, Index);
884}
885
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000886// Check if a load may be folded as a memory operand in its user.
887bool SystemZTTIImpl::
888isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) {
889 if (!Ld->hasOneUse())
890 return false;
891 FoldedValue = Ld;
892 const Instruction *UserI = cast<Instruction>(*Ld->user_begin());
893 unsigned LoadedBits = getScalarSizeInBits(Ld->getType());
894 unsigned TruncBits = 0;
895 unsigned SExtBits = 0;
896 unsigned ZExtBits = 0;
897 if (UserI->hasOneUse()) {
898 unsigned UserBits = UserI->getType()->getScalarSizeInBits();
899 if (isa<TruncInst>(UserI))
900 TruncBits = UserBits;
901 else if (isa<SExtInst>(UserI))
902 SExtBits = UserBits;
903 else if (isa<ZExtInst>(UserI))
904 ZExtBits = UserBits;
905 }
906 if (TruncBits || SExtBits || ZExtBits) {
907 FoldedValue = UserI;
908 UserI = cast<Instruction>(*UserI->user_begin());
909 // Load (single use) -> trunc/extend (single use) -> UserI
910 }
Jonas Paulssonaf8e0362018-10-30 13:41:03 +0000911 if ((UserI->getOpcode() == Instruction::Sub ||
912 UserI->getOpcode() == Instruction::SDiv ||
913 UserI->getOpcode() == Instruction::UDiv) &&
914 UserI->getOperand(1) != FoldedValue)
915 return false; // Not commutative, only RHS foldable.
Jonas Paulssond6b7aca2018-11-28 08:31:50 +0000916 // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an
917 // extension was made of the load.
918 unsigned LoadOrTruncBits =
919 ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits));
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000920 switch (UserI->getOpcode()) {
921 case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64
922 case Instruction::Sub:
Jonas Paulsson06acb3a2018-11-28 08:58:27 +0000923 case Instruction::ICmp:
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000924 if (LoadedBits == 32 && ZExtBits == 64)
925 return true;
926 LLVM_FALLTHROUGH;
927 case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64
Jonas Paulsson06acb3a2018-11-28 08:58:27 +0000928 if (UserI->getOpcode() != Instruction::ICmp) {
929 if (LoadedBits == 16 &&
930 (SExtBits == 32 ||
931 (SExtBits == 64 && ST->hasMiscellaneousExtensions2())))
932 return true;
933 if (LoadOrTruncBits == 16)
934 return true;
935 }
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000936 LLVM_FALLTHROUGH;
937 case Instruction::SDiv:// SE: 32->64
938 if (LoadedBits == 32 && SExtBits == 64)
939 return true;
940 LLVM_FALLTHROUGH;
941 case Instruction::UDiv:
942 case Instruction::And:
943 case Instruction::Or:
944 case Instruction::Xor:
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000945 // This also makes sense for float operations, but disabled for now due
946 // to regressions.
947 // case Instruction::FCmp:
948 // case Instruction::FAdd:
949 // case Instruction::FSub:
950 // case Instruction::FMul:
951 // case Instruction::FDiv:
952
953 // All possible extensions of memory checked above.
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000954
Jonas Paulsson011a5032018-11-28 08:08:05 +0000955 // Comparison between memory and immediate.
956 if (UserI->getOpcode() == Instruction::ICmp)
957 if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1)))
958 if (isUInt<16>(CI->getZExtValue()))
959 return true;
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000960 return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64);
961 break;
962 }
963 return false;
964}
965
Jonas Paulsson5da8e432018-11-28 07:52:34 +0000966static bool isBswapIntrinsicCall(const Value *V) {
967 if (const Instruction *I = dyn_cast<Instruction>(V))
968 if (auto *CI = dyn_cast<CallInst>(I))
969 if (auto *F = CI->getCalledFunction())
970 if (F->getIntrinsicID() == Intrinsic::bswap)
971 return true;
972 return false;
973}
974
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000975int SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
976 unsigned Alignment, unsigned AddressSpace,
977 const Instruction *I) {
978 assert(!Src->isVoidTy() && "Invalid type");
979
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000980 if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) {
981 // Store the load or its truncated or extended value in FoldedValue.
982 const Instruction *FoldedValue = nullptr;
983 if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) {
984 const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin());
985 assert (UserI->getNumOperands() == 2 && "Expected a binop.");
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000986
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000987 // UserI can't fold two loads, so in that case return 0 cost only
988 // half of the time.
989 for (unsigned i = 0; i < 2; ++i) {
990 if (UserI->getOperand(i) == FoldedValue)
991 continue;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +0000992
Jonas Paulssonb7caa802018-10-25 22:28:25 +0000993 if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){
994 LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp);
995 if (!OtherLoad &&
996 (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) ||
997 isa<ZExtInst>(OtherOp)))
998 OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0));
999 if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/))
1000 return i == 0; // Both operands foldable.
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001001 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001002 }
Jonas Paulssonb7caa802018-10-25 22:28:25 +00001003
1004 return 0; // Only I is foldable in user.
1005 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001006 }
1007
Jonas Paulsson2c8b3372018-10-10 07:36:27 +00001008 unsigned NumOps =
1009 (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src));
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001010
Jonas Paulsson5da8e432018-11-28 07:52:34 +00001011 // Store/Load reversed saves one instruction.
1012 if (!Src->isVectorTy() && NumOps == 1 && I != nullptr) {
1013 if (Opcode == Instruction::Load && I->hasOneUse()) {
1014 const Instruction *LdUser = cast<Instruction>(*I->user_begin());
1015 // In case of load -> bswap -> store, return normal cost for the load.
1016 if (isBswapIntrinsicCall(LdUser) &&
1017 (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin())))
1018 return 0;
1019 }
1020 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
1021 const Value *StoredVal = SI->getValueOperand();
1022 if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal))
1023 return 0;
1024 }
1025 }
1026
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001027 if (Src->getScalarSizeInBits() == 128)
1028 // 128 bit scalars are held in a pair of two 64 bit registers.
1029 NumOps *= 2;
1030
1031 return NumOps;
1032}
1033
Jonas Paulsson79f24412018-11-02 17:15:36 +00001034// The generic implementation of getInterleavedMemoryOpCost() is based on
1035// adding costs of the memory operations plus all the extracts and inserts
1036// needed for using / defining the vector operands. The SystemZ version does
1037// roughly the same but bases the computations on vector permutations
1038// instead.
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001039int SystemZTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
1040 unsigned Factor,
1041 ArrayRef<unsigned> Indices,
1042 unsigned Alignment,
Dorit Nuzman38bbf812018-10-14 08:50:06 +00001043 unsigned AddressSpace,
Dorit Nuzman34da6dd2018-10-31 09:57:56 +00001044 bool UseMaskForCond,
1045 bool UseMaskForGaps) {
1046 if (UseMaskForCond || UseMaskForGaps)
Dorit Nuzman38bbf812018-10-14 08:50:06 +00001047 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
Dorit Nuzman34da6dd2018-10-31 09:57:56 +00001048 Alignment, AddressSpace,
1049 UseMaskForCond, UseMaskForGaps);
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001050 assert(isa<VectorType>(VecTy) &&
1051 "Expect a vector type for interleaved memory op");
1052
Jonas Paulsson79f24412018-11-02 17:15:36 +00001053 // Return the ceiling of dividing A by B.
1054 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001055
Jonas Paulsson79f24412018-11-02 17:15:36 +00001056 unsigned NumElts = VecTy->getVectorNumElements();
1057 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1058 unsigned VF = NumElts / Factor;
1059 unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy));
1060 unsigned NumVectorMemOps = getNumVectorRegs(VecTy);
1061 unsigned NumPermutes = 0;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001062
Jonas Paulsson79f24412018-11-02 17:15:36 +00001063 if (Opcode == Instruction::Load) {
1064 // Loading interleave groups may have gaps, which may mean fewer
1065 // loads. Find out how many vectors will be loaded in total, and in how
1066 // many of them each value will be in.
1067 BitVector UsedInsts(NumVectorMemOps, false);
1068 std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false));
1069 for (unsigned Index : Indices)
1070 for (unsigned Elt = 0; Elt < VF; ++Elt) {
1071 unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg;
1072 UsedInsts.set(Vec);
1073 ValueVecs[Index].set(Vec);
1074 }
1075 NumVectorMemOps = UsedInsts.count();
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001076
Jonas Paulsson79f24412018-11-02 17:15:36 +00001077 for (unsigned Index : Indices) {
1078 // Estimate that each loaded source vector containing this Index
1079 // requires one operation, except that vperm can handle two input
1080 // registers first time for each dst vector.
1081 unsigned NumSrcVecs = ValueVecs[Index].count();
1082 unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U);
1083 assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources");
1084 NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs);
1085 }
1086 } else {
1087 // Estimate the permutes for each stored vector as the smaller of the
1088 // number of elements and the number of source vectors. Subtract one per
1089 // dst vector for vperm (S.A.).
1090 unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor);
1091 unsigned NumDstVecs = NumVectorMemOps;
1092 assert (NumSrcVecs > 1 && "Expected at least two source vectors.");
1093 NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs;
1094 }
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001095
1096 // Cost of load/store operations and the permutations needed.
Jonas Paulsson79f24412018-11-02 17:15:36 +00001097 return NumVectorMemOps + NumPermutes;
Jonas Paulssonfccc7d62017-04-12 11:49:08 +00001098}
Jonas Paulsson96782c22018-11-22 07:17:29 +00001099
1100static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) {
1101 if (RetTy->isVectorTy() && ID == Intrinsic::bswap)
1102 return getNumVectorRegs(RetTy); // VPERM
1103 return -1;
1104}
1105
1106int SystemZTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1107 ArrayRef<Value *> Args,
1108 FastMathFlags FMF, unsigned VF) {
1109 int Cost = getVectorIntrinsicInstrCost(ID, RetTy);
1110 if (Cost != -1)
1111 return Cost;
1112 return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
1113}
1114
1115int SystemZTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1116 ArrayRef<Type *> Tys,
1117 FastMathFlags FMF,
1118 unsigned ScalarizationCostPassed) {
1119 int Cost = getVectorIntrinsicInstrCost(ID, RetTy);
1120 if (Cost != -1)
1121 return Cost;
1122 return BaseT::getIntrinsicInstrCost(ID, RetTy, Tys,
1123 FMF, ScalarizationCostPassed);
1124}