1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the auto-upgrade helper functions.
10 // This is where deprecated IR intrinsics and other IR features are updated to
11 // current specifications.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/InstVisitor.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicsAArch64.h"
28 #include "llvm/IR/IntrinsicsARM.h"
29 #include "llvm/IR/IntrinsicsX86.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Regex.h"
35 #include <cstring>
36 using namespace llvm;
37
rename(GlobalValue * GV)38 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
39
40 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
41 // changed their type from v4f32 to v2i64.
UpgradePTESTIntrinsic(Function * F,Intrinsic::ID IID,Function * & NewFn)42 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
43 Function *&NewFn) {
44 // Check whether this is an old version of the function, which received
45 // v4f32 arguments.
46 Type *Arg0Type = F->getFunctionType()->getParamType(0);
47 if (Arg0Type != FixedVectorType::get(Type::getFloatTy(F->getContext()), 4))
48 return false;
49
50 // Yes, it's old, replace it with new version.
51 rename(F);
52 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
53 return true;
54 }
55
56 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
57 // arguments have changed their type from i32 to i8.
UpgradeX86IntrinsicsWith8BitMask(Function * F,Intrinsic::ID IID,Function * & NewFn)58 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
59 Function *&NewFn) {
60 // Check that the last argument is an i32.
61 Type *LastArgType = F->getFunctionType()->getParamType(
62 F->getFunctionType()->getNumParams() - 1);
63 if (!LastArgType->isIntegerTy(32))
64 return false;
65
66 // Move this function aside and map down.
67 rename(F);
68 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
69 return true;
70 }
71
72 // Upgrade the declaration of fp compare intrinsics that change return type
73 // from scalar to vXi1 mask.
UpgradeX86MaskedFPCompare(Function * F,Intrinsic::ID IID,Function * & NewFn)74 static bool UpgradeX86MaskedFPCompare(Function *F, Intrinsic::ID IID,
75 Function *&NewFn) {
76 // Check if the return type is a vector.
77 if (F->getReturnType()->isVectorTy())
78 return false;
79
80 rename(F);
81 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
82 return true;
83 }
84
UpgradeX86BF16Intrinsic(Function * F,Intrinsic::ID IID,Function * & NewFn)85 static bool UpgradeX86BF16Intrinsic(Function *F, Intrinsic::ID IID,
86 Function *&NewFn) {
87 if (F->getReturnType()->getScalarType()->isBFloatTy())
88 return false;
89
90 rename(F);
91 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
92 return true;
93 }
94
UpgradeX86BF16DPIntrinsic(Function * F,Intrinsic::ID IID,Function * & NewFn)95 static bool UpgradeX86BF16DPIntrinsic(Function *F, Intrinsic::ID IID,
96 Function *&NewFn) {
97 if (F->getFunctionType()->getParamType(1)->getScalarType()->isBFloatTy())
98 return false;
99
100 rename(F);
101 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
102 return true;
103 }
104
ShouldUpgradeX86Intrinsic(Function * F,StringRef Name)105 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
106 // All of the intrinsics matches below should be marked with which llvm
107 // version started autoupgrading them. At some point in the future we would
108 // like to use this information to remove upgrade code for some older
109 // intrinsics. It is currently undecided how we will determine that future
110 // point.
111 if (Name == "addcarryx.u32" || // Added in 8.0
112 Name == "addcarryx.u64" || // Added in 8.0
113 Name == "addcarry.u32" || // Added in 8.0
114 Name == "addcarry.u64" || // Added in 8.0
115 Name == "subborrow.u32" || // Added in 8.0
116 Name == "subborrow.u64" || // Added in 8.0
117 Name.startswith("sse2.padds.") || // Added in 8.0
118 Name.startswith("sse2.psubs.") || // Added in 8.0
119 Name.startswith("sse2.paddus.") || // Added in 8.0
120 Name.startswith("sse2.psubus.") || // Added in 8.0
121 Name.startswith("avx2.padds.") || // Added in 8.0
122 Name.startswith("avx2.psubs.") || // Added in 8.0
123 Name.startswith("avx2.paddus.") || // Added in 8.0
124 Name.startswith("avx2.psubus.") || // Added in 8.0
125 Name.startswith("avx512.padds.") || // Added in 8.0
126 Name.startswith("avx512.psubs.") || // Added in 8.0
127 Name.startswith("avx512.mask.padds.") || // Added in 8.0
128 Name.startswith("avx512.mask.psubs.") || // Added in 8.0
129 Name.startswith("avx512.mask.paddus.") || // Added in 8.0
130 Name.startswith("avx512.mask.psubus.") || // Added in 8.0
131 Name=="ssse3.pabs.b.128" || // Added in 6.0
132 Name=="ssse3.pabs.w.128" || // Added in 6.0
133 Name=="ssse3.pabs.d.128" || // Added in 6.0
134 Name.startswith("fma4.vfmadd.s") || // Added in 7.0
135 Name.startswith("fma.vfmadd.") || // Added in 7.0
136 Name.startswith("fma.vfmsub.") || // Added in 7.0
137 Name.startswith("fma.vfmsubadd.") || // Added in 7.0
138 Name.startswith("fma.vfnmadd.") || // Added in 7.0
139 Name.startswith("fma.vfnmsub.") || // Added in 7.0
140 Name.startswith("avx512.mask.vfmadd.") || // Added in 7.0
141 Name.startswith("avx512.mask.vfnmadd.") || // Added in 7.0
142 Name.startswith("avx512.mask.vfnmsub.") || // Added in 7.0
143 Name.startswith("avx512.mask3.vfmadd.") || // Added in 7.0
144 Name.startswith("avx512.maskz.vfmadd.") || // Added in 7.0
145 Name.startswith("avx512.mask3.vfmsub.") || // Added in 7.0
146 Name.startswith("avx512.mask3.vfnmsub.") || // Added in 7.0
147 Name.startswith("avx512.mask.vfmaddsub.") || // Added in 7.0
148 Name.startswith("avx512.maskz.vfmaddsub.") || // Added in 7.0
149 Name.startswith("avx512.mask3.vfmaddsub.") || // Added in 7.0
150 Name.startswith("avx512.mask3.vfmsubadd.") || // Added in 7.0
151 Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
152 Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
153 Name.startswith("avx512.kunpck") || //added in 6.0
154 Name.startswith("avx2.pabs.") || // Added in 6.0
155 Name.startswith("avx512.mask.pabs.") || // Added in 6.0
156 Name.startswith("avx512.broadcastm") || // Added in 6.0
157 Name == "sse.sqrt.ss" || // Added in 7.0
158 Name == "sse2.sqrt.sd" || // Added in 7.0
159 Name.startswith("avx512.mask.sqrt.p") || // Added in 7.0
160 Name.startswith("avx.sqrt.p") || // Added in 7.0
161 Name.startswith("sse2.sqrt.p") || // Added in 7.0
162 Name.startswith("sse.sqrt.p") || // Added in 7.0
163 Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
164 Name.startswith("sse2.pcmpeq.") || // Added in 3.1
165 Name.startswith("sse2.pcmpgt.") || // Added in 3.1
166 Name.startswith("avx2.pcmpeq.") || // Added in 3.1
167 Name.startswith("avx2.pcmpgt.") || // Added in 3.1
168 Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
169 Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
170 Name.startswith("avx.vperm2f128.") || // Added in 6.0
171 Name == "avx2.vperm2i128" || // Added in 6.0
172 Name == "sse.add.ss" || // Added in 4.0
173 Name == "sse2.add.sd" || // Added in 4.0
174 Name == "sse.sub.ss" || // Added in 4.0
175 Name == "sse2.sub.sd" || // Added in 4.0
176 Name == "sse.mul.ss" || // Added in 4.0
177 Name == "sse2.mul.sd" || // Added in 4.0
178 Name == "sse.div.ss" || // Added in 4.0
179 Name == "sse2.div.sd" || // Added in 4.0
180 Name == "sse41.pmaxsb" || // Added in 3.9
181 Name == "sse2.pmaxs.w" || // Added in 3.9
182 Name == "sse41.pmaxsd" || // Added in 3.9
183 Name == "sse2.pmaxu.b" || // Added in 3.9
184 Name == "sse41.pmaxuw" || // Added in 3.9
185 Name == "sse41.pmaxud" || // Added in 3.9
186 Name == "sse41.pminsb" || // Added in 3.9
187 Name == "sse2.pmins.w" || // Added in 3.9
188 Name == "sse41.pminsd" || // Added in 3.9
189 Name == "sse2.pminu.b" || // Added in 3.9
190 Name == "sse41.pminuw" || // Added in 3.9
191 Name == "sse41.pminud" || // Added in 3.9
192 Name == "avx512.kand.w" || // Added in 7.0
193 Name == "avx512.kandn.w" || // Added in 7.0
194 Name == "avx512.knot.w" || // Added in 7.0
195 Name == "avx512.kor.w" || // Added in 7.0
196 Name == "avx512.kxor.w" || // Added in 7.0
197 Name == "avx512.kxnor.w" || // Added in 7.0
198 Name == "avx512.kortestc.w" || // Added in 7.0
199 Name == "avx512.kortestz.w" || // Added in 7.0
200 Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
201 Name.startswith("avx2.pmax") || // Added in 3.9
202 Name.startswith("avx2.pmin") || // Added in 3.9
203 Name.startswith("avx512.mask.pmax") || // Added in 4.0
204 Name.startswith("avx512.mask.pmin") || // Added in 4.0
205 Name.startswith("avx2.vbroadcast") || // Added in 3.8
206 Name.startswith("avx2.pbroadcast") || // Added in 3.8
207 Name.startswith("avx.vpermil.") || // Added in 3.1
208 Name.startswith("sse2.pshuf") || // Added in 3.9
209 Name.startswith("avx512.pbroadcast") || // Added in 3.9
210 Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
211 Name.startswith("avx512.mask.movddup") || // Added in 3.9
212 Name.startswith("avx512.mask.movshdup") || // Added in 3.9
213 Name.startswith("avx512.mask.movsldup") || // Added in 3.9
214 Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
215 Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
216 Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
217 Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
218 Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
219 Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
220 Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
221 Name.startswith("avx512.mask.punpckl") || // Added in 3.9
222 Name.startswith("avx512.mask.punpckh") || // Added in 3.9
223 Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
224 Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
225 Name.startswith("avx512.mask.pand.") || // Added in 3.9
226 Name.startswith("avx512.mask.pandn.") || // Added in 3.9
227 Name.startswith("avx512.mask.por.") || // Added in 3.9
228 Name.startswith("avx512.mask.pxor.") || // Added in 3.9
229 Name.startswith("avx512.mask.and.") || // Added in 3.9
230 Name.startswith("avx512.mask.andn.") || // Added in 3.9
231 Name.startswith("avx512.mask.or.") || // Added in 3.9
232 Name.startswith("avx512.mask.xor.") || // Added in 3.9
233 Name.startswith("avx512.mask.padd.") || // Added in 4.0
234 Name.startswith("avx512.mask.psub.") || // Added in 4.0
235 Name.startswith("avx512.mask.pmull.") || // Added in 4.0
236 Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
237 Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
238 Name.startswith("avx512.mask.cvtudq2ps.") || // Added in 7.0 updated 9.0
239 Name.startswith("avx512.mask.cvtqq2pd.") || // Added in 7.0 updated 9.0
240 Name.startswith("avx512.mask.cvtuqq2pd.") || // Added in 7.0 updated 9.0
241 Name.startswith("avx512.mask.cvtdq2ps.") || // Added in 7.0 updated 9.0
242 Name == "avx512.mask.vcvtph2ps.128" || // Added in 11.0
243 Name == "avx512.mask.vcvtph2ps.256" || // Added in 11.0
244 Name == "avx512.mask.cvtqq2ps.256" || // Added in 9.0
245 Name == "avx512.mask.cvtqq2ps.512" || // Added in 9.0
246 Name == "avx512.mask.cvtuqq2ps.256" || // Added in 9.0
247 Name == "avx512.mask.cvtuqq2ps.512" || // Added in 9.0
248 Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
249 Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
250 Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
251 Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
252 Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
253 Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
254 Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
255 Name == "avx512.cvtusi2sd" || // Added in 7.0
256 Name.startswith("avx512.mask.permvar.") || // Added in 7.0
257 Name == "sse2.pmulu.dq" || // Added in 7.0
258 Name == "sse41.pmuldq" || // Added in 7.0
259 Name == "avx2.pmulu.dq" || // Added in 7.0
260 Name == "avx2.pmul.dq" || // Added in 7.0
261 Name == "avx512.pmulu.dq.512" || // Added in 7.0
262 Name == "avx512.pmul.dq.512" || // Added in 7.0
263 Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
264 Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
265 Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
266 Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
267 Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
268 Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
269 Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
270 Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
271 Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
272 Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
273 Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
274 Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
275 Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
276 Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
277 Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
278 Name.startswith("avx512.cmp.p") || // Added in 12.0
279 Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
280 Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
281 Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
282 Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
283 Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
284 Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
285 Name.startswith("avx512.mask.psll.d") || // Added in 4.0
286 Name.startswith("avx512.mask.psll.q") || // Added in 4.0
287 Name.startswith("avx512.mask.psll.w") || // Added in 4.0
288 Name.startswith("avx512.mask.psra.d") || // Added in 4.0
289 Name.startswith("avx512.mask.psra.q") || // Added in 4.0
290 Name.startswith("avx512.mask.psra.w") || // Added in 4.0
291 Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
292 Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
293 Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
294 Name.startswith("avx512.mask.pslli") || // Added in 4.0
295 Name.startswith("avx512.mask.psrai") || // Added in 4.0
296 Name.startswith("avx512.mask.psrli") || // Added in 4.0
297 Name.startswith("avx512.mask.psllv") || // Added in 4.0
298 Name.startswith("avx512.mask.psrav") || // Added in 4.0
299 Name.startswith("avx512.mask.psrlv") || // Added in 4.0
300 Name.startswith("sse41.pmovsx") || // Added in 3.8
301 Name.startswith("sse41.pmovzx") || // Added in 3.9
302 Name.startswith("avx2.pmovsx") || // Added in 3.9
303 Name.startswith("avx2.pmovzx") || // Added in 3.9
304 Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
305 Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
306 Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
307 Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
308 Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
309 Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
310 Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
311 Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
312 Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
313 Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
314 Name.startswith("avx512.mask.vpdpbusd.") || // Added in 7.0
315 Name.startswith("avx512.maskz.vpdpbusd.") || // Added in 7.0
316 Name.startswith("avx512.mask.vpdpbusds.") || // Added in 7.0
317 Name.startswith("avx512.maskz.vpdpbusds.") || // Added in 7.0
318 Name.startswith("avx512.mask.vpdpwssd.") || // Added in 7.0
319 Name.startswith("avx512.maskz.vpdpwssd.") || // Added in 7.0
320 Name.startswith("avx512.mask.vpdpwssds.") || // Added in 7.0
321 Name.startswith("avx512.maskz.vpdpwssds.") || // Added in 7.0
322 Name.startswith("avx512.mask.dbpsadbw.") || // Added in 7.0
323 Name.startswith("avx512.mask.vpshld.") || // Added in 7.0
324 Name.startswith("avx512.mask.vpshrd.") || // Added in 7.0
325 Name.startswith("avx512.mask.vpshldv.") || // Added in 8.0
326 Name.startswith("avx512.mask.vpshrdv.") || // Added in 8.0
327 Name.startswith("avx512.maskz.vpshldv.") || // Added in 8.0
328 Name.startswith("avx512.maskz.vpshrdv.") || // Added in 8.0
329 Name.startswith("avx512.vpshld.") || // Added in 8.0
330 Name.startswith("avx512.vpshrd.") || // Added in 8.0
331 Name.startswith("avx512.mask.add.p") || // Added in 7.0. 128/256 in 4.0
332 Name.startswith("avx512.mask.sub.p") || // Added in 7.0. 128/256 in 4.0
333 Name.startswith("avx512.mask.mul.p") || // Added in 7.0. 128/256 in 4.0
334 Name.startswith("avx512.mask.div.p") || // Added in 7.0. 128/256 in 4.0
335 Name.startswith("avx512.mask.max.p") || // Added in 7.0. 128/256 in 5.0
336 Name.startswith("avx512.mask.min.p") || // Added in 7.0. 128/256 in 5.0
337 Name.startswith("avx512.mask.fpclass.p") || // Added in 7.0
338 Name.startswith("avx512.mask.vpshufbitqmb.") || // Added in 8.0
339 Name.startswith("avx512.mask.pmultishift.qb.") || // Added in 8.0
340 Name.startswith("avx512.mask.conflict.") || // Added in 9.0
341 Name == "avx512.mask.pmov.qd.256" || // Added in 9.0
342 Name == "avx512.mask.pmov.qd.512" || // Added in 9.0
343 Name == "avx512.mask.pmov.wb.256" || // Added in 9.0
344 Name == "avx512.mask.pmov.wb.512" || // Added in 9.0
345 Name == "sse.cvtsi2ss" || // Added in 7.0
346 Name == "sse.cvtsi642ss" || // Added in 7.0
347 Name == "sse2.cvtsi2sd" || // Added in 7.0
348 Name == "sse2.cvtsi642sd" || // Added in 7.0
349 Name == "sse2.cvtss2sd" || // Added in 7.0
350 Name == "sse2.cvtdq2pd" || // Added in 3.9
351 Name == "sse2.cvtdq2ps" || // Added in 7.0
352 Name == "sse2.cvtps2pd" || // Added in 3.9
353 Name == "avx.cvtdq2.pd.256" || // Added in 3.9
354 Name == "avx.cvtdq2.ps.256" || // Added in 7.0
355 Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
356 Name.startswith("vcvtph2ps.") || // Added in 11.0
357 Name.startswith("avx.vinsertf128.") || // Added in 3.7
358 Name == "avx2.vinserti128" || // Added in 3.7
359 Name.startswith("avx512.mask.insert") || // Added in 4.0
360 Name.startswith("avx.vextractf128.") || // Added in 3.7
361 Name == "avx2.vextracti128" || // Added in 3.7
362 Name.startswith("avx512.mask.vextract") || // Added in 4.0
363 Name.startswith("sse4a.movnt.") || // Added in 3.9
364 Name.startswith("avx.movnt.") || // Added in 3.2
365 Name.startswith("avx512.storent.") || // Added in 3.9
366 Name == "sse41.movntdqa" || // Added in 5.0
367 Name == "avx2.movntdqa" || // Added in 5.0
368 Name == "avx512.movntdqa" || // Added in 5.0
369 Name == "sse2.storel.dq" || // Added in 3.9
370 Name.startswith("sse.storeu.") || // Added in 3.9
371 Name.startswith("sse2.storeu.") || // Added in 3.9
372 Name.startswith("avx.storeu.") || // Added in 3.9
373 Name.startswith("avx512.mask.storeu.") || // Added in 3.9
374 Name.startswith("avx512.mask.store.p") || // Added in 3.9
375 Name.startswith("avx512.mask.store.b.") || // Added in 3.9
376 Name.startswith("avx512.mask.store.w.") || // Added in 3.9
377 Name.startswith("avx512.mask.store.d.") || // Added in 3.9
378 Name.startswith("avx512.mask.store.q.") || // Added in 3.9
379 Name == "avx512.mask.store.ss" || // Added in 7.0
380 Name.startswith("avx512.mask.loadu.") || // Added in 3.9
381 Name.startswith("avx512.mask.load.") || // Added in 3.9
382 Name.startswith("avx512.mask.expand.load.") || // Added in 7.0
383 Name.startswith("avx512.mask.compress.store.") || // Added in 7.0
384 Name.startswith("avx512.mask.expand.b") || // Added in 9.0
385 Name.startswith("avx512.mask.expand.w") || // Added in 9.0
386 Name.startswith("avx512.mask.expand.d") || // Added in 9.0
387 Name.startswith("avx512.mask.expand.q") || // Added in 9.0
388 Name.startswith("avx512.mask.expand.p") || // Added in 9.0
389 Name.startswith("avx512.mask.compress.b") || // Added in 9.0
390 Name.startswith("avx512.mask.compress.w") || // Added in 9.0
391 Name.startswith("avx512.mask.compress.d") || // Added in 9.0
392 Name.startswith("avx512.mask.compress.q") || // Added in 9.0
393 Name.startswith("avx512.mask.compress.p") || // Added in 9.0
394 Name == "sse42.crc32.64.8" || // Added in 3.4
395 Name.startswith("avx.vbroadcast.s") || // Added in 3.5
396 Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
397 Name.startswith("avx512.mask.palignr.") || // Added in 3.9
398 Name.startswith("avx512.mask.valign.") || // Added in 4.0
399 Name.startswith("sse2.psll.dq") || // Added in 3.7
400 Name.startswith("sse2.psrl.dq") || // Added in 3.7
401 Name.startswith("avx2.psll.dq") || // Added in 3.7
402 Name.startswith("avx2.psrl.dq") || // Added in 3.7
403 Name.startswith("avx512.psll.dq") || // Added in 3.9
404 Name.startswith("avx512.psrl.dq") || // Added in 3.9
405 Name == "sse41.pblendw" || // Added in 3.7
406 Name.startswith("sse41.blendp") || // Added in 3.7
407 Name.startswith("avx.blend.p") || // Added in 3.7
408 Name == "avx2.pblendw" || // Added in 3.7
409 Name.startswith("avx2.pblendd.") || // Added in 3.7
410 Name.startswith("avx.vbroadcastf128") || // Added in 4.0
411 Name == "avx2.vbroadcasti128" || // Added in 3.7
412 Name.startswith("avx512.mask.broadcastf32x4.") || // Added in 6.0
413 Name.startswith("avx512.mask.broadcastf64x2.") || // Added in 6.0
414 Name.startswith("avx512.mask.broadcastf32x8.") || // Added in 6.0
415 Name.startswith("avx512.mask.broadcastf64x4.") || // Added in 6.0
416 Name.startswith("avx512.mask.broadcasti32x4.") || // Added in 6.0
417 Name.startswith("avx512.mask.broadcasti64x2.") || // Added in 6.0
418 Name.startswith("avx512.mask.broadcasti32x8.") || // Added in 6.0
419 Name.startswith("avx512.mask.broadcasti64x4.") || // Added in 6.0
420 Name == "xop.vpcmov" || // Added in 3.8
421 Name == "xop.vpcmov.256" || // Added in 5.0
422 Name.startswith("avx512.mask.move.s") || // Added in 4.0
423 Name.startswith("avx512.cvtmask2") || // Added in 5.0
424 Name.startswith("xop.vpcom") || // Added in 3.2, Updated in 9.0
425 Name.startswith("xop.vprot") || // Added in 8.0
426 Name.startswith("avx512.prol") || // Added in 8.0
427 Name.startswith("avx512.pror") || // Added in 8.0
428 Name.startswith("avx512.mask.prorv.") || // Added in 8.0
429 Name.startswith("avx512.mask.pror.") || // Added in 8.0
430 Name.startswith("avx512.mask.prolv.") || // Added in 8.0
431 Name.startswith("avx512.mask.prol.") || // Added in 8.0
432 Name.startswith("avx512.ptestm") || //Added in 6.0
433 Name.startswith("avx512.ptestnm") || //Added in 6.0
434 Name.startswith("avx512.mask.pavg")) // Added in 6.0
435 return true;
436
437 return false;
438 }
439
UpgradeX86IntrinsicFunction(Function * F,StringRef Name,Function * & NewFn)440 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
441 Function *&NewFn) {
442 // Only handle intrinsics that start with "x86.".
443 if (!Name.startswith("x86."))
444 return false;
445 // Remove "x86." prefix.
446 Name = Name.substr(4);
447
448 if (ShouldUpgradeX86Intrinsic(F, Name)) {
449 NewFn = nullptr;
450 return true;
451 }
452
453 if (Name == "rdtscp") { // Added in 8.0
454 // If this intrinsic has 0 operands, it's the new version.
455 if (F->getFunctionType()->getNumParams() == 0)
456 return false;
457
458 rename(F);
459 NewFn = Intrinsic::getDeclaration(F->getParent(),
460 Intrinsic::x86_rdtscp);
461 return true;
462 }
463
464 // SSE4.1 ptest functions may have an old signature.
465 if (Name.startswith("sse41.ptest")) { // Added in 3.2
466 if (Name.substr(11) == "c")
467 return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
468 if (Name.substr(11) == "z")
469 return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
470 if (Name.substr(11) == "nzc")
471 return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
472 }
473 // Several blend and other instructions with masks used the wrong number of
474 // bits.
475 if (Name == "sse41.insertps") // Added in 3.6
476 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
477 NewFn);
478 if (Name == "sse41.dppd") // Added in 3.6
479 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
480 NewFn);
481 if (Name == "sse41.dpps") // Added in 3.6
482 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
483 NewFn);
484 if (Name == "sse41.mpsadbw") // Added in 3.6
485 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
486 NewFn);
487 if (Name == "avx.dp.ps.256") // Added in 3.6
488 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
489 NewFn);
490 if (Name == "avx2.mpsadbw") // Added in 3.6
491 return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
492 NewFn);
493 if (Name == "avx512.mask.cmp.pd.128") // Added in 7.0
494 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_128,
495 NewFn);
496 if (Name == "avx512.mask.cmp.pd.256") // Added in 7.0
497 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_256,
498 NewFn);
499 if (Name == "avx512.mask.cmp.pd.512") // Added in 7.0
500 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
501 NewFn);
502 if (Name == "avx512.mask.cmp.ps.128") // Added in 7.0
503 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_128,
504 NewFn);
505 if (Name == "avx512.mask.cmp.ps.256") // Added in 7.0
506 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_256,
507 NewFn);
508 if (Name == "avx512.mask.cmp.ps.512") // Added in 7.0
509 return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
510 NewFn);
511 if (Name == "avx512bf16.cvtne2ps2bf16.128") // Added in 9.0
512 return UpgradeX86BF16Intrinsic(
513 F, Intrinsic::x86_avx512bf16_cvtne2ps2bf16_128, NewFn);
514 if (Name == "avx512bf16.cvtne2ps2bf16.256") // Added in 9.0
515 return UpgradeX86BF16Intrinsic(
516 F, Intrinsic::x86_avx512bf16_cvtne2ps2bf16_256, NewFn);
517 if (Name == "avx512bf16.cvtne2ps2bf16.512") // Added in 9.0
518 return UpgradeX86BF16Intrinsic(
519 F, Intrinsic::x86_avx512bf16_cvtne2ps2bf16_512, NewFn);
520 if (Name == "avx512bf16.mask.cvtneps2bf16.128") // Added in 9.0
521 return UpgradeX86BF16Intrinsic(
522 F, Intrinsic::x86_avx512bf16_mask_cvtneps2bf16_128, NewFn);
523 if (Name == "avx512bf16.cvtneps2bf16.256") // Added in 9.0
524 return UpgradeX86BF16Intrinsic(
525 F, Intrinsic::x86_avx512bf16_cvtneps2bf16_256, NewFn);
526 if (Name == "avx512bf16.cvtneps2bf16.512") // Added in 9.0
527 return UpgradeX86BF16Intrinsic(
528 F, Intrinsic::x86_avx512bf16_cvtneps2bf16_512, NewFn);
529 if (Name == "avx512bf16.dpbf16ps.128") // Added in 9.0
530 return UpgradeX86BF16DPIntrinsic(
531 F, Intrinsic::x86_avx512bf16_dpbf16ps_128, NewFn);
532 if (Name == "avx512bf16.dpbf16ps.256") // Added in 9.0
533 return UpgradeX86BF16DPIntrinsic(
534 F, Intrinsic::x86_avx512bf16_dpbf16ps_256, NewFn);
535 if (Name == "avx512bf16.dpbf16ps.512") // Added in 9.0
536 return UpgradeX86BF16DPIntrinsic(
537 F, Intrinsic::x86_avx512bf16_dpbf16ps_512, NewFn);
538
539 // frcz.ss/sd may need to have an argument dropped. Added in 3.2
540 if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
541 rename(F);
542 NewFn = Intrinsic::getDeclaration(F->getParent(),
543 Intrinsic::x86_xop_vfrcz_ss);
544 return true;
545 }
546 if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
547 rename(F);
548 NewFn = Intrinsic::getDeclaration(F->getParent(),
549 Intrinsic::x86_xop_vfrcz_sd);
550 return true;
551 }
552 // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
553 if (Name.startswith("xop.vpermil2")) { // Added in 3.9
554 auto Idx = F->getFunctionType()->getParamType(2);
555 if (Idx->isFPOrFPVectorTy()) {
556 rename(F);
557 unsigned IdxSize = Idx->getPrimitiveSizeInBits();
558 unsigned EltSize = Idx->getScalarSizeInBits();
559 Intrinsic::ID Permil2ID;
560 if (EltSize == 64 && IdxSize == 128)
561 Permil2ID = Intrinsic::x86_xop_vpermil2pd;
562 else if (EltSize == 32 && IdxSize == 128)
563 Permil2ID = Intrinsic::x86_xop_vpermil2ps;
564 else if (EltSize == 64 && IdxSize == 256)
565 Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
566 else
567 Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
568 NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
569 return true;
570 }
571 }
572
573 if (Name == "seh.recoverfp") {
574 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_recoverfp);
575 return true;
576 }
577
578 return false;
579 }
580
UpgradeIntrinsicFunction1(Function * F,Function * & NewFn)581 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
582 assert(F && "Illegal to upgrade a non-existent Function.");
583
584 // Quickly eliminate it, if it's not a candidate.
585 StringRef Name = F->getName();
586 if (Name.size() <= 7 || !Name.startswith("llvm."))
587 return false;
588 Name = Name.substr(5); // Strip off "llvm."
589
590 switch (Name[0]) {
591 default: break;
592 case 'a': {
593 if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
594 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
595 F->arg_begin()->getType());
596 return true;
597 }
598 if (Name.startswith("aarch64.neon.frintn")) {
599 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::roundeven,
600 F->arg_begin()->getType());
601 return true;
602 }
603 if (Name.startswith("aarch64.neon.rbit")) {
604 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
605 F->arg_begin()->getType());
606 return true;
607 }
608 if (Name == "aarch64.sve.bfdot.lane") {
609 NewFn = Intrinsic::getDeclaration(F->getParent(),
610 Intrinsic::aarch64_sve_bfdot_lane_v2);
611 return true;
612 }
613 if (Name == "aarch64.sve.bfmlalb.lane") {
614 NewFn = Intrinsic::getDeclaration(F->getParent(),
615 Intrinsic::aarch64_sve_bfmlalb_lane_v2);
616 return true;
617 }
618 if (Name == "aarch64.sve.bfmlalt.lane") {
619 NewFn = Intrinsic::getDeclaration(F->getParent(),
620 Intrinsic::aarch64_sve_bfmlalt_lane_v2);
621 return true;
622 }
623 static const Regex LdRegex("^aarch64\\.sve\\.ld[234](.nxv[a-z0-9]+|$)");
624 if (LdRegex.match(Name)) {
625 Type *ScalarTy =
626 dyn_cast<VectorType>(F->getReturnType())->getElementType();
627 ElementCount EC =
628 dyn_cast<VectorType>(F->arg_begin()->getType())->getElementCount();
629 Type *Ty = VectorType::get(ScalarTy, EC);
630 Intrinsic::ID ID =
631 StringSwitch<Intrinsic::ID>(Name)
632 .StartsWith("aarch64.sve.ld2", Intrinsic::aarch64_sve_ld2_sret)
633 .StartsWith("aarch64.sve.ld3", Intrinsic::aarch64_sve_ld3_sret)
634 .StartsWith("aarch64.sve.ld4", Intrinsic::aarch64_sve_ld4_sret)
635 .Default(Intrinsic::not_intrinsic);
636 NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Ty);
637 return true;
638 }
639 if (Name.startswith("aarch64.sve.tuple.get")) {
640 Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
641 NewFn = Intrinsic::getDeclaration(F->getParent(),
642 Intrinsic::vector_extract, Tys);
643 return true;
644 }
645 if (Name.startswith("aarch64.sve.tuple.set")) {
646 auto Args = F->getFunctionType()->params();
647 Type *Tys[] = {Args[0], Args[2], Args[1]};
648 NewFn = Intrinsic::getDeclaration(F->getParent(),
649 Intrinsic::vector_insert, Tys);
650 return true;
651 }
652 static const Regex CreateTupleRegex(
653 "^aarch64\\.sve\\.tuple\\.create[234](.nxv[a-z0-9]+|$)");
654 if (CreateTupleRegex.match(Name)) {
655 auto Args = F->getFunctionType()->params();
656 Type *Tys[] = {F->getReturnType(), Args[1]};
657 NewFn = Intrinsic::getDeclaration(F->getParent(),
658 Intrinsic::vector_insert, Tys);
659 return true;
660 }
661 if (Name.startswith("arm.neon.vclz")) {
662 Type* args[2] = {
663 F->arg_begin()->getType(),
664 Type::getInt1Ty(F->getContext())
665 };
666 // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
667 // the end of the name. Change name from llvm.arm.neon.vclz.* to
668 // llvm.ctlz.*
669 FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
670 NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
671 "llvm.ctlz." + Name.substr(14), F->getParent());
672 return true;
673 }
674 if (Name.startswith("arm.neon.vcnt")) {
675 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
676 F->arg_begin()->getType());
677 return true;
678 }
679 static const Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
680 if (vstRegex.match(Name)) {
681 static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
682 Intrinsic::arm_neon_vst2,
683 Intrinsic::arm_neon_vst3,
684 Intrinsic::arm_neon_vst4};
685
686 static const Intrinsic::ID StoreLaneInts[] = {
687 Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
688 Intrinsic::arm_neon_vst4lane
689 };
690
691 auto fArgs = F->getFunctionType()->params();
692 Type *Tys[] = {fArgs[0], fArgs[1]};
693 if (!Name.contains("lane"))
694 NewFn = Intrinsic::getDeclaration(F->getParent(),
695 StoreInts[fArgs.size() - 3], Tys);
696 else
697 NewFn = Intrinsic::getDeclaration(F->getParent(),
698 StoreLaneInts[fArgs.size() - 5], Tys);
699 return true;
700 }
701 if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
702 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
703 return true;
704 }
705 if (Name.startswith("arm.neon.vqadds.")) {
706 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::sadd_sat,
707 F->arg_begin()->getType());
708 return true;
709 }
710 if (Name.startswith("arm.neon.vqaddu.")) {
711 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::uadd_sat,
712 F->arg_begin()->getType());
713 return true;
714 }
715 if (Name.startswith("arm.neon.vqsubs.")) {
716 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ssub_sat,
717 F->arg_begin()->getType());
718 return true;
719 }
720 if (Name.startswith("arm.neon.vqsubu.")) {
721 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::usub_sat,
722 F->arg_begin()->getType());
723 return true;
724 }
725 if (Name.startswith("aarch64.neon.addp")) {
726 if (F->arg_size() != 2)
727 break; // Invalid IR.
728 VectorType *Ty = dyn_cast<VectorType>(F->getReturnType());
729 if (Ty && Ty->getElementType()->isFloatingPointTy()) {
730 NewFn = Intrinsic::getDeclaration(F->getParent(),
731 Intrinsic::aarch64_neon_faddp, Ty);
732 return true;
733 }
734 }
735
736 // Changed in 12.0: bfdot accept v4bf16 and v8bf16 instead of v8i8 and v16i8
737 // respectively
738 if ((Name.startswith("arm.neon.bfdot.") ||
739 Name.startswith("aarch64.neon.bfdot.")) &&
740 Name.endswith("i8")) {
741 Intrinsic::ID IID =
742 StringSwitch<Intrinsic::ID>(Name)
743 .Cases("arm.neon.bfdot.v2f32.v8i8",
744 "arm.neon.bfdot.v4f32.v16i8",
745 Intrinsic::arm_neon_bfdot)
746 .Cases("aarch64.neon.bfdot.v2f32.v8i8",
747 "aarch64.neon.bfdot.v4f32.v16i8",
748 Intrinsic::aarch64_neon_bfdot)
749 .Default(Intrinsic::not_intrinsic);
750 if (IID == Intrinsic::not_intrinsic)
751 break;
752
753 size_t OperandWidth = F->getReturnType()->getPrimitiveSizeInBits();
754 assert((OperandWidth == 64 || OperandWidth == 128) &&
755 "Unexpected operand width");
756 LLVMContext &Ctx = F->getParent()->getContext();
757 std::array<Type *, 2> Tys {{
758 F->getReturnType(),
759 FixedVectorType::get(Type::getBFloatTy(Ctx), OperandWidth / 16)
760 }};
761 NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
762 return true;
763 }
764
765 // Changed in 12.0: bfmmla, bfmlalb and bfmlalt are not polymorphic anymore
766 // and accept v8bf16 instead of v16i8
767 if ((Name.startswith("arm.neon.bfm") ||
768 Name.startswith("aarch64.neon.bfm")) &&
769 Name.endswith(".v4f32.v16i8")) {
770 Intrinsic::ID IID =
771 StringSwitch<Intrinsic::ID>(Name)
772 .Case("arm.neon.bfmmla.v4f32.v16i8",
773 Intrinsic::arm_neon_bfmmla)
774 .Case("arm.neon.bfmlalb.v4f32.v16i8",
775 Intrinsic::arm_neon_bfmlalb)
776 .Case("arm.neon.bfmlalt.v4f32.v16i8",
777 Intrinsic::arm_neon_bfmlalt)
778 .Case("aarch64.neon.bfmmla.v4f32.v16i8",
779 Intrinsic::aarch64_neon_bfmmla)
780 .Case("aarch64.neon.bfmlalb.v4f32.v16i8",
781 Intrinsic::aarch64_neon_bfmlalb)
782 .Case("aarch64.neon.bfmlalt.v4f32.v16i8",
783 Intrinsic::aarch64_neon_bfmlalt)
784 .Default(Intrinsic::not_intrinsic);
785 if (IID == Intrinsic::not_intrinsic)
786 break;
787
788 std::array<Type *, 0> Tys;
789 NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
790 return true;
791 }
792
793 if (Name == "arm.mve.vctp64" &&
794 cast<FixedVectorType>(F->getReturnType())->getNumElements() == 4) {
795 // A vctp64 returning a v4i1 is converted to return a v2i1. Rename the
796 // function and deal with it below in UpgradeIntrinsicCall.
797 rename(F);
798 return true;
799 }
800 // These too are changed to accept a v2i1 insteead of the old v4i1.
801 if (Name == "arm.mve.mull.int.predicated.v2i64.v4i32.v4i1" ||
802 Name == "arm.mve.vqdmull.predicated.v2i64.v4i32.v4i1" ||
803 Name == "arm.mve.vldr.gather.base.predicated.v2i64.v2i64.v4i1" ||
804 Name == "arm.mve.vldr.gather.base.wb.predicated.v2i64.v2i64.v4i1" ||
805 Name == "arm.mve.vldr.gather.offset.predicated.v2i64.p0i64.v2i64.v4i1" ||
806 Name == "arm.mve.vstr.scatter.base.predicated.v2i64.v2i64.v4i1" ||
807 Name == "arm.mve.vstr.scatter.base.wb.predicated.v2i64.v2i64.v4i1" ||
808 Name == "arm.mve.vstr.scatter.offset.predicated.p0i64.v2i64.v2i64.v4i1" ||
809 Name == "arm.cde.vcx1q.predicated.v2i64.v4i1" ||
810 Name == "arm.cde.vcx1qa.predicated.v2i64.v4i1" ||
811 Name == "arm.cde.vcx2q.predicated.v2i64.v4i1" ||
812 Name == "arm.cde.vcx2qa.predicated.v2i64.v4i1" ||
813 Name == "arm.cde.vcx3q.predicated.v2i64.v4i1" ||
814 Name == "arm.cde.vcx3qa.predicated.v2i64.v4i1")
815 return true;
816
817 if (Name == "amdgcn.alignbit") {
818 // Target specific intrinsic became redundant
819 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::fshr,
820 {F->getReturnType()});
821 return true;
822 }
823
824 break;
825 }
826
827 case 'c': {
828 if (Name.startswith("ctlz.") && F->arg_size() == 1) {
829 rename(F);
830 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
831 F->arg_begin()->getType());
832 return true;
833 }
834 if (Name.startswith("cttz.") && F->arg_size() == 1) {
835 rename(F);
836 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
837 F->arg_begin()->getType());
838 return true;
839 }
840 break;
841 }
842 case 'd': {
843 if (Name == "dbg.value" && F->arg_size() == 4) {
844 rename(F);
845 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
846 return true;
847 }
848 break;
849 }
850 case 'e': {
851 if (Name.startswith("experimental.vector.extract.")) {
852 rename(F);
853 Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
854 NewFn = Intrinsic::getDeclaration(F->getParent(),
855 Intrinsic::vector_extract, Tys);
856 return true;
857 }
858
859 if (Name.startswith("experimental.vector.insert.")) {
860 rename(F);
861 auto Args = F->getFunctionType()->params();
862 Type *Tys[] = {Args[0], Args[1]};
863 NewFn = Intrinsic::getDeclaration(F->getParent(),
864 Intrinsic::vector_insert, Tys);
865 return true;
866 }
867
868 SmallVector<StringRef, 2> Groups;
869 static const Regex R("^experimental.vector.reduce.([a-z]+)\\.[a-z][0-9]+");
870 if (R.match(Name, &Groups)) {
871 Intrinsic::ID ID;
872 ID = StringSwitch<Intrinsic::ID>(Groups[1])
873 .Case("add", Intrinsic::vector_reduce_add)
874 .Case("mul", Intrinsic::vector_reduce_mul)
875 .Case("and", Intrinsic::vector_reduce_and)
876 .Case("or", Intrinsic::vector_reduce_or)
877 .Case("xor", Intrinsic::vector_reduce_xor)
878 .Case("smax", Intrinsic::vector_reduce_smax)
879 .Case("smin", Intrinsic::vector_reduce_smin)
880 .Case("umax", Intrinsic::vector_reduce_umax)
881 .Case("umin", Intrinsic::vector_reduce_umin)
882 .Case("fmax", Intrinsic::vector_reduce_fmax)
883 .Case("fmin", Intrinsic::vector_reduce_fmin)
884 .Default(Intrinsic::not_intrinsic);
885 if (ID != Intrinsic::not_intrinsic) {
886 rename(F);
887 auto Args = F->getFunctionType()->params();
888 NewFn = Intrinsic::getDeclaration(F->getParent(), ID, {Args[0]});
889 return true;
890 }
891 }
892 static const Regex R2(
893 "^experimental.vector.reduce.v2.([a-z]+)\\.[fi][0-9]+");
894 Groups.clear();
895 if (R2.match(Name, &Groups)) {
896 Intrinsic::ID ID = Intrinsic::not_intrinsic;
897 if (Groups[1] == "fadd")
898 ID = Intrinsic::vector_reduce_fadd;
899 if (Groups[1] == "fmul")
900 ID = Intrinsic::vector_reduce_fmul;
901 if (ID != Intrinsic::not_intrinsic) {
902 rename(F);
903 auto Args = F->getFunctionType()->params();
904 Type *Tys[] = {Args[1]};
905 NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
906 return true;
907 }
908 }
909 break;
910 }
911 case 'f':
912 if (Name.startswith("flt.rounds")) {
913 rename(F);
914 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::get_rounding);
915 return true;
916 }
917 break;
918 case 'i':
919 case 'l': {
920 bool IsLifetimeStart = Name.startswith("lifetime.start");
921 if (IsLifetimeStart || Name.startswith("invariant.start")) {
922 Intrinsic::ID ID = IsLifetimeStart ?
923 Intrinsic::lifetime_start : Intrinsic::invariant_start;
924 auto Args = F->getFunctionType()->params();
925 Type* ObjectPtr[1] = {Args[1]};
926 if (F->getName() != Intrinsic::getName(ID, ObjectPtr, F->getParent())) {
927 rename(F);
928 NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
929 return true;
930 }
931 }
932
933 bool IsLifetimeEnd = Name.startswith("lifetime.end");
934 if (IsLifetimeEnd || Name.startswith("invariant.end")) {
935 Intrinsic::ID ID = IsLifetimeEnd ?
936 Intrinsic::lifetime_end : Intrinsic::invariant_end;
937
938 auto Args = F->getFunctionType()->params();
939 Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
940 if (F->getName() != Intrinsic::getName(ID, ObjectPtr, F->getParent())) {
941 rename(F);
942 NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
943 return true;
944 }
945 }
946 if (Name.startswith("invariant.group.barrier")) {
947 // Rename invariant.group.barrier to launder.invariant.group
948 auto Args = F->getFunctionType()->params();
949 Type* ObjectPtr[1] = {Args[0]};
950 rename(F);
951 NewFn = Intrinsic::getDeclaration(F->getParent(),
952 Intrinsic::launder_invariant_group, ObjectPtr);
953 return true;
954
955 }
956
957 break;
958 }
959 case 'm': {
960 if (Name.startswith("masked.load.")) {
961 Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
962 if (F->getName() !=
963 Intrinsic::getName(Intrinsic::masked_load, Tys, F->getParent())) {
964 rename(F);
965 NewFn = Intrinsic::getDeclaration(F->getParent(),
966 Intrinsic::masked_load,
967 Tys);
968 return true;
969 }
970 }
971 if (Name.startswith("masked.store.")) {
972 auto Args = F->getFunctionType()->params();
973 Type *Tys[] = { Args[0], Args[1] };
974 if (F->getName() !=
975 Intrinsic::getName(Intrinsic::masked_store, Tys, F->getParent())) {
976 rename(F);
977 NewFn = Intrinsic::getDeclaration(F->getParent(),
978 Intrinsic::masked_store,
979 Tys);
980 return true;
981 }
982 }
983 // Renaming gather/scatter intrinsics with no address space overloading
984 // to the new overload which includes an address space
985 if (Name.startswith("masked.gather.")) {
986 Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
987 if (F->getName() !=
988 Intrinsic::getName(Intrinsic::masked_gather, Tys, F->getParent())) {
989 rename(F);
990 NewFn = Intrinsic::getDeclaration(F->getParent(),
991 Intrinsic::masked_gather, Tys);
992 return true;
993 }
994 }
995 if (Name.startswith("masked.scatter.")) {
996 auto Args = F->getFunctionType()->params();
997 Type *Tys[] = {Args[0], Args[1]};
998 if (F->getName() !=
999 Intrinsic::getName(Intrinsic::masked_scatter, Tys, F->getParent())) {
1000 rename(F);
1001 NewFn = Intrinsic::getDeclaration(F->getParent(),
1002 Intrinsic::masked_scatter, Tys);
1003 return true;
1004 }
1005 }
1006 // Updating the memory intrinsics (memcpy/memmove/memset) that have an
1007 // alignment parameter to embedding the alignment as an attribute of
1008 // the pointer args.
1009 if (Name.startswith("memcpy.") && F->arg_size() == 5) {
1010 rename(F);
1011 // Get the types of dest, src, and len
1012 ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
1013 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
1014 ParamTypes);
1015 return true;
1016 }
1017 if (Name.startswith("memmove.") && F->arg_size() == 5) {
1018 rename(F);
1019 // Get the types of dest, src, and len
1020 ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
1021 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
1022 ParamTypes);
1023 return true;
1024 }
1025 if (Name.startswith("memset.") && F->arg_size() == 5) {
1026 rename(F);
1027 // Get the types of dest, and len
1028 const auto *FT = F->getFunctionType();
1029 Type *ParamTypes[2] = {
1030 FT->getParamType(0), // Dest
1031 FT->getParamType(2) // len
1032 };
1033 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
1034 ParamTypes);
1035 return true;
1036 }
1037 break;
1038 }
1039 case 'n': {
1040 if (Name.startswith("nvvm.")) {
1041 Name = Name.substr(5);
1042
1043 // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
1044 Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
1045 .Cases("brev32", "brev64", Intrinsic::bitreverse)
1046 .Case("clz.i", Intrinsic::ctlz)
1047 .Case("popc.i", Intrinsic::ctpop)
1048 .Default(Intrinsic::not_intrinsic);
1049 if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
1050 NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
1051 {F->getReturnType()});
1052 return true;
1053 }
1054
1055 // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
1056 // not to an intrinsic alone. We expand them in UpgradeIntrinsicCall.
1057 //
1058 // TODO: We could add lohi.i2d.
1059 bool Expand = StringSwitch<bool>(Name)
1060 .Cases("abs.i", "abs.ll", true)
1061 .Cases("clz.ll", "popc.ll", "h2f", true)
1062 .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
1063 .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
1064 .StartsWith("atomic.load.add.f32.p", true)
1065 .StartsWith("atomic.load.add.f64.p", true)
1066 .Default(false);
1067 if (Expand) {
1068 NewFn = nullptr;
1069 return true;
1070 }
1071 }
1072 break;
1073 }
1074 case 'o':
1075 // We only need to change the name to match the mangling including the
1076 // address space.
1077 if (Name.startswith("objectsize.")) {
1078 Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
1079 if (F->arg_size() == 2 || F->arg_size() == 3 ||
1080 F->getName() !=
1081 Intrinsic::getName(Intrinsic::objectsize, Tys, F->getParent())) {
1082 rename(F);
1083 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
1084 Tys);
1085 return true;
1086 }
1087 }
1088 break;
1089
1090 case 'p':
1091 if (Name == "prefetch") {
1092 // Handle address space overloading.
1093 Type *Tys[] = {F->arg_begin()->getType()};
1094 if (F->getName() !=
1095 Intrinsic::getName(Intrinsic::prefetch, Tys, F->getParent())) {
1096 rename(F);
1097 NewFn =
1098 Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch, Tys);
1099 return true;
1100 }
1101 } else if (Name.startswith("ptr.annotation.") && F->arg_size() == 4) {
1102 rename(F);
1103 NewFn = Intrinsic::getDeclaration(
1104 F->getParent(), Intrinsic::ptr_annotation,
1105 {F->arg_begin()->getType(), F->getArg(1)->getType()});
1106 return true;
1107 }
1108 break;
1109
1110 case 's':
1111 if (Name == "stackprotectorcheck") {
1112 NewFn = nullptr;
1113 return true;
1114 }
1115 break;
1116
1117 case 'v': {
1118 if (Name == "var.annotation" && F->arg_size() == 4) {
1119 rename(F);
1120 NewFn = Intrinsic::getDeclaration(
1121 F->getParent(), Intrinsic::var_annotation,
1122 {{F->arg_begin()->getType(), F->getArg(1)->getType()}});
1123 return true;
1124 }
1125 break;
1126 }
1127
1128 case 'x':
1129 if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
1130 return true;
1131 }
1132
1133 auto *ST = dyn_cast<StructType>(F->getReturnType());
1134 if (ST && (!ST->isLiteral() || ST->isPacked())) {
1135 // Replace return type with literal non-packed struct. Only do this for
1136 // intrinsics declared to return a struct, not for intrinsics with
1137 // overloaded return type, in which case the exact struct type will be
1138 // mangled into the name.
1139 SmallVector<Intrinsic::IITDescriptor> Desc;
1140 Intrinsic::getIntrinsicInfoTableEntries(F->getIntrinsicID(), Desc);
1141 if (Desc.front().Kind == Intrinsic::IITDescriptor::Struct) {
1142 auto *FT = F->getFunctionType();
1143 auto *NewST = StructType::get(ST->getContext(), ST->elements());
1144 auto *NewFT = FunctionType::get(NewST, FT->params(), FT->isVarArg());
1145 std::string Name = F->getName().str();
1146 rename(F);
1147 NewFn = Function::Create(NewFT, F->getLinkage(), F->getAddressSpace(),
1148 Name, F->getParent());
1149
1150 // The new function may also need remangling.
1151 if (auto Result = llvm::Intrinsic::remangleIntrinsicFunction(NewFn))
1152 NewFn = *Result;
1153 return true;
1154 }
1155 }
1156
1157 // Remangle our intrinsic since we upgrade the mangling
1158 auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
1159 if (Result != std::nullopt) {
1160 NewFn = *Result;
1161 return true;
1162 }
1163
1164 // This may not belong here. This function is effectively being overloaded
1165 // to both detect an intrinsic which needs upgrading, and to provide the
1166 // upgraded form of the intrinsic. We should perhaps have two separate
1167 // functions for this.
1168 return false;
1169 }
1170
UpgradeIntrinsicFunction(Function * F,Function * & NewFn)1171 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
1172 NewFn = nullptr;
1173 bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
1174 assert(F != NewFn && "Intrinsic function upgraded to the same function");
1175
1176 // Upgrade intrinsic attributes. This does not change the function.
1177 if (NewFn)
1178 F = NewFn;
1179 if (Intrinsic::ID id = F->getIntrinsicID())
1180 F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
1181 return Upgraded;
1182 }
1183
UpgradeGlobalVariable(GlobalVariable * GV)1184 GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
1185 if (!(GV->hasName() && (GV->getName() == "llvm.global_ctors" ||
1186 GV->getName() == "llvm.global_dtors")) ||
1187 !GV->hasInitializer())
1188 return nullptr;
1189 ArrayType *ATy = dyn_cast<ArrayType>(GV->getValueType());
1190 if (!ATy)
1191 return nullptr;
1192 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1193 if (!STy || STy->getNumElements() != 2)
1194 return nullptr;
1195
1196 LLVMContext &C = GV->getContext();
1197 IRBuilder<> IRB(C);
1198 auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
1199 IRB.getInt8PtrTy());
1200 Constant *Init = GV->getInitializer();
1201 unsigned N = Init->getNumOperands();
1202 std::vector<Constant *> NewCtors(N);
1203 for (unsigned i = 0; i != N; ++i) {
1204 auto Ctor = cast<Constant>(Init->getOperand(i));
1205 NewCtors[i] = ConstantStruct::get(
1206 EltTy, Ctor->getAggregateElement(0u), Ctor->getAggregateElement(1),
1207 Constant::getNullValue(IRB.getInt8PtrTy()));
1208 }
1209 Constant *NewInit = ConstantArray::get(ArrayType::get(EltTy, N), NewCtors);
1210
1211 return new GlobalVariable(NewInit->getType(), false, GV->getLinkage(),
1212 NewInit, GV->getName());
1213 }
1214
1215 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
1216 // to byte shuffles.
UpgradeX86PSLLDQIntrinsics(IRBuilder<> & Builder,Value * Op,unsigned Shift)1217 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
1218 Value *Op, unsigned Shift) {
1219 auto *ResultTy = cast<FixedVectorType>(Op->getType());
1220 unsigned NumElts = ResultTy->getNumElements() * 8;
1221
1222 // Bitcast from a 64-bit element type to a byte element type.
1223 Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
1224 Op = Builder.CreateBitCast(Op, VecTy, "cast");
1225
1226 // We'll be shuffling in zeroes.
1227 Value *Res = Constant::getNullValue(VecTy);
1228
1229 // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1230 // we'll just return the zero vector.
1231 if (Shift < 16) {
1232 int Idxs[64];
1233 // 256/512-bit version is split into 2/4 16-byte lanes.
1234 for (unsigned l = 0; l != NumElts; l += 16)
1235 for (unsigned i = 0; i != 16; ++i) {
1236 unsigned Idx = NumElts + i - Shift;
1237 if (Idx < NumElts)
1238 Idx -= NumElts - 16; // end of lane, switch operand.
1239 Idxs[l + i] = Idx + l;
1240 }
1241
1242 Res = Builder.CreateShuffleVector(Res, Op, ArrayRef(Idxs, NumElts));
1243 }
1244
1245 // Bitcast back to a 64-bit element type.
1246 return Builder.CreateBitCast(Res, ResultTy, "cast");
1247 }
1248
1249 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
1250 // to byte shuffles.
UpgradeX86PSRLDQIntrinsics(IRBuilder<> & Builder,Value * Op,unsigned Shift)1251 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
1252 unsigned Shift) {
1253 auto *ResultTy = cast<FixedVectorType>(Op->getType());
1254 unsigned NumElts = ResultTy->getNumElements() * 8;
1255
1256 // Bitcast from a 64-bit element type to a byte element type.
1257 Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
1258 Op = Builder.CreateBitCast(Op, VecTy, "cast");
1259
1260 // We'll be shuffling in zeroes.
1261 Value *Res = Constant::getNullValue(VecTy);
1262
1263 // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1264 // we'll just return the zero vector.
1265 if (Shift < 16) {
1266 int Idxs[64];
1267 // 256/512-bit version is split into 2/4 16-byte lanes.
1268 for (unsigned l = 0; l != NumElts; l += 16)
1269 for (unsigned i = 0; i != 16; ++i) {
1270 unsigned Idx = i + Shift;
1271 if (Idx >= 16)
1272 Idx += NumElts - 16; // end of lane, switch operand.
1273 Idxs[l + i] = Idx + l;
1274 }
1275
1276 Res = Builder.CreateShuffleVector(Op, Res, ArrayRef(Idxs, NumElts));
1277 }
1278
1279 // Bitcast back to a 64-bit element type.
1280 return Builder.CreateBitCast(Res, ResultTy, "cast");
1281 }
1282
getX86MaskVec(IRBuilder<> & Builder,Value * Mask,unsigned NumElts)1283 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
1284 unsigned NumElts) {
1285 assert(isPowerOf2_32(NumElts) && "Expected power-of-2 mask elements");
1286 llvm::VectorType *MaskTy = FixedVectorType::get(
1287 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
1288 Mask = Builder.CreateBitCast(Mask, MaskTy);
1289
1290 // If we have less than 8 elements (1, 2 or 4), then the starting mask was an
1291 // i8 and we need to extract down to the right number of elements.
1292 if (NumElts <= 4) {
1293 int Indices[4];
1294 for (unsigned i = 0; i != NumElts; ++i)
1295 Indices[i] = i;
1296 Mask = Builder.CreateShuffleVector(Mask, Mask, ArrayRef(Indices, NumElts),
1297 "extract");
1298 }
1299
1300 return Mask;
1301 }
1302
EmitX86Select(IRBuilder<> & Builder,Value * Mask,Value * Op0,Value * Op1)1303 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
1304 Value *Op0, Value *Op1) {
1305 // If the mask is all ones just emit the first operation.
1306 if (const auto *C = dyn_cast<Constant>(Mask))
1307 if (C->isAllOnesValue())
1308 return Op0;
1309
1310 Mask = getX86MaskVec(Builder, Mask,
1311 cast<FixedVectorType>(Op0->getType())->getNumElements());
1312 return Builder.CreateSelect(Mask, Op0, Op1);
1313 }
1314
EmitX86ScalarSelect(IRBuilder<> & Builder,Value * Mask,Value * Op0,Value * Op1)1315 static Value *EmitX86ScalarSelect(IRBuilder<> &Builder, Value *Mask,
1316 Value *Op0, Value *Op1) {
1317 // If the mask is all ones just emit the first operation.
1318 if (const auto *C = dyn_cast<Constant>(Mask))
1319 if (C->isAllOnesValue())
1320 return Op0;
1321
1322 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(),
1323 Mask->getType()->getIntegerBitWidth());
1324 Mask = Builder.CreateBitCast(Mask, MaskTy);
1325 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
1326 return Builder.CreateSelect(Mask, Op0, Op1);
1327 }
1328
1329 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
1330 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
1331 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
UpgradeX86ALIGNIntrinsics(IRBuilder<> & Builder,Value * Op0,Value * Op1,Value * Shift,Value * Passthru,Value * Mask,bool IsVALIGN)1332 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
1333 Value *Op1, Value *Shift,
1334 Value *Passthru, Value *Mask,
1335 bool IsVALIGN) {
1336 unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
1337
1338 unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1339 assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
1340 assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
1341 assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
1342
1343 // Mask the immediate for VALIGN.
1344 if (IsVALIGN)
1345 ShiftVal &= (NumElts - 1);
1346
1347 // If palignr is shifting the pair of vectors more than the size of two
1348 // lanes, emit zero.
1349 if (ShiftVal >= 32)
1350 return llvm::Constant::getNullValue(Op0->getType());
1351
1352 // If palignr is shifting the pair of input vectors more than one lane,
1353 // but less than two lanes, convert to shifting in zeroes.
1354 if (ShiftVal > 16) {
1355 ShiftVal -= 16;
1356 Op1 = Op0;
1357 Op0 = llvm::Constant::getNullValue(Op0->getType());
1358 }
1359
1360 int Indices[64];
1361 // 256-bit palignr operates on 128-bit lanes so we need to handle that
1362 for (unsigned l = 0; l < NumElts; l += 16) {
1363 for (unsigned i = 0; i != 16; ++i) {
1364 unsigned Idx = ShiftVal + i;
1365 if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
1366 Idx += NumElts - 16; // End of lane, switch operand.
1367 Indices[l + i] = Idx + l;
1368 }
1369 }
1370
1371 Value *Align = Builder.CreateShuffleVector(
1372 Op1, Op0, ArrayRef(Indices, NumElts), "palignr");
1373
1374 return EmitX86Select(Builder, Mask, Align, Passthru);
1375 }
1376
UpgradeX86VPERMT2Intrinsics(IRBuilder<> & Builder,CallBase & CI,bool ZeroMask,bool IndexForm)1377 static Value *UpgradeX86VPERMT2Intrinsics(IRBuilder<> &Builder, CallBase &CI,
1378 bool ZeroMask, bool IndexForm) {
1379 Type *Ty = CI.getType();
1380 unsigned VecWidth = Ty->getPrimitiveSizeInBits();
1381 unsigned EltWidth = Ty->getScalarSizeInBits();
1382 bool IsFloat = Ty->isFPOrFPVectorTy();
1383 Intrinsic::ID IID;
1384 if (VecWidth == 128 && EltWidth == 32 && IsFloat)
1385 IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
1386 else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
1387 IID = Intrinsic::x86_avx512_vpermi2var_d_128;
1388 else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
1389 IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
1390 else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
1391 IID = Intrinsic::x86_avx512_vpermi2var_q_128;
1392 else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1393 IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
1394 else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1395 IID = Intrinsic::x86_avx512_vpermi2var_d_256;
1396 else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1397 IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
1398 else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1399 IID = Intrinsic::x86_avx512_vpermi2var_q_256;
1400 else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1401 IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
1402 else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1403 IID = Intrinsic::x86_avx512_vpermi2var_d_512;
1404 else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1405 IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
1406 else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1407 IID = Intrinsic::x86_avx512_vpermi2var_q_512;
1408 else if (VecWidth == 128 && EltWidth == 16)
1409 IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
1410 else if (VecWidth == 256 && EltWidth == 16)
1411 IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
1412 else if (VecWidth == 512 && EltWidth == 16)
1413 IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
1414 else if (VecWidth == 128 && EltWidth == 8)
1415 IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
1416 else if (VecWidth == 256 && EltWidth == 8)
1417 IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
1418 else if (VecWidth == 512 && EltWidth == 8)
1419 IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
1420 else
1421 llvm_unreachable("Unexpected intrinsic");
1422
1423 Value *Args[] = { CI.getArgOperand(0) , CI.getArgOperand(1),
1424 CI.getArgOperand(2) };
1425
1426 // If this isn't index form we need to swap operand 0 and 1.
1427 if (!IndexForm)
1428 std::swap(Args[0], Args[1]);
1429
1430 Value *V = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1431 Args);
1432 Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty)
1433 : Builder.CreateBitCast(CI.getArgOperand(1),
1434 Ty);
1435 return EmitX86Select(Builder, CI.getArgOperand(3), V, PassThru);
1436 }
1437
UpgradeX86BinaryIntrinsics(IRBuilder<> & Builder,CallBase & CI,Intrinsic::ID IID)1438 static Value *UpgradeX86BinaryIntrinsics(IRBuilder<> &Builder, CallBase &CI,
1439 Intrinsic::ID IID) {
1440 Type *Ty = CI.getType();
1441 Value *Op0 = CI.getOperand(0);
1442 Value *Op1 = CI.getOperand(1);
1443 Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1444 Value *Res = Builder.CreateCall(Intrin, {Op0, Op1});
1445
1446 if (CI.arg_size() == 4) { // For masked intrinsics.
1447 Value *VecSrc = CI.getOperand(2);
1448 Value *Mask = CI.getOperand(3);
1449 Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1450 }
1451 return Res;
1452 }
1453
upgradeX86Rotate(IRBuilder<> & Builder,CallBase & CI,bool IsRotateRight)1454 static Value *upgradeX86Rotate(IRBuilder<> &Builder, CallBase &CI,
1455 bool IsRotateRight) {
1456 Type *Ty = CI.getType();
1457 Value *Src = CI.getArgOperand(0);
1458 Value *Amt = CI.getArgOperand(1);
1459
1460 // Amount may be scalar immediate, in which case create a splat vector.
1461 // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1462 // we only care about the lowest log2 bits anyway.
1463 if (Amt->getType() != Ty) {
1464 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1465 Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1466 Amt = Builder.CreateVectorSplat(NumElts, Amt);
1467 }
1468
1469 Intrinsic::ID IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1470 Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1471 Value *Res = Builder.CreateCall(Intrin, {Src, Src, Amt});
1472
1473 if (CI.arg_size() == 4) { // For masked intrinsics.
1474 Value *VecSrc = CI.getOperand(2);
1475 Value *Mask = CI.getOperand(3);
1476 Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1477 }
1478 return Res;
1479 }
1480
upgradeX86vpcom(IRBuilder<> & Builder,CallBase & CI,unsigned Imm,bool IsSigned)1481 static Value *upgradeX86vpcom(IRBuilder<> &Builder, CallBase &CI, unsigned Imm,
1482 bool IsSigned) {
1483 Type *Ty = CI.getType();
1484 Value *LHS = CI.getArgOperand(0);
1485 Value *RHS = CI.getArgOperand(1);
1486
1487 CmpInst::Predicate Pred;
1488 switch (Imm) {
1489 case 0x0:
1490 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1491 break;
1492 case 0x1:
1493 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1494 break;
1495 case 0x2:
1496 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1497 break;
1498 case 0x3:
1499 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1500 break;
1501 case 0x4:
1502 Pred = ICmpInst::ICMP_EQ;
1503 break;
1504 case 0x5:
1505 Pred = ICmpInst::ICMP_NE;
1506 break;
1507 case 0x6:
1508 return Constant::getNullValue(Ty); // FALSE
1509 case 0x7:
1510 return Constant::getAllOnesValue(Ty); // TRUE
1511 default:
1512 llvm_unreachable("Unknown XOP vpcom/vpcomu predicate");
1513 }
1514
1515 Value *Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1516 Value *Ext = Builder.CreateSExt(Cmp, Ty);
1517 return Ext;
1518 }
1519
upgradeX86ConcatShift(IRBuilder<> & Builder,CallBase & CI,bool IsShiftRight,bool ZeroMask)1520 static Value *upgradeX86ConcatShift(IRBuilder<> &Builder, CallBase &CI,
1521 bool IsShiftRight, bool ZeroMask) {
1522 Type *Ty = CI.getType();
1523 Value *Op0 = CI.getArgOperand(0);
1524 Value *Op1 = CI.getArgOperand(1);
1525 Value *Amt = CI.getArgOperand(2);
1526
1527 if (IsShiftRight)
1528 std::swap(Op0, Op1);
1529
1530 // Amount may be scalar immediate, in which case create a splat vector.
1531 // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1532 // we only care about the lowest log2 bits anyway.
1533 if (Amt->getType() != Ty) {
1534 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1535 Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1536 Amt = Builder.CreateVectorSplat(NumElts, Amt);
1537 }
1538
1539 Intrinsic::ID IID = IsShiftRight ? Intrinsic::fshr : Intrinsic::fshl;
1540 Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1541 Value *Res = Builder.CreateCall(Intrin, {Op0, Op1, Amt});
1542
1543 unsigned NumArgs = CI.arg_size();
1544 if (NumArgs >= 4) { // For masked intrinsics.
1545 Value *VecSrc = NumArgs == 5 ? CI.getArgOperand(3) :
1546 ZeroMask ? ConstantAggregateZero::get(CI.getType()) :
1547 CI.getArgOperand(0);
1548 Value *Mask = CI.getOperand(NumArgs - 1);
1549 Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1550 }
1551 return Res;
1552 }
1553
UpgradeMaskedStore(IRBuilder<> & Builder,Value * Ptr,Value * Data,Value * Mask,bool Aligned)1554 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
1555 Value *Ptr, Value *Data, Value *Mask,
1556 bool Aligned) {
1557 // Cast the pointer to the right type.
1558 Ptr = Builder.CreateBitCast(Ptr,
1559 llvm::PointerType::getUnqual(Data->getType()));
1560 const Align Alignment =
1561 Aligned
1562 ? Align(Data->getType()->getPrimitiveSizeInBits().getFixedValue() / 8)
1563 : Align(1);
1564
1565 // If the mask is all ones just emit a regular store.
1566 if (const auto *C = dyn_cast<Constant>(Mask))
1567 if (C->isAllOnesValue())
1568 return Builder.CreateAlignedStore(Data, Ptr, Alignment);
1569
1570 // Convert the mask from an integer type to a vector of i1.
1571 unsigned NumElts = cast<FixedVectorType>(Data->getType())->getNumElements();
1572 Mask = getX86MaskVec(Builder, Mask, NumElts);
1573 return Builder.CreateMaskedStore(Data, Ptr, Alignment, Mask);
1574 }
1575
UpgradeMaskedLoad(IRBuilder<> & Builder,Value * Ptr,Value * Passthru,Value * Mask,bool Aligned)1576 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
1577 Value *Ptr, Value *Passthru, Value *Mask,
1578 bool Aligned) {
1579 Type *ValTy = Passthru->getType();
1580 // Cast the pointer to the right type.
1581 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ValTy));
1582 const Align Alignment =
1583 Aligned
1584 ? Align(
1585 Passthru->getType()->getPrimitiveSizeInBits().getFixedValue() /
1586 8)
1587 : Align(1);
1588
1589 // If the mask is all ones just emit a regular store.
1590 if (const auto *C = dyn_cast<Constant>(Mask))
1591 if (C->isAllOnesValue())
1592 return Builder.CreateAlignedLoad(ValTy, Ptr, Alignment);
1593
1594 // Convert the mask from an integer type to a vector of i1.
1595 unsigned NumElts = cast<FixedVectorType>(ValTy)->getNumElements();
1596 Mask = getX86MaskVec(Builder, Mask, NumElts);
1597 return Builder.CreateMaskedLoad(ValTy, Ptr, Alignment, Mask, Passthru);
1598 }
1599
upgradeAbs(IRBuilder<> & Builder,CallBase & CI)1600 static Value *upgradeAbs(IRBuilder<> &Builder, CallBase &CI) {
1601 Type *Ty = CI.getType();
1602 Value *Op0 = CI.getArgOperand(0);
1603 Function *F = Intrinsic::getDeclaration(CI.getModule(), Intrinsic::abs, Ty);
1604 Value *Res = Builder.CreateCall(F, {Op0, Builder.getInt1(false)});
1605 if (CI.arg_size() == 3)
1606 Res = EmitX86Select(Builder, CI.getArgOperand(2), Res, CI.getArgOperand(1));
1607 return Res;
1608 }
1609
upgradePMULDQ(IRBuilder<> & Builder,CallBase & CI,bool IsSigned)1610 static Value *upgradePMULDQ(IRBuilder<> &Builder, CallBase &CI, bool IsSigned) {
1611 Type *Ty = CI.getType();
1612
1613 // Arguments have a vXi32 type so cast to vXi64.
1614 Value *LHS = Builder.CreateBitCast(CI.getArgOperand(0), Ty);
1615 Value *RHS = Builder.CreateBitCast(CI.getArgOperand(1), Ty);
1616
1617 if (IsSigned) {
1618 // Shift left then arithmetic shift right.
1619 Constant *ShiftAmt = ConstantInt::get(Ty, 32);
1620 LHS = Builder.CreateShl(LHS, ShiftAmt);
1621 LHS = Builder.CreateAShr(LHS, ShiftAmt);
1622 RHS = Builder.CreateShl(RHS, ShiftAmt);
1623 RHS = Builder.CreateAShr(RHS, ShiftAmt);
1624 } else {
1625 // Clear the upper bits.
1626 Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
1627 LHS = Builder.CreateAnd(LHS, Mask);
1628 RHS = Builder.CreateAnd(RHS, Mask);
1629 }
1630
1631 Value *Res = Builder.CreateMul(LHS, RHS);
1632
1633 if (CI.arg_size() == 4)
1634 Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1635
1636 return Res;
1637 }
1638
1639 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
ApplyX86MaskOn1BitsVec(IRBuilder<> & Builder,Value * Vec,Value * Mask)1640 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder, Value *Vec,
1641 Value *Mask) {
1642 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1643 if (Mask) {
1644 const auto *C = dyn_cast<Constant>(Mask);
1645 if (!C || !C->isAllOnesValue())
1646 Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
1647 }
1648
1649 if (NumElts < 8) {
1650 int Indices[8];
1651 for (unsigned i = 0; i != NumElts; ++i)
1652 Indices[i] = i;
1653 for (unsigned i = NumElts; i != 8; ++i)
1654 Indices[i] = NumElts + i % NumElts;
1655 Vec = Builder.CreateShuffleVector(Vec,
1656 Constant::getNullValue(Vec->getType()),
1657 Indices);
1658 }
1659 return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
1660 }
1661
upgradeMaskedCompare(IRBuilder<> & Builder,CallBase & CI,unsigned CC,bool Signed)1662 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallBase &CI,
1663 unsigned CC, bool Signed) {
1664 Value *Op0 = CI.getArgOperand(0);
1665 unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1666
1667 Value *Cmp;
1668 if (CC == 3) {
1669 Cmp = Constant::getNullValue(
1670 FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1671 } else if (CC == 7) {
1672 Cmp = Constant::getAllOnesValue(
1673 FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1674 } else {
1675 ICmpInst::Predicate Pred;
1676 switch (CC) {
1677 default: llvm_unreachable("Unknown condition code");
1678 case 0: Pred = ICmpInst::ICMP_EQ; break;
1679 case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
1680 case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
1681 case 4: Pred = ICmpInst::ICMP_NE; break;
1682 case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
1683 case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
1684 }
1685 Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
1686 }
1687
1688 Value *Mask = CI.getArgOperand(CI.arg_size() - 1);
1689
1690 return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask);
1691 }
1692
1693 // Replace a masked intrinsic with an older unmasked intrinsic.
UpgradeX86MaskedShift(IRBuilder<> & Builder,CallBase & CI,Intrinsic::ID IID)1694 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallBase &CI,
1695 Intrinsic::ID IID) {
1696 Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
1697 Value *Rep = Builder.CreateCall(Intrin,
1698 { CI.getArgOperand(0), CI.getArgOperand(1) });
1699 return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
1700 }
1701
upgradeMaskedMove(IRBuilder<> & Builder,CallBase & CI)1702 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallBase &CI) {
1703 Value* A = CI.getArgOperand(0);
1704 Value* B = CI.getArgOperand(1);
1705 Value* Src = CI.getArgOperand(2);
1706 Value* Mask = CI.getArgOperand(3);
1707
1708 Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
1709 Value* Cmp = Builder.CreateIsNotNull(AndNode);
1710 Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
1711 Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
1712 Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
1713 return Builder.CreateInsertElement(A, Select, (uint64_t)0);
1714 }
1715
1716
UpgradeMaskToInt(IRBuilder<> & Builder,CallBase & CI)1717 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallBase &CI) {
1718 Value* Op = CI.getArgOperand(0);
1719 Type* ReturnOp = CI.getType();
1720 unsigned NumElts = cast<FixedVectorType>(CI.getType())->getNumElements();
1721 Value *Mask = getX86MaskVec(Builder, Op, NumElts);
1722 return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
1723 }
1724
1725 // Replace intrinsic with unmasked version and a select.
upgradeAVX512MaskToSelect(StringRef Name,IRBuilder<> & Builder,CallBase & CI,Value * & Rep)1726 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
1727 CallBase &CI, Value *&Rep) {
1728 Name = Name.substr(12); // Remove avx512.mask.
1729
1730 unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
1731 unsigned EltWidth = CI.getType()->getScalarSizeInBits();
1732 Intrinsic::ID IID;
1733 if (Name.startswith("max.p")) {
1734 if (VecWidth == 128 && EltWidth == 32)
1735 IID = Intrinsic::x86_sse_max_ps;
1736 else if (VecWidth == 128 && EltWidth == 64)
1737 IID = Intrinsic::x86_sse2_max_pd;
1738 else if (VecWidth == 256 && EltWidth == 32)
1739 IID = Intrinsic::x86_avx_max_ps_256;
1740 else if (VecWidth == 256 && EltWidth == 64)
1741 IID = Intrinsic::x86_avx_max_pd_256;
1742 else
1743 llvm_unreachable("Unexpected intrinsic");
1744 } else if (Name.startswith("min.p")) {
1745 if (VecWidth == 128 && EltWidth == 32)
1746 IID = Intrinsic::x86_sse_min_ps;
1747 else if (VecWidth == 128 && EltWidth == 64)
1748 IID = Intrinsic::x86_sse2_min_pd;
1749 else if (VecWidth == 256 && EltWidth == 32)
1750 IID = Intrinsic::x86_avx_min_ps_256;
1751 else if (VecWidth == 256 && EltWidth == 64)
1752 IID = Intrinsic::x86_avx_min_pd_256;
1753 else
1754 llvm_unreachable("Unexpected intrinsic");
1755 } else if (Name.startswith("pshuf.b.")) {
1756 if (VecWidth == 128)
1757 IID = Intrinsic::x86_ssse3_pshuf_b_128;
1758 else if (VecWidth == 256)
1759 IID = Intrinsic::x86_avx2_pshuf_b;
1760 else if (VecWidth == 512)
1761 IID = Intrinsic::x86_avx512_pshuf_b_512;
1762 else
1763 llvm_unreachable("Unexpected intrinsic");
1764 } else if (Name.startswith("pmul.hr.sw.")) {
1765 if (VecWidth == 128)
1766 IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1767 else if (VecWidth == 256)
1768 IID = Intrinsic::x86_avx2_pmul_hr_sw;
1769 else if (VecWidth == 512)
1770 IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1771 else
1772 llvm_unreachable("Unexpected intrinsic");
1773 } else if (Name.startswith("pmulh.w.")) {
1774 if (VecWidth == 128)
1775 IID = Intrinsic::x86_sse2_pmulh_w;
1776 else if (VecWidth == 256)
1777 IID = Intrinsic::x86_avx2_pmulh_w;
1778 else if (VecWidth == 512)
1779 IID = Intrinsic::x86_avx512_pmulh_w_512;
1780 else
1781 llvm_unreachable("Unexpected intrinsic");
1782 } else if (Name.startswith("pmulhu.w.")) {
1783 if (VecWidth == 128)
1784 IID = Intrinsic::x86_sse2_pmulhu_w;
1785 else if (VecWidth == 256)
1786 IID = Intrinsic::x86_avx2_pmulhu_w;
1787 else if (VecWidth == 512)
1788 IID = Intrinsic::x86_avx512_pmulhu_w_512;
1789 else
1790 llvm_unreachable("Unexpected intrinsic");
1791 } else if (Name.startswith("pmaddw.d.")) {
1792 if (VecWidth == 128)
1793 IID = Intrinsic::x86_sse2_pmadd_wd;
1794 else if (VecWidth == 256)
1795 IID = Intrinsic::x86_avx2_pmadd_wd;
1796 else if (VecWidth == 512)
1797 IID = Intrinsic::x86_avx512_pmaddw_d_512;
1798 else
1799 llvm_unreachable("Unexpected intrinsic");
1800 } else if (Name.startswith("pmaddubs.w.")) {
1801 if (VecWidth == 128)
1802 IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1803 else if (VecWidth == 256)
1804 IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1805 else if (VecWidth == 512)
1806 IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1807 else
1808 llvm_unreachable("Unexpected intrinsic");
1809 } else if (Name.startswith("packsswb.")) {
1810 if (VecWidth == 128)
1811 IID = Intrinsic::x86_sse2_packsswb_128;
1812 else if (VecWidth == 256)
1813 IID = Intrinsic::x86_avx2_packsswb;
1814 else if (VecWidth == 512)
1815 IID = Intrinsic::x86_avx512_packsswb_512;
1816 else
1817 llvm_unreachable("Unexpected intrinsic");
1818 } else if (Name.startswith("packssdw.")) {
1819 if (VecWidth == 128)
1820 IID = Intrinsic::x86_sse2_packssdw_128;
1821 else if (VecWidth == 256)
1822 IID = Intrinsic::x86_avx2_packssdw;
1823 else if (VecWidth == 512)
1824 IID = Intrinsic::x86_avx512_packssdw_512;
1825 else
1826 llvm_unreachable("Unexpected intrinsic");
1827 } else if (Name.startswith("packuswb.")) {
1828 if (VecWidth == 128)
1829 IID = Intrinsic::x86_sse2_packuswb_128;
1830 else if (VecWidth == 256)
1831 IID = Intrinsic::x86_avx2_packuswb;
1832 else if (VecWidth == 512)
1833 IID = Intrinsic::x86_avx512_packuswb_512;
1834 else
1835 llvm_unreachable("Unexpected intrinsic");
1836 } else if (Name.startswith("packusdw.")) {
1837 if (VecWidth == 128)
1838 IID = Intrinsic::x86_sse41_packusdw;
1839 else if (VecWidth == 256)
1840 IID = Intrinsic::x86_avx2_packusdw;
1841 else if (VecWidth == 512)
1842 IID = Intrinsic::x86_avx512_packusdw_512;
1843 else
1844 llvm_unreachable("Unexpected intrinsic");
1845 } else if (Name.startswith("vpermilvar.")) {
1846 if (VecWidth == 128 && EltWidth == 32)
1847 IID = Intrinsic::x86_avx_vpermilvar_ps;
1848 else if (VecWidth == 128 && EltWidth == 64)
1849 IID = Intrinsic::x86_avx_vpermilvar_pd;
1850 else if (VecWidth == 256 && EltWidth == 32)
1851 IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1852 else if (VecWidth == 256 && EltWidth == 64)
1853 IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1854 else if (VecWidth == 512 && EltWidth == 32)
1855 IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1856 else if (VecWidth == 512 && EltWidth == 64)
1857 IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1858 else
1859 llvm_unreachable("Unexpected intrinsic");
1860 } else if (Name == "cvtpd2dq.256") {
1861 IID = Intrinsic::x86_avx_cvt_pd2dq_256;
1862 } else if (Name == "cvtpd2ps.256") {
1863 IID = Intrinsic::x86_avx_cvt_pd2_ps_256;
1864 } else if (Name == "cvttpd2dq.256") {
1865 IID = Intrinsic::x86_avx_cvtt_pd2dq_256;
1866 } else if (Name == "cvttps2dq.128") {
1867 IID = Intrinsic::x86_sse2_cvttps2dq;
1868 } else if (Name == "cvttps2dq.256") {
1869 IID = Intrinsic::x86_avx_cvtt_ps2dq_256;
1870 } else if (Name.startswith("permvar.")) {
1871 bool IsFloat = CI.getType()->isFPOrFPVectorTy();
1872 if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1873 IID = Intrinsic::x86_avx2_permps;
1874 else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1875 IID = Intrinsic::x86_avx2_permd;
1876 else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1877 IID = Intrinsic::x86_avx512_permvar_df_256;
1878 else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1879 IID = Intrinsic::x86_avx512_permvar_di_256;
1880 else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1881 IID = Intrinsic::x86_avx512_permvar_sf_512;
1882 else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1883 IID = Intrinsic::x86_avx512_permvar_si_512;
1884 else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1885 IID = Intrinsic::x86_avx512_permvar_df_512;
1886 else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1887 IID = Intrinsic::x86_avx512_permvar_di_512;
1888 else if (VecWidth == 128 && EltWidth == 16)
1889 IID = Intrinsic::x86_avx512_permvar_hi_128;
1890 else if (VecWidth == 256 && EltWidth == 16)
1891 IID = Intrinsic::x86_avx512_permvar_hi_256;
1892 else if (VecWidth == 512 && EltWidth == 16)
1893 IID = Intrinsic::x86_avx512_permvar_hi_512;
1894 else if (VecWidth == 128 && EltWidth == 8)
1895 IID = Intrinsic::x86_avx512_permvar_qi_128;
1896 else if (VecWidth == 256 && EltWidth == 8)
1897 IID = Intrinsic::x86_avx512_permvar_qi_256;
1898 else if (VecWidth == 512 && EltWidth == 8)
1899 IID = Intrinsic::x86_avx512_permvar_qi_512;
1900 else
1901 llvm_unreachable("Unexpected intrinsic");
1902 } else if (Name.startswith("dbpsadbw.")) {
1903 if (VecWidth == 128)
1904 IID = Intrinsic::x86_avx512_dbpsadbw_128;
1905 else if (VecWidth == 256)
1906 IID = Intrinsic::x86_avx512_dbpsadbw_256;
1907 else if (VecWidth == 512)
1908 IID = Intrinsic::x86_avx512_dbpsadbw_512;
1909 else
1910 llvm_unreachable("Unexpected intrinsic");
1911 } else if (Name.startswith("pmultishift.qb.")) {
1912 if (VecWidth == 128)
1913 IID = Intrinsic::x86_avx512_pmultishift_qb_128;
1914 else if (VecWidth == 256)
1915 IID = Intrinsic::x86_avx512_pmultishift_qb_256;
1916 else if (VecWidth == 512)
1917 IID = Intrinsic::x86_avx512_pmultishift_qb_512;
1918 else
1919 llvm_unreachable("Unexpected intrinsic");
1920 } else if (Name.startswith("conflict.")) {
1921 if (Name[9] == 'd' && VecWidth == 128)
1922 IID = Intrinsic::x86_avx512_conflict_d_128;
1923 else if (Name[9] == 'd' && VecWidth == 256)
1924 IID = Intrinsic::x86_avx512_conflict_d_256;
1925 else if (Name[9] == 'd' && VecWidth == 512)
1926 IID = Intrinsic::x86_avx512_conflict_d_512;
1927 else if (Name[9] == 'q' && VecWidth == 128)
1928 IID = Intrinsic::x86_avx512_conflict_q_128;
1929 else if (Name[9] == 'q' && VecWidth == 256)
1930 IID = Intrinsic::x86_avx512_conflict_q_256;
1931 else if (Name[9] == 'q' && VecWidth == 512)
1932 IID = Intrinsic::x86_avx512_conflict_q_512;
1933 else
1934 llvm_unreachable("Unexpected intrinsic");
1935 } else if (Name.startswith("pavg.")) {
1936 if (Name[5] == 'b' && VecWidth == 128)
1937 IID = Intrinsic::x86_sse2_pavg_b;
1938 else if (Name[5] == 'b' && VecWidth == 256)
1939 IID = Intrinsic::x86_avx2_pavg_b;
1940 else if (Name[5] == 'b' && VecWidth == 512)
1941 IID = Intrinsic::x86_avx512_pavg_b_512;
1942 else if (Name[5] == 'w' && VecWidth == 128)
1943 IID = Intrinsic::x86_sse2_pavg_w;
1944 else if (Name[5] == 'w' && VecWidth == 256)
1945 IID = Intrinsic::x86_avx2_pavg_w;
1946 else if (Name[5] == 'w' && VecWidth == 512)
1947 IID = Intrinsic::x86_avx512_pavg_w_512;
1948 else
1949 llvm_unreachable("Unexpected intrinsic");
1950 } else
1951 return false;
1952
1953 SmallVector<Value *, 4> Args(CI.args());
1954 Args.pop_back();
1955 Args.pop_back();
1956 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1957 Args);
1958 unsigned NumArgs = CI.arg_size();
1959 Rep = EmitX86Select(Builder, CI.getArgOperand(NumArgs - 1), Rep,
1960 CI.getArgOperand(NumArgs - 2));
1961 return true;
1962 }
1963
1964 /// Upgrade comment in call to inline asm that represents an objc retain release
1965 /// marker.
UpgradeInlineAsmString(std::string * AsmStr)1966 void llvm::UpgradeInlineAsmString(std::string *AsmStr) {
1967 size_t Pos;
1968 if (AsmStr->find("mov\tfp") == 0 &&
1969 AsmStr->find("objc_retainAutoreleaseReturnValue") != std::string::npos &&
1970 (Pos = AsmStr->find("# marker")) != std::string::npos) {
1971 AsmStr->replace(Pos, 1, ";");
1972 }
1973 }
1974
UpgradeARMIntrinsicCall(StringRef Name,CallBase * CI,Function * F,IRBuilder<> & Builder)1975 static Value *UpgradeARMIntrinsicCall(StringRef Name, CallBase *CI, Function *F,
1976 IRBuilder<> &Builder) {
1977 if (Name == "mve.vctp64.old") {
1978 // Replace the old v4i1 vctp64 with a v2i1 vctp and predicate-casts to the
1979 // correct type.
1980 Value *VCTP = Builder.CreateCall(
1981 Intrinsic::getDeclaration(F->getParent(), Intrinsic::arm_mve_vctp64),
1982 CI->getArgOperand(0), CI->getName());
1983 Value *C1 = Builder.CreateCall(
1984 Intrinsic::getDeclaration(
1985 F->getParent(), Intrinsic::arm_mve_pred_v2i,
1986 {VectorType::get(Builder.getInt1Ty(), 2, false)}),
1987 VCTP);
1988 return Builder.CreateCall(
1989 Intrinsic::getDeclaration(
1990 F->getParent(), Intrinsic::arm_mve_pred_i2v,
1991 {VectorType::get(Builder.getInt1Ty(), 4, false)}),
1992 C1);
1993 } else if (Name == "mve.mull.int.predicated.v2i64.v4i32.v4i1" ||
1994 Name == "mve.vqdmull.predicated.v2i64.v4i32.v4i1" ||
1995 Name == "mve.vldr.gather.base.predicated.v2i64.v2i64.v4i1" ||
1996 Name == "mve.vldr.gather.base.wb.predicated.v2i64.v2i64.v4i1" ||
1997 Name == "mve.vldr.gather.offset.predicated.v2i64.p0i64.v2i64.v4i1" ||
1998 Name == "mve.vstr.scatter.base.predicated.v2i64.v2i64.v4i1" ||
1999 Name == "mve.vstr.scatter.base.wb.predicated.v2i64.v2i64.v4i1" ||
2000 Name == "mve.vstr.scatter.offset.predicated.p0i64.v2i64.v2i64.v4i1" ||
2001 Name == "cde.vcx1q.predicated.v2i64.v4i1" ||
2002 Name == "cde.vcx1qa.predicated.v2i64.v4i1" ||
2003 Name == "cde.vcx2q.predicated.v2i64.v4i1" ||
2004 Name == "cde.vcx2qa.predicated.v2i64.v4i1" ||
2005 Name == "cde.vcx3q.predicated.v2i64.v4i1" ||
2006 Name == "cde.vcx3qa.predicated.v2i64.v4i1") {
2007 std::vector<Type *> Tys;
2008 unsigned ID = CI->getIntrinsicID();
2009 Type *V2I1Ty = FixedVectorType::get(Builder.getInt1Ty(), 2);
2010 switch (ID) {
2011 case Intrinsic::arm_mve_mull_int_predicated:
2012 case Intrinsic::arm_mve_vqdmull_predicated:
2013 case Intrinsic::arm_mve_vldr_gather_base_predicated:
2014 Tys = {CI->getType(), CI->getOperand(0)->getType(), V2I1Ty};
2015 break;
2016 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated:
2017 case Intrinsic::arm_mve_vstr_scatter_base_predicated:
2018 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated:
2019 Tys = {CI->getOperand(0)->getType(), CI->getOperand(0)->getType(),
2020 V2I1Ty};
2021 break;
2022 case Intrinsic::arm_mve_vldr_gather_offset_predicated:
2023 Tys = {CI->getType(), CI->getOperand(0)->getType(),
2024 CI->getOperand(1)->getType(), V2I1Ty};
2025 break;
2026 case Intrinsic::arm_mve_vstr_scatter_offset_predicated:
2027 Tys = {CI->getOperand(0)->getType(), CI->getOperand(1)->getType(),
2028 CI->getOperand(2)->getType(), V2I1Ty};
2029 break;
2030 case Intrinsic::arm_cde_vcx1q_predicated:
2031 case Intrinsic::arm_cde_vcx1qa_predicated:
2032 case Intrinsic::arm_cde_vcx2q_predicated:
2033 case Intrinsic::arm_cde_vcx2qa_predicated:
2034 case Intrinsic::arm_cde_vcx3q_predicated:
2035 case Intrinsic::arm_cde_vcx3qa_predicated:
2036 Tys = {CI->getOperand(1)->getType(), V2I1Ty};
2037 break;
2038 default:
2039 llvm_unreachable("Unhandled Intrinsic!");
2040 }
2041
2042 std::vector<Value *> Ops;
2043 for (Value *Op : CI->args()) {
2044 Type *Ty = Op->getType();
2045 if (Ty->getScalarSizeInBits() == 1) {
2046 Value *C1 = Builder.CreateCall(
2047 Intrinsic::getDeclaration(
2048 F->getParent(), Intrinsic::arm_mve_pred_v2i,
2049 {VectorType::get(Builder.getInt1Ty(), 4, false)}),
2050 Op);
2051 Op = Builder.CreateCall(
2052 Intrinsic::getDeclaration(F->getParent(),
2053 Intrinsic::arm_mve_pred_i2v, {V2I1Ty}),
2054 C1);
2055 }
2056 Ops.push_back(Op);
2057 }
2058
2059 Function *Fn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
2060 return Builder.CreateCall(Fn, Ops, CI->getName());
2061 }
2062 llvm_unreachable("Unknown function for ARM CallBase upgrade.");
2063 }
2064
2065 /// Upgrade a call to an old intrinsic. All argument and return casting must be
2066 /// provided to seamlessly integrate with existing context.
UpgradeIntrinsicCall(CallBase * CI,Function * NewFn)2067 void llvm::UpgradeIntrinsicCall(CallBase *CI, Function *NewFn) {
2068 // Note dyn_cast to Function is not quite the same as getCalledFunction, which
2069 // checks the callee's function type matches. It's likely we need to handle
2070 // type changes here.
2071 Function *F = dyn_cast<Function>(CI->getCalledOperand());
2072 if (!F)
2073 return;
2074
2075 LLVMContext &C = CI->getContext();
2076 IRBuilder<> Builder(C);
2077 Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
2078
2079 if (!NewFn) {
2080 // Get the Function's name.
2081 StringRef Name = F->getName();
2082
2083 assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
2084 Name = Name.substr(5);
2085
2086 bool IsX86 = Name.startswith("x86.");
2087 if (IsX86)
2088 Name = Name.substr(4);
2089 bool IsNVVM = Name.startswith("nvvm.");
2090 if (IsNVVM)
2091 Name = Name.substr(5);
2092 bool IsARM = Name.startswith("arm.");
2093 if (IsARM)
2094 Name = Name.substr(4);
2095
2096 if (IsX86 && Name.startswith("sse4a.movnt.")) {
2097 Module *M = F->getParent();
2098 SmallVector<Metadata *, 1> Elts;
2099 Elts.push_back(
2100 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
2101 MDNode *Node = MDNode::get(C, Elts);
2102
2103 Value *Arg0 = CI->getArgOperand(0);
2104 Value *Arg1 = CI->getArgOperand(1);
2105
2106 // Nontemporal (unaligned) store of the 0'th element of the float/double
2107 // vector.
2108 Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
2109 PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
2110 Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
2111 Value *Extract =
2112 Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
2113
2114 StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, Align(1));
2115 SI->setMetadata(M->getMDKindID("nontemporal"), Node);
2116
2117 // Remove intrinsic.
2118 CI->eraseFromParent();
2119 return;
2120 }
2121
2122 if (IsX86 && (Name.startswith("avx.movnt.") ||
2123 Name.startswith("avx512.storent."))) {
2124 Module *M = F->getParent();
2125 SmallVector<Metadata *, 1> Elts;
2126 Elts.push_back(
2127 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
2128 MDNode *Node = MDNode::get(C, Elts);
2129
2130 Value *Arg0 = CI->getArgOperand(0);
2131 Value *Arg1 = CI->getArgOperand(1);
2132
2133 // Convert the type of the pointer to a pointer to the stored type.
2134 Value *BC = Builder.CreateBitCast(Arg0,
2135 PointerType::getUnqual(Arg1->getType()),
2136 "cast");
2137 StoreInst *SI = Builder.CreateAlignedStore(
2138 Arg1, BC,
2139 Align(Arg1->getType()->getPrimitiveSizeInBits().getFixedValue() / 8));
2140 SI->setMetadata(M->getMDKindID("nontemporal"), Node);
2141
2142 // Remove intrinsic.
2143 CI->eraseFromParent();
2144 return;
2145 }
2146
2147 if (IsX86 && Name == "sse2.storel.dq") {
2148 Value *Arg0 = CI->getArgOperand(0);
2149 Value *Arg1 = CI->getArgOperand(1);
2150
2151 auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
2152 Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
2153 Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
2154 Value *BC = Builder.CreateBitCast(Arg0,
2155 PointerType::getUnqual(Elt->getType()),
2156 "cast");
2157 Builder.CreateAlignedStore(Elt, BC, Align(1));
2158
2159 // Remove intrinsic.
2160 CI->eraseFromParent();
2161 return;
2162 }
2163
2164 if (IsX86 && (Name.startswith("sse.storeu.") ||
2165 Name.startswith("sse2.storeu.") ||
2166 Name.startswith("avx.storeu."))) {
2167 Value *Arg0 = CI->getArgOperand(0);
2168 Value *Arg1 = CI->getArgOperand(1);
2169
2170 Arg0 = Builder.CreateBitCast(Arg0,
2171 PointerType::getUnqual(Arg1->getType()),
2172 "cast");
2173 Builder.CreateAlignedStore(Arg1, Arg0, Align(1));
2174
2175 // Remove intrinsic.
2176 CI->eraseFromParent();
2177 return;
2178 }
2179
2180 if (IsX86 && Name == "avx512.mask.store.ss") {
2181 Value *Mask = Builder.CreateAnd(CI->getArgOperand(2), Builder.getInt8(1));
2182 UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
2183 Mask, false);
2184
2185 // Remove intrinsic.
2186 CI->eraseFromParent();
2187 return;
2188 }
2189
2190 if (IsX86 && (Name.startswith("avx512.mask.store"))) {
2191 // "avx512.mask.storeu." or "avx512.mask.store."
2192 bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
2193 UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
2194 CI->getArgOperand(2), Aligned);
2195
2196 // Remove intrinsic.
2197 CI->eraseFromParent();
2198 return;
2199 }
2200
2201 Value *Rep;
2202 // Upgrade packed integer vector compare intrinsics to compare instructions.
2203 if (IsX86 && (Name.startswith("sse2.pcmp") ||
2204 Name.startswith("avx2.pcmp"))) {
2205 // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
2206 bool CmpEq = Name[9] == 'e';
2207 Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
2208 CI->getArgOperand(0), CI->getArgOperand(1));
2209 Rep = Builder.CreateSExt(Rep, CI->getType(), "");
2210 } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
2211 Type *ExtTy = Type::getInt32Ty(C);
2212 if (CI->getOperand(0)->getType()->isIntegerTy(8))
2213 ExtTy = Type::getInt64Ty(C);
2214 unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
2215 ExtTy->getPrimitiveSizeInBits();
2216 Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
2217 Rep = Builder.CreateVectorSplat(NumElts, Rep);
2218 } else if (IsX86 && (Name == "sse.sqrt.ss" ||
2219 Name == "sse2.sqrt.sd")) {
2220 Value *Vec = CI->getArgOperand(0);
2221 Value *Elt0 = Builder.CreateExtractElement(Vec, (uint64_t)0);
2222 Function *Intr = Intrinsic::getDeclaration(F->getParent(),
2223 Intrinsic::sqrt, Elt0->getType());
2224 Elt0 = Builder.CreateCall(Intr, Elt0);
2225 Rep = Builder.CreateInsertElement(Vec, Elt0, (uint64_t)0);
2226 } else if (IsX86 && (Name.startswith("avx.sqrt.p") ||
2227 Name.startswith("sse2.sqrt.p") ||
2228 Name.startswith("sse.sqrt.p"))) {
2229 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2230 Intrinsic::sqrt,
2231 CI->getType()),
2232 {CI->getArgOperand(0)});
2233 } else if (IsX86 && (Name.startswith("avx512.mask.sqrt.p"))) {
2234 if (CI->arg_size() == 4 &&
2235 (!isa<ConstantInt>(CI->getArgOperand(3)) ||
2236 cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
2237 Intrinsic::ID IID = Name[18] == 's' ? Intrinsic::x86_avx512_sqrt_ps_512
2238 : Intrinsic::x86_avx512_sqrt_pd_512;
2239
2240 Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(3) };
2241 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
2242 IID), Args);
2243 } else {
2244 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2245 Intrinsic::sqrt,
2246 CI->getType()),
2247 {CI->getArgOperand(0)});
2248 }
2249 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2250 CI->getArgOperand(1));
2251 } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
2252 Name.startswith("avx512.ptestnm"))) {
2253 Value *Op0 = CI->getArgOperand(0);
2254 Value *Op1 = CI->getArgOperand(1);
2255 Value *Mask = CI->getArgOperand(2);
2256 Rep = Builder.CreateAnd(Op0, Op1);
2257 llvm::Type *Ty = Op0->getType();
2258 Value *Zero = llvm::Constant::getNullValue(Ty);
2259 ICmpInst::Predicate Pred =
2260 Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
2261 Rep = Builder.CreateICmp(Pred, Rep, Zero);
2262 Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask);
2263 } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
2264 unsigned NumElts = cast<FixedVectorType>(CI->getArgOperand(1)->getType())
2265 ->getNumElements();
2266 Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
2267 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2268 CI->getArgOperand(1));
2269 } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
2270 unsigned NumElts = CI->getType()->getScalarSizeInBits();
2271 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
2272 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
2273 int Indices[64];
2274 for (unsigned i = 0; i != NumElts; ++i)
2275 Indices[i] = i;
2276
2277 // First extract half of each vector. This gives better codegen than
2278 // doing it in a single shuffle.
2279 LHS =
2280 Builder.CreateShuffleVector(LHS, LHS, ArrayRef(Indices, NumElts / 2));
2281 RHS =
2282 Builder.CreateShuffleVector(RHS, RHS, ArrayRef(Indices, NumElts / 2));
2283 // Concat the vectors.
2284 // NOTE: Operands have to be swapped to match intrinsic definition.
2285 Rep = Builder.CreateShuffleVector(RHS, LHS, ArrayRef(Indices, NumElts));
2286 Rep = Builder.CreateBitCast(Rep, CI->getType());
2287 } else if (IsX86 && Name == "avx512.kand.w") {
2288 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2289 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2290 Rep = Builder.CreateAnd(LHS, RHS);
2291 Rep = Builder.CreateBitCast(Rep, CI->getType());
2292 } else if (IsX86 && Name == "avx512.kandn.w") {
2293 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2294 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2295 LHS = Builder.CreateNot(LHS);
2296 Rep = Builder.CreateAnd(LHS, RHS);
2297 Rep = Builder.CreateBitCast(Rep, CI->getType());
2298 } else if (IsX86 && Name == "avx512.kor.w") {
2299 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2300 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2301 Rep = Builder.CreateOr(LHS, RHS);
2302 Rep = Builder.CreateBitCast(Rep, CI->getType());
2303 } else if (IsX86 && Name == "avx512.kxor.w") {
2304 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2305 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2306 Rep = Builder.CreateXor(LHS, RHS);
2307 Rep = Builder.CreateBitCast(Rep, CI->getType());
2308 } else if (IsX86 && Name == "avx512.kxnor.w") {
2309 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2310 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2311 LHS = Builder.CreateNot(LHS);
2312 Rep = Builder.CreateXor(LHS, RHS);
2313 Rep = Builder.CreateBitCast(Rep, CI->getType());
2314 } else if (IsX86 && Name == "avx512.knot.w") {
2315 Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2316 Rep = Builder.CreateNot(Rep);
2317 Rep = Builder.CreateBitCast(Rep, CI->getType());
2318 } else if (IsX86 &&
2319 (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
2320 Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2321 Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2322 Rep = Builder.CreateOr(LHS, RHS);
2323 Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
2324 Value *C;
2325 if (Name[14] == 'c')
2326 C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
2327 else
2328 C = ConstantInt::getNullValue(Builder.getInt16Ty());
2329 Rep = Builder.CreateICmpEQ(Rep, C);
2330 Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
2331 } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd" ||
2332 Name == "sse.sub.ss" || Name == "sse2.sub.sd" ||
2333 Name == "sse.mul.ss" || Name == "sse2.mul.sd" ||
2334 Name == "sse.div.ss" || Name == "sse2.div.sd")) {
2335 Type *I32Ty = Type::getInt32Ty(C);
2336 Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
2337 ConstantInt::get(I32Ty, 0));
2338 Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
2339 ConstantInt::get(I32Ty, 0));
2340 Value *EltOp;
2341 if (Name.contains(".add."))
2342 EltOp = Builder.CreateFAdd(Elt0, Elt1);
2343 else if (Name.contains(".sub."))
2344 EltOp = Builder.CreateFSub(Elt0, Elt1);
2345 else if (Name.contains(".mul."))
2346 EltOp = Builder.CreateFMul(Elt0, Elt1);
2347 else
2348 EltOp = Builder.CreateFDiv(Elt0, Elt1);
2349 Rep = Builder.CreateInsertElement(CI->getArgOperand(0), EltOp,
2350 ConstantInt::get(I32Ty, 0));
2351 } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
2352 // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
2353 bool CmpEq = Name[16] == 'e';
2354 Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
2355 } else if (IsX86 && Name.startswith("avx512.mask.vpshufbitqmb.")) {
2356 Type *OpTy = CI->getArgOperand(0)->getType();
2357 unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2358 Intrinsic::ID IID;
2359 switch (VecWidth) {
2360 default: llvm_unreachable("Unexpected intrinsic");
2361 case 128: IID = Intrinsic::x86_avx512_vpshufbitqmb_128; break;
2362 case 256: IID = Intrinsic::x86_avx512_vpshufbitqmb_256; break;
2363 case 512: IID = Intrinsic::x86_avx512_vpshufbitqmb_512; break;
2364 }
2365
2366 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2367 { CI->getOperand(0), CI->getArgOperand(1) });
2368 Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2369 } else if (IsX86 && Name.startswith("avx512.mask.fpclass.p")) {
2370 Type *OpTy = CI->getArgOperand(0)->getType();
2371 unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2372 unsigned EltWidth = OpTy->getScalarSizeInBits();
2373 Intrinsic::ID IID;
2374 if (VecWidth == 128 && EltWidth == 32)
2375 IID = Intrinsic::x86_avx512_fpclass_ps_128;
2376 else if (VecWidth == 256 && EltWidth == 32)
2377 IID = Intrinsic::x86_avx512_fpclass_ps_256;
2378 else if (VecWidth == 512 && EltWidth == 32)
2379 IID = Intrinsic::x86_avx512_fpclass_ps_512;
2380 else if (VecWidth == 128 && EltWidth == 64)
2381 IID = Intrinsic::x86_avx512_fpclass_pd_128;
2382 else if (VecWidth == 256 && EltWidth == 64)
2383 IID = Intrinsic::x86_avx512_fpclass_pd_256;
2384 else if (VecWidth == 512 && EltWidth == 64)
2385 IID = Intrinsic::x86_avx512_fpclass_pd_512;
2386 else
2387 llvm_unreachable("Unexpected intrinsic");
2388
2389 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2390 { CI->getOperand(0), CI->getArgOperand(1) });
2391 Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2392 } else if (IsX86 && Name.startswith("avx512.cmp.p")) {
2393 SmallVector<Value *, 4> Args(CI->args());
2394 Type *OpTy = Args[0]->getType();
2395 unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2396 unsigned EltWidth = OpTy->getScalarSizeInBits();
2397 Intrinsic::ID IID;
2398 if (VecWidth == 128 && EltWidth == 32)
2399 IID = Intrinsic::x86_avx512_mask_cmp_ps_128;
2400 else if (VecWidth == 256 && EltWidth == 32)
2401 IID = Intrinsic::x86_avx512_mask_cmp_ps_256;
2402 else if (VecWidth == 512 && EltWidth == 32)
2403 IID = Intrinsic::x86_avx512_mask_cmp_ps_512;
2404 else if (VecWidth == 128 && EltWidth == 64)
2405 IID = Intrinsic::x86_avx512_mask_cmp_pd_128;
2406 else if (VecWidth == 256 && EltWidth == 64)
2407 IID = Intrinsic::x86_avx512_mask_cmp_pd_256;
2408 else if (VecWidth == 512 && EltWidth == 64)
2409 IID = Intrinsic::x86_avx512_mask_cmp_pd_512;
2410 else
2411 llvm_unreachable("Unexpected intrinsic");
2412
2413 Value *Mask = Constant::getAllOnesValue(CI->getType());
2414 if (VecWidth == 512)
2415 std::swap(Mask, Args.back());
2416 Args.push_back(Mask);
2417
2418 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2419 Args);
2420 } else if (IsX86 && Name.startswith("avx512.mask.cmp.")) {
2421 // Integer compare intrinsics.
2422 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2423 Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
2424 } else if (IsX86 && Name.startswith("avx512.mask.ucmp.")) {
2425 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2426 Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
2427 } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
2428 Name.startswith("avx512.cvtw2mask.") ||
2429 Name.startswith("avx512.cvtd2mask.") ||
2430 Name.startswith("avx512.cvtq2mask."))) {
2431 Value *Op = CI->getArgOperand(0);
2432 Value *Zero = llvm::Constant::getNullValue(Op->getType());
2433 Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
2434 Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr);
2435 } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
2436 Name == "ssse3.pabs.w.128" ||
2437 Name == "ssse3.pabs.d.128" ||
2438 Name.startswith("avx2.pabs") ||
2439 Name.startswith("avx512.mask.pabs"))) {
2440 Rep = upgradeAbs(Builder, *CI);
2441 } else if (IsX86 && (Name == "sse41.pmaxsb" ||
2442 Name == "sse2.pmaxs.w" ||
2443 Name == "sse41.pmaxsd" ||
2444 Name.startswith("avx2.pmaxs") ||
2445 Name.startswith("avx512.mask.pmaxs"))) {
2446 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::smax);
2447 } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
2448 Name == "sse41.pmaxuw" ||
2449 Name == "sse41.pmaxud" ||
2450 Name.startswith("avx2.pmaxu") ||
2451 Name.startswith("avx512.mask.pmaxu"))) {
2452 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::umax);
2453 } else if (IsX86 && (Name == "sse41.pminsb" ||
2454 Name == "sse2.pmins.w" ||
2455 Name == "sse41.pminsd" ||
2456 Name.startswith("avx2.pmins") ||
2457 Name.startswith("avx512.mask.pmins"))) {
2458 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::smin);
2459 } else if (IsX86 && (Name == "sse2.pminu.b" ||
2460 Name == "sse41.pminuw" ||
2461 Name == "sse41.pminud" ||
2462 Name.startswith("avx2.pminu") ||
2463 Name.startswith("avx512.mask.pminu"))) {
2464 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::umin);
2465 } else if (IsX86 && (Name == "sse2.pmulu.dq" ||
2466 Name == "avx2.pmulu.dq" ||
2467 Name == "avx512.pmulu.dq.512" ||
2468 Name.startswith("avx512.mask.pmulu.dq."))) {
2469 Rep = upgradePMULDQ(Builder, *CI, /*Signed*/false);
2470 } else if (IsX86 && (Name == "sse41.pmuldq" ||
2471 Name == "avx2.pmul.dq" ||
2472 Name == "avx512.pmul.dq.512" ||
2473 Name.startswith("avx512.mask.pmul.dq."))) {
2474 Rep = upgradePMULDQ(Builder, *CI, /*Signed*/true);
2475 } else if (IsX86 && (Name == "sse.cvtsi2ss" ||
2476 Name == "sse2.cvtsi2sd" ||
2477 Name == "sse.cvtsi642ss" ||
2478 Name == "sse2.cvtsi642sd")) {
2479 Rep = Builder.CreateSIToFP(
2480 CI->getArgOperand(1),
2481 cast<VectorType>(CI->getType())->getElementType());
2482 Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2483 } else if (IsX86 && Name == "avx512.cvtusi2sd") {
2484 Rep = Builder.CreateUIToFP(
2485 CI->getArgOperand(1),
2486 cast<VectorType>(CI->getType())->getElementType());
2487 Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2488 } else if (IsX86 && Name == "sse2.cvtss2sd") {
2489 Rep = Builder.CreateExtractElement(CI->getArgOperand(1), (uint64_t)0);
2490 Rep = Builder.CreateFPExt(
2491 Rep, cast<VectorType>(CI->getType())->getElementType());
2492 Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2493 } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
2494 Name == "sse2.cvtdq2ps" ||
2495 Name == "avx.cvtdq2.pd.256" ||
2496 Name == "avx.cvtdq2.ps.256" ||
2497 Name.startswith("avx512.mask.cvtdq2pd.") ||
2498 Name.startswith("avx512.mask.cvtudq2pd.") ||
2499 Name.startswith("avx512.mask.cvtdq2ps.") ||
2500 Name.startswith("avx512.mask.cvtudq2ps.") ||
2501 Name.startswith("avx512.mask.cvtqq2pd.") ||
2502 Name.startswith("avx512.mask.cvtuqq2pd.") ||
2503 Name == "avx512.mask.cvtqq2ps.256" ||
2504 Name == "avx512.mask.cvtqq2ps.512" ||
2505 Name == "avx512.mask.cvtuqq2ps.256" ||
2506 Name == "avx512.mask.cvtuqq2ps.512" ||
2507 Name == "sse2.cvtps2pd" ||
2508 Name == "avx.cvt.ps2.pd.256" ||
2509 Name == "avx512.mask.cvtps2pd.128" ||
2510 Name == "avx512.mask.cvtps2pd.256")) {
2511 auto *DstTy = cast<FixedVectorType>(CI->getType());
2512 Rep = CI->getArgOperand(0);
2513 auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2514
2515 unsigned NumDstElts = DstTy->getNumElements();
2516 if (NumDstElts < SrcTy->getNumElements()) {
2517 assert(NumDstElts == 2 && "Unexpected vector size");
2518 Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1});
2519 }
2520
2521 bool IsPS2PD = SrcTy->getElementType()->isFloatTy();
2522 bool IsUnsigned = (StringRef::npos != Name.find("cvtu"));
2523 if (IsPS2PD)
2524 Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
2525 else if (CI->arg_size() == 4 &&
2526 (!isa<ConstantInt>(CI->getArgOperand(3)) ||
2527 cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
2528 Intrinsic::ID IID = IsUnsigned ? Intrinsic::x86_avx512_uitofp_round
2529 : Intrinsic::x86_avx512_sitofp_round;
2530 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID,
2531 { DstTy, SrcTy });
2532 Rep = Builder.CreateCall(F, { Rep, CI->getArgOperand(3) });
2533 } else {
2534 Rep = IsUnsigned ? Builder.CreateUIToFP(Rep, DstTy, "cvt")
2535 : Builder.CreateSIToFP(Rep, DstTy, "cvt");
2536 }
2537
2538 if (CI->arg_size() >= 3)
2539 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2540 CI->getArgOperand(1));
2541 } else if (IsX86 && (Name.startswith("avx512.mask.vcvtph2ps.") ||
2542 Name.startswith("vcvtph2ps."))) {
2543 auto *DstTy = cast<FixedVectorType>(CI->getType());
2544 Rep = CI->getArgOperand(0);
2545 auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2546 unsigned NumDstElts = DstTy->getNumElements();
2547 if (NumDstElts != SrcTy->getNumElements()) {
2548 assert(NumDstElts == 4 && "Unexpected vector size");
2549 Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1, 2, 3});
2550 }
2551 Rep = Builder.CreateBitCast(
2552 Rep, FixedVectorType::get(Type::getHalfTy(C), NumDstElts));
2553 Rep = Builder.CreateFPExt(Rep, DstTy, "cvtph2ps");
2554 if (CI->arg_size() >= 3)
2555 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2556 CI->getArgOperand(1));
2557 } else if (IsX86 && Name.startswith("avx512.mask.load")) {
2558 // "avx512.mask.loadu." or "avx512.mask.load."
2559 bool Aligned = Name[16] != 'u'; // "avx512.mask.loadu".
2560 Rep =
2561 UpgradeMaskedLoad(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
2562 CI->getArgOperand(2), Aligned);
2563 } else if (IsX86 && Name.startswith("avx512.mask.expand.load.")) {
2564 auto *ResultTy = cast<FixedVectorType>(CI->getType());
2565 Type *PtrTy = ResultTy->getElementType();
2566
2567 // Cast the pointer to element type.
2568 Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2569 llvm::PointerType::getUnqual(PtrTy));
2570
2571 Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2572 ResultTy->getNumElements());
2573
2574 Function *ELd = Intrinsic::getDeclaration(F->getParent(),
2575 Intrinsic::masked_expandload,
2576 ResultTy);
2577 Rep = Builder.CreateCall(ELd, { Ptr, MaskVec, CI->getOperand(1) });
2578 } else if (IsX86 && Name.startswith("avx512.mask.compress.store.")) {
2579 auto *ResultTy = cast<VectorType>(CI->getArgOperand(1)->getType());
2580 Type *PtrTy = ResultTy->getElementType();
2581
2582 // Cast the pointer to element type.
2583 Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2584 llvm::PointerType::getUnqual(PtrTy));
2585
2586 Value *MaskVec =
2587 getX86MaskVec(Builder, CI->getArgOperand(2),
2588 cast<FixedVectorType>(ResultTy)->getNumElements());
2589
2590 Function *CSt = Intrinsic::getDeclaration(F->getParent(),
2591 Intrinsic::masked_compressstore,
2592 ResultTy);
2593 Rep = Builder.CreateCall(CSt, { CI->getArgOperand(1), Ptr, MaskVec });
2594 } else if (IsX86 && (Name.startswith("avx512.mask.compress.") ||
2595 Name.startswith("avx512.mask.expand."))) {
2596 auto *ResultTy = cast<FixedVectorType>(CI->getType());
2597
2598 Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2599 ResultTy->getNumElements());
2600
2601 bool IsCompress = Name[12] == 'c';
2602 Intrinsic::ID IID = IsCompress ? Intrinsic::x86_avx512_mask_compress
2603 : Intrinsic::x86_avx512_mask_expand;
2604 Function *Intr = Intrinsic::getDeclaration(F->getParent(), IID, ResultTy);
2605 Rep = Builder.CreateCall(Intr, { CI->getOperand(0), CI->getOperand(1),
2606 MaskVec });
2607 } else if (IsX86 && Name.startswith("xop.vpcom")) {
2608 bool IsSigned;
2609 if (Name.endswith("ub") || Name.endswith("uw") || Name.endswith("ud") ||
2610 Name.endswith("uq"))
2611 IsSigned = false;
2612 else if (Name.endswith("b") || Name.endswith("w") || Name.endswith("d") ||
2613 Name.endswith("q"))
2614 IsSigned = true;
2615 else
2616 llvm_unreachable("Unknown suffix");
2617
2618 unsigned Imm;
2619 if (CI->arg_size() == 3) {
2620 Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2621 } else {
2622 Name = Name.substr(9); // strip off "xop.vpcom"
2623 if (Name.startswith("lt"))
2624 Imm = 0;
2625 else if (Name.startswith("le"))
2626 Imm = 1;
2627 else if (Name.startswith("gt"))
2628 Imm = 2;
2629 else if (Name.startswith("ge"))
2630 Imm = 3;
2631 else if (Name.startswith("eq"))
2632 Imm = 4;
2633 else if (Name.startswith("ne"))
2634 Imm = 5;
2635 else if (Name.startswith("false"))
2636 Imm = 6;
2637 else if (Name.startswith("true"))
2638 Imm = 7;
2639 else
2640 llvm_unreachable("Unknown condition");
2641 }
2642
2643 Rep = upgradeX86vpcom(Builder, *CI, Imm, IsSigned);
2644 } else if (IsX86 && Name.startswith("xop.vpcmov")) {
2645 Value *Sel = CI->getArgOperand(2);
2646 Value *NotSel = Builder.CreateNot(Sel);
2647 Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
2648 Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
2649 Rep = Builder.CreateOr(Sel0, Sel1);
2650 } else if (IsX86 && (Name.startswith("xop.vprot") ||
2651 Name.startswith("avx512.prol") ||
2652 Name.startswith("avx512.mask.prol"))) {
2653 Rep = upgradeX86Rotate(Builder, *CI, false);
2654 } else if (IsX86 && (Name.startswith("avx512.pror") ||
2655 Name.startswith("avx512.mask.pror"))) {
2656 Rep = upgradeX86Rotate(Builder, *CI, true);
2657 } else if (IsX86 && (Name.startswith("avx512.vpshld.") ||
2658 Name.startswith("avx512.mask.vpshld") ||
2659 Name.startswith("avx512.maskz.vpshld"))) {
2660 bool ZeroMask = Name[11] == 'z';
2661 Rep = upgradeX86ConcatShift(Builder, *CI, false, ZeroMask);
2662 } else if (IsX86 && (Name.startswith("avx512.vpshrd.") ||
2663 Name.startswith("avx512.mask.vpshrd") ||
2664 Name.startswith("avx512.maskz.vpshrd"))) {
2665 bool ZeroMask = Name[11] == 'z';
2666 Rep = upgradeX86ConcatShift(Builder, *CI, true, ZeroMask);
2667 } else if (IsX86 && Name == "sse42.crc32.64.8") {
2668 Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
2669 Intrinsic::x86_sse42_crc32_32_8);
2670 Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
2671 Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
2672 Rep = Builder.CreateZExt(Rep, CI->getType(), "");
2673 } else if (IsX86 && (Name.startswith("avx.vbroadcast.s") ||
2674 Name.startswith("avx512.vbroadcast.s"))) {
2675 // Replace broadcasts with a series of insertelements.
2676 auto *VecTy = cast<FixedVectorType>(CI->getType());
2677 Type *EltTy = VecTy->getElementType();
2678 unsigned EltNum = VecTy->getNumElements();
2679 Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
2680 EltTy->getPointerTo());
2681 Value *Load = Builder.CreateLoad(EltTy, Cast);
2682 Type *I32Ty = Type::getInt32Ty(C);
2683 Rep = PoisonValue::get(VecTy);
2684 for (unsigned I = 0; I < EltNum; ++I)
2685 Rep = Builder.CreateInsertElement(Rep, Load,
2686 ConstantInt::get(I32Ty, I));
2687 } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
2688 Name.startswith("sse41.pmovzx") ||
2689 Name.startswith("avx2.pmovsx") ||
2690 Name.startswith("avx2.pmovzx") ||
2691 Name.startswith("avx512.mask.pmovsx") ||
2692 Name.startswith("avx512.mask.pmovzx"))) {
2693 auto *DstTy = cast<FixedVectorType>(CI->getType());
2694 unsigned NumDstElts = DstTy->getNumElements();
2695
2696 // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
2697 SmallVector<int, 8> ShuffleMask(NumDstElts);
2698 for (unsigned i = 0; i != NumDstElts; ++i)
2699 ShuffleMask[i] = i;
2700
2701 Value *SV =
2702 Builder.CreateShuffleVector(CI->getArgOperand(0), ShuffleMask);
2703
2704 bool DoSext = (StringRef::npos != Name.find("pmovsx"));
2705 Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
2706 : Builder.CreateZExt(SV, DstTy);
2707 // If there are 3 arguments, it's a masked intrinsic so we need a select.
2708 if (CI->arg_size() == 3)
2709 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2710 CI->getArgOperand(1));
2711 } else if (Name == "avx512.mask.pmov.qd.256" ||
2712 Name == "avx512.mask.pmov.qd.512" ||
2713 Name == "avx512.mask.pmov.wb.256" ||
2714 Name == "avx512.mask.pmov.wb.512") {
2715 Type *Ty = CI->getArgOperand(1)->getType();
2716 Rep = Builder.CreateTrunc(CI->getArgOperand(0), Ty);
2717 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2718 CI->getArgOperand(1));
2719 } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
2720 Name == "avx2.vbroadcasti128")) {
2721 // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
2722 Type *EltTy = cast<VectorType>(CI->getType())->getElementType();
2723 unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
2724 auto *VT = FixedVectorType::get(EltTy, NumSrcElts);
2725 Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
2726 PointerType::getUnqual(VT));
2727 Value *Load = Builder.CreateAlignedLoad(VT, Op, Align(1));
2728 if (NumSrcElts == 2)
2729 Rep = Builder.CreateShuffleVector(Load, ArrayRef<int>{0, 1, 0, 1});
2730 else
2731 Rep = Builder.CreateShuffleVector(
2732 Load, ArrayRef<int>{0, 1, 2, 3, 0, 1, 2, 3});
2733 } else if (IsX86 && (Name.startswith("avx512.mask.shuf.i") ||
2734 Name.startswith("avx512.mask.shuf.f"))) {
2735 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2736 Type *VT = CI->getType();
2737 unsigned NumLanes = VT->getPrimitiveSizeInBits() / 128;
2738 unsigned NumElementsInLane = 128 / VT->getScalarSizeInBits();
2739 unsigned ControlBitsMask = NumLanes - 1;
2740 unsigned NumControlBits = NumLanes / 2;
2741 SmallVector<int, 8> ShuffleMask(0);
2742
2743 for (unsigned l = 0; l != NumLanes; ++l) {
2744 unsigned LaneMask = (Imm >> (l * NumControlBits)) & ControlBitsMask;
2745 // We actually need the other source.
2746 if (l >= NumLanes / 2)
2747 LaneMask += NumLanes;
2748 for (unsigned i = 0; i != NumElementsInLane; ++i)
2749 ShuffleMask.push_back(LaneMask * NumElementsInLane + i);
2750 }
2751 Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2752 CI->getArgOperand(1), ShuffleMask);
2753 Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2754 CI->getArgOperand(3));
2755 }else if (IsX86 && (Name.startswith("avx512.mask.broadcastf") ||
2756 Name.startswith("avx512.mask.broadcasti"))) {
2757 unsigned NumSrcElts =
2758 cast<FixedVectorType>(CI->getArgOperand(0)->getType())
2759 ->getNumElements();
2760 unsigned NumDstElts =
2761 cast<FixedVectorType>(CI->getType())->getNumElements();
2762
2763 SmallVector<int, 8> ShuffleMask(NumDstElts);
2764 for (unsigned i = 0; i != NumDstElts; ++i)
2765 ShuffleMask[i] = i % NumSrcElts;
2766
2767 Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2768 CI->getArgOperand(0),
2769 ShuffleMask);
2770 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2771 CI->getArgOperand(1));
2772 } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
2773 Name.startswith("avx2.vbroadcast") ||
2774 Name.startswith("avx512.pbroadcast") ||
2775 Name.startswith("avx512.mask.broadcast.s"))) {
2776 // Replace vp?broadcasts with a vector shuffle.
2777 Value *Op = CI->getArgOperand(0);
2778 ElementCount EC = cast<VectorType>(CI->getType())->getElementCount();
2779 Type *MaskTy = VectorType::get(Type::getInt32Ty(C), EC);
2780 SmallVector<int, 8> M;
2781 ShuffleVectorInst::getShuffleMask(Constant::getNullValue(MaskTy), M);
2782 Rep = Builder.CreateShuffleVector(Op, M);
2783
2784 if (CI->arg_size() == 3)
2785 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2786 CI->getArgOperand(1));
2787 } else if (IsX86 && (Name.startswith("sse2.padds.") ||
2788 Name.startswith("avx2.padds.") ||
2789 Name.startswith("avx512.padds.") ||
2790 Name.startswith("avx512.mask.padds."))) {
2791 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::sadd_sat);
2792 } else if (IsX86 && (Name.startswith("sse2.psubs.") ||
2793 Name.startswith("avx2.psubs.") ||
2794 Name.startswith("avx512.psubs.") ||
2795 Name.startswith("avx512.mask.psubs."))) {
2796 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::ssub_sat);
2797 } else if (IsX86 && (Name.startswith("sse2.paddus.") ||
2798 Name.startswith("avx2.paddus.") ||
2799 Name.startswith("avx512.mask.paddus."))) {
2800 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::uadd_sat);
2801 } else if (IsX86 && (Name.startswith("sse2.psubus.") ||
2802 Name.startswith("avx2.psubus.") ||
2803 Name.startswith("avx512.mask.psubus."))) {
2804 Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::usub_sat);
2805 } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
2806 Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2807 CI->getArgOperand(1),
2808 CI->getArgOperand(2),
2809 CI->getArgOperand(3),
2810 CI->getArgOperand(4),
2811 false);
2812 } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
2813 Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2814 CI->getArgOperand(1),
2815 CI->getArgOperand(2),
2816 CI->getArgOperand(3),
2817 CI->getArgOperand(4),
2818 true);
2819 } else if (IsX86 && (Name == "sse2.psll.dq" ||
2820 Name == "avx2.psll.dq")) {
2821 // 128/256-bit shift left specified in bits.
2822 unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2823 Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
2824 Shift / 8); // Shift is in bits.
2825 } else if (IsX86 && (Name == "sse2.psrl.dq" ||
2826 Name == "avx2.psrl.dq")) {
2827 // 128/256-bit shift right specified in bits.
2828 unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2829 Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
2830 Shift / 8); // Shift is in bits.
2831 } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
2832 Name == "avx2.psll.dq.bs" ||
2833 Name == "avx512.psll.dq.512")) {
2834 // 128/256/512-bit shift left specified in bytes.
2835 unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2836 Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2837 } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
2838 Name == "avx2.psrl.dq.bs" ||
2839 Name == "avx512.psrl.dq.512")) {
2840 // 128/256/512-bit shift right specified in bytes.
2841 unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2842 Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2843 } else if (IsX86 && (Name == "sse41.pblendw" ||
2844 Name.startswith("sse41.blendp") ||
2845 Name.startswith("avx.blend.p") ||
2846 Name == "avx2.pblendw" ||
2847 Name.startswith("avx2.pblendd."))) {
2848 Value *Op0 = CI->getArgOperand(0);
2849 Value *Op1 = CI->getArgOperand(1);
2850 unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2851 auto *VecTy = cast<FixedVectorType>(CI->getType());
2852 unsigned NumElts = VecTy->getNumElements();
2853
2854 SmallVector<int, 16> Idxs(NumElts);
2855 for (unsigned i = 0; i != NumElts; ++i)
2856 Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
2857
2858 Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2859 } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
2860 Name == "avx2.vinserti128" ||
2861 Name.startswith("avx512.mask.insert"))) {
2862 Value *Op0 = CI->getArgOperand(0);
2863 Value *Op1 = CI->getArgOperand(1);
2864 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2865 unsigned DstNumElts =
2866 cast<FixedVectorType>(CI->getType())->getNumElements();
2867 unsigned SrcNumElts =
2868 cast<FixedVectorType>(Op1->getType())->getNumElements();
2869 unsigned Scale = DstNumElts / SrcNumElts;
2870
2871 // Mask off the high bits of the immediate value; hardware ignores those.
2872 Imm = Imm % Scale;
2873
2874 // Extend the second operand into a vector the size of the destination.
2875 SmallVector<int, 8> Idxs(DstNumElts);
2876 for (unsigned i = 0; i != SrcNumElts; ++i)
2877 Idxs[i] = i;
2878 for (unsigned i = SrcNumElts; i != DstNumElts; ++i)
2879 Idxs[i] = SrcNumElts;
2880 Rep = Builder.CreateShuffleVector(Op1, Idxs);
2881
2882 // Insert the second operand into the first operand.
2883
2884 // Note that there is no guarantee that instruction lowering will actually
2885 // produce a vinsertf128 instruction for the created shuffles. In
2886 // particular, the 0 immediate case involves no lane changes, so it can
2887 // be handled as a blend.
2888
2889 // Example of shuffle mask for 32-bit elements:
2890 // Imm = 1 <i32 0, i32 1, i32 2, i32 3, i32 8, i32 9, i32 10, i32 11>
2891 // Imm = 0 <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6, i32 7 >
2892
2893 // First fill with identify mask.
2894 for (unsigned i = 0; i != DstNumElts; ++i)
2895 Idxs[i] = i;
2896 // Then replace the elements where we need to insert.
2897 for (unsigned i = 0; i != SrcNumElts; ++i)
2898 Idxs[i + Imm * SrcNumElts] = i + DstNumElts;
2899 Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
2900
2901 // If the intrinsic has a mask operand, handle that.
2902 if (CI->arg_size() == 5)
2903 Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2904 CI->getArgOperand(3));
2905 } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
2906 Name == "avx2.vextracti128" ||
2907 Name.startswith("avx512.mask.vextract"))) {
2908 Value *Op0 = CI->getArgOperand(0);
2909 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2910 unsigned DstNumElts =
2911 cast<FixedVectorType>(CI->getType())->getNumElements();
2912 unsigned SrcNumElts =
2913 cast<FixedVectorType>(Op0->getType())->getNumElements();
2914 unsigned Scale = SrcNumElts / DstNumElts;
2915
2916 // Mask off the high bits of the immediate value; hardware ignores those.
2917 Imm = Imm % Scale;
2918
2919 // Get indexes for the subvector of the input vector.
2920 SmallVector<int, 8> Idxs(DstNumElts);
2921 for (unsigned i = 0; i != DstNumElts; ++i) {
2922 Idxs[i] = i + (Imm * DstNumElts);
2923 }
2924 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2925
2926 // If the intrinsic has a mask operand, handle that.
2927 if (CI->arg_size() == 4)
2928 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2929 CI->getArgOperand(2));
2930 } else if (!IsX86 && Name == "stackprotectorcheck") {
2931 Rep = nullptr;
2932 } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
2933 Name.startswith("avx512.mask.perm.di."))) {
2934 Value *Op0 = CI->getArgOperand(0);
2935 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2936 auto *VecTy = cast<FixedVectorType>(CI->getType());
2937 unsigned NumElts = VecTy->getNumElements();
2938
2939 SmallVector<int, 8> Idxs(NumElts);
2940 for (unsigned i = 0; i != NumElts; ++i)
2941 Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
2942
2943 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2944
2945 if (CI->arg_size() == 4)
2946 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2947 CI->getArgOperand(2));
2948 } else if (IsX86 && (Name.startswith("avx.vperm2f128.") ||
2949 Name == "avx2.vperm2i128")) {
2950 // The immediate permute control byte looks like this:
2951 // [1:0] - select 128 bits from sources for low half of destination
2952 // [2] - ignore
2953 // [3] - zero low half of destination
2954 // [5:4] - select 128 bits from sources for high half of destination
2955 // [6] - ignore
2956 // [7] - zero high half of destination
2957
2958 uint8_t Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2959
2960 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2961 unsigned HalfSize = NumElts / 2;
2962 SmallVector<int, 8> ShuffleMask(NumElts);
2963
2964 // Determine which operand(s) are actually in use for this instruction.
2965 Value *V0 = (Imm & 0x02) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2966 Value *V1 = (Imm & 0x20) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2967
2968 // If needed, replace operands based on zero mask.
2969 V0 = (Imm & 0x08) ? ConstantAggregateZero::get(CI->getType()) : V0;
2970 V1 = (Imm & 0x80) ? ConstantAggregateZero::get(CI->getType()) : V1;
2971
2972 // Permute low half of result.
2973 unsigned StartIndex = (Imm & 0x01) ? HalfSize : 0;
2974 for (unsigned i = 0; i < HalfSize; ++i)
2975 ShuffleMask[i] = StartIndex + i;
2976
2977 // Permute high half of result.
2978 StartIndex = (Imm & 0x10) ? HalfSize : 0;
2979 for (unsigned i = 0; i < HalfSize; ++i)
2980 ShuffleMask[i + HalfSize] = NumElts + StartIndex + i;
2981
2982 Rep = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2983
2984 } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
2985 Name == "sse2.pshuf.d" ||
2986 Name.startswith("avx512.mask.vpermil.p") ||
2987 Name.startswith("avx512.mask.pshuf.d."))) {
2988 Value *Op0 = CI->getArgOperand(0);
2989 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2990 auto *VecTy = cast<FixedVectorType>(CI->getType());
2991 unsigned NumElts = VecTy->getNumElements();
2992 // Calculate the size of each index in the immediate.
2993 unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
2994 unsigned IdxMask = ((1 << IdxSize) - 1);
2995
2996 SmallVector<int, 8> Idxs(NumElts);
2997 // Lookup the bits for this element, wrapping around the immediate every
2998 // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
2999 // to offset by the first index of each group.
3000 for (unsigned i = 0; i != NumElts; ++i)
3001 Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
3002
3003 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
3004
3005 if (CI->arg_size() == 4)
3006 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3007 CI->getArgOperand(2));
3008 } else if (IsX86 && (Name == "sse2.pshufl.w" ||
3009 Name.startswith("avx512.mask.pshufl.w."))) {
3010 Value *Op0 = CI->getArgOperand(0);
3011 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
3012 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3013
3014 SmallVector<int, 16> Idxs(NumElts);
3015 for (unsigned l = 0; l != NumElts; l += 8) {
3016 for (unsigned i = 0; i != 4; ++i)
3017 Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
3018 for (unsigned i = 4; i != 8; ++i)
3019 Idxs[i + l] = i + l;
3020 }
3021
3022 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
3023
3024 if (CI->arg_size() == 4)
3025 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3026 CI->getArgOperand(2));
3027 } else if (IsX86 && (Name == "sse2.pshufh.w" ||
3028 Name.startswith("avx512.mask.pshufh.w."))) {
3029 Value *Op0 = CI->getArgOperand(0);
3030 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
3031 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3032
3033 SmallVector<int, 16> Idxs(NumElts);
3034 for (unsigned l = 0; l != NumElts; l += 8) {
3035 for (unsigned i = 0; i != 4; ++i)
3036 Idxs[i + l] = i + l;
3037 for (unsigned i = 0; i != 4; ++i)
3038 Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
3039 }
3040
3041 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
3042
3043 if (CI->arg_size() == 4)
3044 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3045 CI->getArgOperand(2));
3046 } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
3047 Value *Op0 = CI->getArgOperand(0);
3048 Value *Op1 = CI->getArgOperand(1);
3049 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
3050 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3051
3052 unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
3053 unsigned HalfLaneElts = NumLaneElts / 2;
3054
3055 SmallVector<int, 16> Idxs(NumElts);
3056 for (unsigned i = 0; i != NumElts; ++i) {
3057 // Base index is the starting element of the lane.
3058 Idxs[i] = i - (i % NumLaneElts);
3059 // If we are half way through the lane switch to the other source.
3060 if ((i % NumLaneElts) >= HalfLaneElts)
3061 Idxs[i] += NumElts;
3062 // Now select the specific element. By adding HalfLaneElts bits from
3063 // the immediate. Wrapping around the immediate every 8-bits.
3064 Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
3065 }
3066
3067 Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
3068
3069 Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
3070 CI->getArgOperand(3));
3071 } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
3072 Name.startswith("avx512.mask.movshdup") ||
3073 Name.startswith("avx512.mask.movsldup"))) {
3074 Value *Op0 = CI->getArgOperand(0);
3075 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3076 unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
3077
3078 unsigned Offset = 0;
3079 if (Name.startswith("avx512.mask.movshdup."))
3080 Offset = 1;
3081
3082 SmallVector<int, 16> Idxs(NumElts);
3083 for (unsigned l = 0; l != NumElts; l += NumLaneElts)
3084 for (unsigned i = 0; i != NumLaneElts; i += 2) {
3085 Idxs[i + l + 0] = i + l + Offset;
3086 Idxs[i + l + 1] = i + l + Offset;
3087 }
3088
3089 Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
3090
3091 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
3092 CI->getArgOperand(1));
3093 } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
3094 Name.startswith("avx512.mask.unpckl."))) {
3095 Value *Op0 = CI->getArgOperand(0);
3096 Value *Op1 = CI->getArgOperand(1);
3097 int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3098 int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
3099
3100 SmallVector<int, 64> Idxs(NumElts);
3101 for (int l = 0; l != NumElts; l += NumLaneElts)
3102 for (int i = 0; i != NumLaneElts; ++i)
3103 Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
3104
3105 Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
3106
3107 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3108 CI->getArgOperand(2));
3109 } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
3110 Name.startswith("avx512.mask.unpckh."))) {
3111 Value *Op0 = CI->getArgOperand(0);
3112 Value *Op1 = CI->getArgOperand(1);
3113 int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3114 int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
3115
3116 SmallVector<int, 64> Idxs(NumElts);
3117 for (int l = 0; l != NumElts; l += NumLaneElts)
3118 for (int i = 0; i != NumLaneElts; ++i)
3119 Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
3120
3121 Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
3122
3123 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3124 CI->getArgOperand(2));
3125 } else if (IsX86 && (Name.startswith("avx512.mask.and.") ||
3126 Name.startswith("avx512.mask.pand."))) {
3127 VectorType *FTy = cast<VectorType>(CI->getType());
3128 VectorType *ITy = VectorType::getInteger(FTy);
3129 Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
3130 Builder.CreateBitCast(CI->getArgOperand(1), ITy));
3131 Rep = Builder.CreateBitCast(Rep, FTy);
3132 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3133 CI->getArgOperand(2));
3134 } else if (IsX86 && (Name.startswith("avx512.mask.andn.") ||
3135 Name.startswith("avx512.mask.pandn."))) {
3136 VectorType *FTy = cast<VectorType>(CI->getType());
3137 VectorType *ITy = VectorType::getInteger(FTy);
3138 Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
3139 Rep = Builder.CreateAnd(Rep,
3140 Builder.CreateBitCast(CI->getArgOperand(1), ITy));
3141 Rep = Builder.CreateBitCast(Rep, FTy);
3142 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3143 CI->getArgOperand(2));
3144 } else if (IsX86 && (Name.startswith("avx512.mask.or.") ||
3145 Name.startswith("avx512.mask.por."))) {
3146 VectorType *FTy = cast<VectorType>(CI->getType());
3147 VectorType *ITy = VectorType::getInteger(FTy);
3148 Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
3149 Builder.CreateBitCast(CI->getArgOperand(1), ITy));
3150 Rep = Builder.CreateBitCast(Rep, FTy);
3151 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3152 CI->getArgOperand(2));
3153 } else if (IsX86 && (Name.startswith("avx512.mask.xor.") ||
3154 Name.startswith("avx512.mask.pxor."))) {
3155 VectorType *FTy = cast<VectorType>(CI->getType());
3156 VectorType *ITy = VectorType::getInteger(FTy);
3157 Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
3158 Builder.CreateBitCast(CI->getArgOperand(1), ITy));
3159 Rep = Builder.CreateBitCast(Rep, FTy);
3160 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3161 CI->getArgOperand(2));
3162 } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
3163 Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
3164 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3165 CI->getArgOperand(2));
3166 } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
3167 Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
3168 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3169 CI->getArgOperand(2));
3170 } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
3171 Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
3172 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3173 CI->getArgOperand(2));
3174 } else if (IsX86 && Name.startswith("avx512.mask.add.p")) {
3175 if (Name.endswith(".512")) {
3176 Intrinsic::ID IID;
3177 if (Name[17] == 's')
3178 IID = Intrinsic::x86_avx512_add_ps_512;
3179 else
3180 IID = Intrinsic::x86_avx512_add_pd_512;
3181
3182 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3183 { CI->getArgOperand(0), CI->getArgOperand(1),
3184 CI->getArgOperand(4) });
3185 } else {
3186 Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
3187 }
3188 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3189 CI->getArgOperand(2));
3190 } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
3191 if (Name.endswith(".512")) {
3192 Intrinsic::ID IID;
3193 if (Name[17] == 's')
3194 IID = Intrinsic::x86_avx512_div_ps_512;
3195 else
3196 IID = Intrinsic::x86_avx512_div_pd_512;
3197
3198 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3199 { CI->getArgOperand(0), CI->getArgOperand(1),
3200 CI->getArgOperand(4) });
3201 } else {
3202 Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
3203 }
3204 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3205 CI->getArgOperand(2));
3206 } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
3207 if (Name.endswith(".512")) {
3208 Intrinsic::ID IID;
3209 if (Name[17] == 's')
3210 IID = Intrinsic::x86_avx512_mul_ps_512;
3211 else
3212 IID = Intrinsic::x86_avx512_mul_pd_512;
3213
3214 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3215 { CI->getArgOperand(0), CI->getArgOperand(1),
3216 CI->getArgOperand(4) });
3217 } else {
3218 Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
3219 }
3220 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3221 CI->getArgOperand(2));
3222 } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
3223 if (Name.endswith(".512")) {
3224 Intrinsic::ID IID;
3225 if (Name[17] == 's')
3226 IID = Intrinsic::x86_avx512_sub_ps_512;
3227 else
3228 IID = Intrinsic::x86_avx512_sub_pd_512;
3229
3230 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3231 { CI->getArgOperand(0), CI->getArgOperand(1),
3232 CI->getArgOperand(4) });
3233 } else {
3234 Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
3235 }
3236 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3237 CI->getArgOperand(2));
3238 } else if (IsX86 && (Name.startswith("avx512.mask.max.p") ||
3239 Name.startswith("avx512.mask.min.p")) &&
3240 Name.drop_front(18) == ".512") {
3241 bool IsDouble = Name[17] == 'd';
3242 bool IsMin = Name[13] == 'i';
3243 static const Intrinsic::ID MinMaxTbl[2][2] = {
3244 { Intrinsic::x86_avx512_max_ps_512, Intrinsic::x86_avx512_max_pd_512 },
3245 { Intrinsic::x86_avx512_min_ps_512, Intrinsic::x86_avx512_min_pd_512 }
3246 };
3247 Intrinsic::ID IID = MinMaxTbl[IsMin][IsDouble];
3248
3249 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3250 { CI->getArgOperand(0), CI->getArgOperand(1),
3251 CI->getArgOperand(4) });
3252 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
3253 CI->getArgOperand(2));
3254 } else if (IsX86 && Name.startswith("avx512.mask.lzcnt.")) {
3255 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
3256 Intrinsic::ctlz,
3257 CI->getType()),
3258 { CI->getArgOperand(0), Builder.getInt1(false) });
3259 Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
3260 CI->getArgOperand(1));
3261 } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
3262 bool IsImmediate = Name[16] == 'i' ||
3263 (Name.size() > 18 && Name[18] == 'i');
3264 bool IsVariable = Name[16] == 'v';
3265 char Size = Name[16] == '.' ? Name[17] :
3266 Name[17] == '.' ? Name[18] :
3267 Name[18] == '.' ? Name[19] :
3268 Name[20];
3269
3270 Intrinsic::ID IID;
3271 if (IsVariable && Name[17] != '.') {
3272 if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
3273 IID = Intrinsic::x86_avx2_psllv_q;
3274 else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
3275 IID = Intrinsic::x86_avx2_psllv_q_256;
3276 else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
3277 IID = Intrinsic::x86_avx2_psllv_d;
3278 else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
3279 IID = Intrinsic::x86_avx2_psllv_d_256;
3280 else if (Size == 'h' && Name[17] == '8') // avx512.mask.psllv8.hi
3281 IID = Intrinsic::x86_avx512_psllv_w_128;
3282 else if (Size == 'h' && Name[17] == '1') // avx512.mask.psllv16.hi
3283 IID = Intrinsic::x86_avx512_psllv_w_256;
3284 else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psllv32hi
3285 IID = Intrinsic::x86_avx512_psllv_w_512;
3286 else
3287 llvm_unreachable("Unexpected size");
3288 } else if (Name.endswith(".128")) {
3289 if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
3290 IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
3291 : Intrinsic::x86_sse2_psll_d;
3292 else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
3293 IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
3294 : Intrinsic::x86_sse2_psll_q;
3295 else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
3296 IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
3297 : Intrinsic::x86_sse2_psll_w;
3298 else
3299 llvm_unreachable("Unexpected size");
3300 } else if (Name.endswith(".256")) {
3301 if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
3302 IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
3303 : Intrinsic::x86_avx2_psll_d;
3304 else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
3305 IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
3306 : Intrinsic::x86_avx2_psll_q;
3307 else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
3308 IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
3309 : Intrinsic::x86_avx2_psll_w;
3310 else
3311 llvm_unreachable("Unexpected size");
3312 } else {
3313 if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
3314 IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
3315 IsVariable ? Intrinsic::x86_avx512_psllv_d_512 :
3316 Intrinsic::x86_avx512_psll_d_512;
3317 else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
3318 IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
3319 IsVariable ? Intrinsic::x86_avx512_psllv_q_512 :
3320 Intrinsic::x86_avx512_psll_q_512;
3321 else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
3322 IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
3323 : Intrinsic::x86_avx512_psll_w_512;
3324 else
3325 llvm_unreachable("Unexpected size");
3326 }
3327
3328 Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3329 } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
3330 bool IsImmediate = Name[16] == 'i' ||
3331 (Name.size() > 18 && Name[18] == 'i');
3332 bool IsVariable = Name[16] == 'v';
3333 char Size = Name[16] == '.' ? Name[17] :
3334 Name[17] == '.' ? Name[18] :
3335 Name[18] == '.' ? Name[19] :
3336 Name[20];
3337
3338 Intrinsic::ID IID;
3339 if (IsVariable && Name[17] != '.') {
3340 if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
3341 IID = Intrinsic::x86_avx2_psrlv_q;
3342 else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
3343 IID = Intrinsic::x86_avx2_psrlv_q_256;
3344 else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
3345 IID = Intrinsic::x86_avx2_psrlv_d;
3346 else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
3347 IID = Intrinsic::x86_avx2_psrlv_d_256;
3348 else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrlv8.hi
3349 IID = Intrinsic::x86_avx512_psrlv_w_128;
3350 else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrlv16.hi
3351 IID = Intrinsic::x86_avx512_psrlv_w_256;
3352 else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrlv32hi
3353 IID = Intrinsic::x86_avx512_psrlv_w_512;
3354 else
3355 llvm_unreachable("Unexpected size");
3356 } else if (Name.endswith(".128")) {
3357 if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
3358 IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
3359 : Intrinsic::x86_sse2_psrl_d;
3360 else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
3361 IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
3362 : Intrinsic::x86_sse2_psrl_q;
3363 else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
3364 IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
3365 : Intrinsic::x86_sse2_psrl_w;
3366 else
3367 llvm_unreachable("Unexpected size");
3368 } else if (Name.endswith(".256")) {
3369 if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
3370 IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
3371 : Intrinsic::x86_avx2_psrl_d;
3372 else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
3373 IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
3374 : Intrinsic::x86_avx2_psrl_q;
3375 else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
3376 IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
3377 : Intrinsic::x86_avx2_psrl_w;
3378 else
3379 llvm_unreachable("Unexpected size");
3380 } else {
3381 if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
3382 IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
3383 IsVariable ? Intrinsic::x86_avx512_psrlv_d_512 :
3384 Intrinsic::x86_avx512_psrl_d_512;
3385 else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
3386 IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
3387 IsVariable ? Intrinsic::x86_avx512_psrlv_q_512 :
3388 Intrinsic::x86_avx512_psrl_q_512;
3389 else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
3390 IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
3391 : Intrinsic::x86_avx512_psrl_w_512;
3392 else
3393 llvm_unreachable("Unexpected size");
3394 }
3395
3396 Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3397 } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
3398 bool IsImmediate = Name[16] == 'i' ||
3399 (Name.size() > 18 && Name[18] == 'i');
3400 bool IsVariable = Name[16] == 'v';
3401 char Size = Name[16] == '.' ? Name[17] :
3402 Name[17] == '.' ? Name[18] :
3403 Name[18] == '.' ? Name[19] :
3404 Name[20];
3405
3406 Intrinsic::ID IID;
3407 if (IsVariable && Name[17] != '.') {
3408 if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
3409 IID = Intrinsic::x86_avx2_psrav_d;
3410 else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
3411 IID = Intrinsic::x86_avx2_psrav_d_256;
3412 else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrav8.hi
3413 IID = Intrinsic::x86_avx512_psrav_w_128;
3414 else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrav16.hi
3415 IID = Intrinsic::x86_avx512_psrav_w_256;
3416 else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrav32hi
3417 IID = Intrinsic::x86_avx512_psrav_w_512;
3418 else
3419 llvm_unreachable("Unexpected size");
3420 } else if (Name.endswith(".128")) {
3421 if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
3422 IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
3423 : Intrinsic::x86_sse2_psra_d;
3424 else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
3425 IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
3426 IsVariable ? Intrinsic::x86_avx512_psrav_q_128 :
3427 Intrinsic::x86_avx512_psra_q_128;
3428 else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
3429 IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
3430 : Intrinsic::x86_sse2_psra_w;
3431 else
3432 llvm_unreachable("Unexpected size");
3433 } else if (Name.endswith(".256")) {
3434 if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
3435 IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
3436 : Intrinsic::x86_avx2_psra_d;
3437 else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
3438 IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
3439 IsVariable ? Intrinsic::x86_avx512_psrav_q_256 :
3440 Intrinsic::x86_avx512_psra_q_256;
3441 else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
3442 IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
3443 : Intrinsic::x86_avx2_psra_w;
3444 else
3445 llvm_unreachable("Unexpected size");
3446 } else {
3447 if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
3448 IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
3449 IsVariable ? Intrinsic::x86_avx512_psrav_d_512 :
3450 Intrinsic::x86_avx512_psra_d_512;
3451 else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
3452 IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
3453 IsVariable ? Intrinsic::x86_avx512_psrav_q_512 :
3454 Intrinsic::x86_avx512_psra_q_512;
3455 else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
3456 IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
3457 : Intrinsic::x86_avx512_psra_w_512;
3458 else
3459 llvm_unreachable("Unexpected size");
3460 }
3461
3462 Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3463 } else if (IsX86 && Name.startswith("avx512.mask.move.s")) {
3464 Rep = upgradeMaskedMove(Builder, *CI);
3465 } else if (IsX86 && Name.startswith("avx512.cvtmask2")) {
3466 Rep = UpgradeMaskToInt(Builder, *CI);
3467 } else if (IsX86 && Name.endswith(".movntdqa")) {
3468 Module *M = F->getParent();
3469 MDNode *Node = MDNode::get(
3470 C, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
3471
3472 Value *Ptr = CI->getArgOperand(0);
3473
3474 // Convert the type of the pointer to a pointer to the stored type.
3475 Value *BC = Builder.CreateBitCast(
3476 Ptr, PointerType::getUnqual(CI->getType()), "cast");
3477 LoadInst *LI = Builder.CreateAlignedLoad(
3478 CI->getType(), BC,
3479 Align(CI->getType()->getPrimitiveSizeInBits().getFixedValue() / 8));
3480 LI->setMetadata(M->getMDKindID("nontemporal"), Node);
3481 Rep = LI;
3482 } else if (IsX86 && (Name.startswith("fma.vfmadd.") ||
3483 Name.startswith("fma.vfmsub.") ||
3484 Name.startswith("fma.vfnmadd.") ||
3485 Name.startswith("fma.vfnmsub."))) {
3486 bool NegMul = Name[6] == 'n';
3487 bool NegAcc = NegMul ? Name[8] == 's' : Name[7] == 's';
3488 bool IsScalar = NegMul ? Name[12] == 's' : Name[11] == 's';
3489
3490 Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3491 CI->getArgOperand(2) };
3492
3493 if (IsScalar) {
3494 Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3495 Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3496 Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3497 }
3498
3499 if (NegMul && !IsScalar)
3500 Ops[0] = Builder.CreateFNeg(Ops[0]);
3501 if (NegMul && IsScalar)
3502 Ops[1] = Builder.CreateFNeg(Ops[1]);
3503 if (NegAcc)
3504 Ops[2] = Builder.CreateFNeg(Ops[2]);
3505
3506 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3507 Intrinsic::fma,
3508 Ops[0]->getType()),
3509 Ops);
3510
3511 if (IsScalar)
3512 Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep,
3513 (uint64_t)0);
3514 } else if (IsX86 && Name.startswith("fma4.vfmadd.s")) {
3515 Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3516 CI->getArgOperand(2) };
3517
3518 Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3519 Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3520 Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3521
3522 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3523 Intrinsic::fma,
3524 Ops[0]->getType()),
3525 Ops);
3526
3527 Rep = Builder.CreateInsertElement(Constant::getNullValue(CI->getType()),
3528 Rep, (uint64_t)0);
3529 } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.s") ||
3530 Name.startswith("avx512.maskz.vfmadd.s") ||
3531 Name.startswith("avx512.mask3.vfmadd.s") ||
3532 Name.startswith("avx512.mask3.vfmsub.s") ||
3533 Name.startswith("avx512.mask3.vfnmsub.s"))) {
3534 bool IsMask3 = Name[11] == '3';
3535 bool IsMaskZ = Name[11] == 'z';
3536 // Drop the "avx512.mask." to make it easier.
3537 Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3538 bool NegMul = Name[2] == 'n';
3539 bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3540
3541 Value *A = CI->getArgOperand(0);
3542 Value *B = CI->getArgOperand(1);
3543 Value *C = CI->getArgOperand(2);
3544
3545 if (NegMul && (IsMask3 || IsMaskZ))
3546 A = Builder.CreateFNeg(A);
3547 if (NegMul && !(IsMask3 || IsMaskZ))
3548 B = Builder.CreateFNeg(B);
3549 if (NegAcc)
3550 C = Builder.CreateFNeg(C);
3551
3552 A = Builder.CreateExtractElement(A, (uint64_t)0);
3553 B = Builder.CreateExtractElement(B, (uint64_t)0);
3554 C = Builder.CreateExtractElement(C, (uint64_t)0);
3555
3556 if (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3557 cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4) {
3558 Value *Ops[] = { A, B, C, CI->getArgOperand(4) };
3559
3560 Intrinsic::ID IID;
3561 if (Name.back() == 'd')
3562 IID = Intrinsic::x86_avx512_vfmadd_f64;
3563 else
3564 IID = Intrinsic::x86_avx512_vfmadd_f32;
3565 Function *FMA = Intrinsic::getDeclaration(CI->getModule(), IID);
3566 Rep = Builder.CreateCall(FMA, Ops);
3567 } else {
3568 Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3569 Intrinsic::fma,
3570 A->getType());
3571 Rep = Builder.CreateCall(FMA, { A, B, C });
3572 }
3573
3574 Value *PassThru = IsMaskZ ? Constant::getNullValue(Rep->getType()) :
3575 IsMask3 ? C : A;
3576
3577 // For Mask3 with NegAcc, we need to create a new extractelement that
3578 // avoids the negation above.
3579 if (NegAcc && IsMask3)
3580 PassThru = Builder.CreateExtractElement(CI->getArgOperand(2),
3581 (uint64_t)0);
3582
3583 Rep = EmitX86ScalarSelect(Builder, CI->getArgOperand(3),
3584 Rep, PassThru);
3585 Rep = Builder.CreateInsertElement(CI->getArgOperand(IsMask3 ? 2 : 0),
3586 Rep, (uint64_t)0);
3587 } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.p") ||
3588 Name.startswith("avx512.mask.vfnmadd.p") ||
3589 Name.startswith("avx512.mask.vfnmsub.p") ||
3590 Name.startswith("avx512.mask3.vfmadd.p") ||
3591 Name.startswith("avx512.mask3.vfmsub.p") ||
3592 Name.startswith("avx512.mask3.vfnmsub.p") ||
3593 Name.startswith("avx512.maskz.vfmadd.p"))) {
3594 bool IsMask3 = Name[11] == '3';
3595 bool IsMaskZ = Name[11] == 'z';
3596 // Drop the "avx512.mask." to make it easier.
3597 Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3598 bool NegMul = Name[2] == 'n';
3599 bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3600
3601 Value *A = CI->getArgOperand(0);
3602 Value *B = CI->getArgOperand(1);
3603 Value *C = CI->getArgOperand(2);
3604
3605 if (NegMul && (IsMask3 || IsMaskZ))
3606 A = Builder.CreateFNeg(A);
3607 if (NegMul && !(IsMask3 || IsMaskZ))
3608 B = Builder.CreateFNeg(B);
3609 if (NegAcc)
3610 C = Builder.CreateFNeg(C);
3611
3612 if (CI->arg_size() == 5 &&
3613 (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3614 cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4)) {
3615 Intrinsic::ID IID;
3616 // Check the character before ".512" in string.
3617 if (Name[Name.size()-5] == 's')
3618 IID = Intrinsic::x86_avx512_vfmadd_ps_512;
3619 else
3620 IID = Intrinsic::x86_avx512_vfmadd_pd_512;
3621
3622 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3623 { A, B, C, CI->getArgOperand(4) });
3624 } else {
3625 Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3626 Intrinsic::fma,
3627 A->getType());
3628 Rep = Builder.CreateCall(FMA, { A, B, C });
3629 }
3630
3631 Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3632 IsMask3 ? CI->getArgOperand(2) :
3633 CI->getArgOperand(0);
3634
3635 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3636 } else if (IsX86 && Name.startswith("fma.vfmsubadd.p")) {
3637 unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3638 unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3639 Intrinsic::ID IID;
3640 if (VecWidth == 128 && EltWidth == 32)
3641 IID = Intrinsic::x86_fma_vfmaddsub_ps;
3642 else if (VecWidth == 256 && EltWidth == 32)
3643 IID = Intrinsic::x86_fma_vfmaddsub_ps_256;
3644 else if (VecWidth == 128 && EltWidth == 64)
3645 IID = Intrinsic::x86_fma_vfmaddsub_pd;
3646 else if (VecWidth == 256 && EltWidth == 64)
3647 IID = Intrinsic::x86_fma_vfmaddsub_pd_256;
3648 else
3649 llvm_unreachable("Unexpected intrinsic");
3650
3651 Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3652 CI->getArgOperand(2) };
3653 Ops[2] = Builder.CreateFNeg(Ops[2]);
3654 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3655 Ops);
3656 } else if (IsX86 && (Name.startswith("avx512.mask.vfmaddsub.p") ||
3657 Name.startswith("avx512.mask3.vfmaddsub.p") ||
3658 Name.startswith("avx512.maskz.vfmaddsub.p") ||
3659 Name.startswith("avx512.mask3.vfmsubadd.p"))) {
3660 bool IsMask3 = Name[11] == '3';
3661 bool IsMaskZ = Name[11] == 'z';
3662 // Drop the "avx512.mask." to make it easier.
3663 Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3664 bool IsSubAdd = Name[3] == 's';
3665 if (CI->arg_size() == 5) {
3666 Intrinsic::ID IID;
3667 // Check the character before ".512" in string.
3668 if (Name[Name.size()-5] == 's')
3669 IID = Intrinsic::x86_avx512_vfmaddsub_ps_512;
3670 else
3671 IID = Intrinsic::x86_avx512_vfmaddsub_pd_512;
3672
3673 Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3674 CI->getArgOperand(2), CI->getArgOperand(4) };
3675 if (IsSubAdd)
3676 Ops[2] = Builder.CreateFNeg(Ops[2]);
3677
3678 Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3679 Ops);
3680 } else {
3681 int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3682
3683 Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3684 CI->getArgOperand(2) };
3685
3686 Function *FMA = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::fma,
3687 Ops[0]->getType());
3688 Value *Odd = Builder.CreateCall(FMA, Ops);
3689 Ops[2] = Builder.CreateFNeg(Ops[2]);
3690 Value *Even = Builder.CreateCall(FMA, Ops);
3691
3692 if (IsSubAdd)
3693 std::swap(Even, Odd);
3694
3695 SmallVector<int, 32> Idxs(NumElts);
3696 for (int i = 0; i != NumElts; ++i)
3697 Idxs[i] = i + (i % 2) * NumElts;
3698
3699 Rep = Builder.CreateShuffleVector(Even, Odd, Idxs);
3700 }
3701
3702 Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3703 IsMask3 ? CI->getArgOperand(2) :
3704 CI->getArgOperand(0);
3705
3706 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3707 } else if (IsX86 && (Name.startswith("avx512.mask.pternlog.") ||
3708 Name.startswith("avx512.maskz.pternlog."))) {
3709 bool ZeroMask = Name[11] == 'z';
3710 unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3711 unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3712 Intrinsic::ID IID;
3713 if (VecWidth == 128 && EltWidth == 32)
3714 IID = Intrinsic::x86_avx512_pternlog_d_128;
3715 else if (VecWidth == 256 && EltWidth == 32)
3716 IID = Intrinsic::x86_avx512_pternlog_d_256;
3717 else if (VecWidth == 512 && EltWidth == 32)
3718 IID = Intrinsic::x86_avx512_pternlog_d_512;
3719 else if (VecWidth == 128 && EltWidth == 64)
3720 IID = Intrinsic::x86_avx512_pternlog_q_128;
3721 else if (VecWidth == 256 && EltWidth == 64)
3722 IID = Intrinsic::x86_avx512_pternlog_q_256;
3723 else if (VecWidth == 512 && EltWidth == 64)
3724 IID = Intrinsic::x86_avx512_pternlog_q_512;
3725 else
3726 llvm_unreachable("Unexpected intrinsic");
3727
3728 Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3729 CI->getArgOperand(2), CI->getArgOperand(3) };
3730 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3731 Args);
3732 Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3733 : CI->getArgOperand(0);
3734 Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep, PassThru);
3735 } else if (IsX86 && (Name.startswith("avx512.mask.vpmadd52") ||
3736 Name.startswith("avx512.maskz.vpmadd52"))) {
3737 bool ZeroMask = Name[11] == 'z';
3738 bool High = Name[20] == 'h' || Name[21] == 'h';
3739 unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3740 Intrinsic::ID IID;
3741 if (VecWidth == 128 && !High)
3742 IID = Intrinsic::x86_avx512_vpmadd52l_uq_128;
3743 else if (VecWidth == 256 && !High)
3744 IID = Intrinsic::x86_avx512_vpmadd52l_uq_256;
3745 else if (VecWidth == 512 && !High)
3746 IID = Intrinsic::x86_avx512_vpmadd52l_uq_512;
3747 else if (VecWidth == 128 && High)
3748 IID = Intrinsic::x86_avx512_vpmadd52h_uq_128;
3749 else if (VecWidth == 256 && High)
3750 IID = Intrinsic::x86_avx512_vpmadd52h_uq_256;
3751 else if (VecWidth == 512 && High)
3752 IID = Intrinsic::x86_avx512_vpmadd52h_uq_512;
3753 else
3754 llvm_unreachable("Unexpected intrinsic");
3755
3756 Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3757 CI->getArgOperand(2) };
3758 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3759 Args);
3760 Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3761 : CI->getArgOperand(0);
3762 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3763 } else if (IsX86 && (Name.startswith("avx512.mask.vpermi2var.") ||
3764 Name.startswith("avx512.mask.vpermt2var.") ||
3765 Name.startswith("avx512.maskz.vpermt2var."))) {
3766 bool ZeroMask = Name[11] == 'z';
3767 bool IndexForm = Name[17] == 'i';
3768 Rep = UpgradeX86VPERMT2Intrinsics(Builder, *CI, ZeroMask, IndexForm);
3769 } else if (IsX86 && (Name.startswith("avx512.mask.vpdpbusd.") ||
3770 Name.startswith("avx512.maskz.vpdpbusd.") ||
3771 Name.startswith("avx512.mask.vpdpbusds.") ||
3772 Name.startswith("avx512.maskz.vpdpbusds."))) {
3773 bool ZeroMask = Name[11] == 'z';
3774 bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3775 unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3776 Intrinsic::ID IID;
3777 if (VecWidth == 128 && !IsSaturating)
3778 IID = Intrinsic::x86_avx512_vpdpbusd_128;
3779 else if (VecWidth == 256 && !IsSaturating)
3780 IID = Intrinsic::x86_avx512_vpdpbusd_256;
3781 else if (VecWidth == 512 && !IsSaturating)
3782 IID = Intrinsic::x86_avx512_vpdpbusd_512;
3783 else if (VecWidth == 128 && IsSaturating)
3784 IID = Intrinsic::x86_avx512_vpdpbusds_128;
3785 else if (VecWidth == 256 && IsSaturating)
3786 IID = Intrinsic::x86_avx512_vpdpbusds_256;
3787 else if (VecWidth == 512 && IsSaturating)
3788 IID = Intrinsic::x86_avx512_vpdpbusds_512;
3789 else
3790 llvm_unreachable("Unexpected intrinsic");
3791
3792 Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3793 CI->getArgOperand(2) };
3794 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3795 Args);
3796 Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3797 : CI->getArgOperand(0);
3798 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3799 } else if (IsX86 && (Name.startswith("avx512.mask.vpdpwssd.") ||
3800 Name.startswith("avx512.maskz.vpdpwssd.") ||
3801 Name.startswith("avx512.mask.vpdpwssds.") ||
3802 Name.startswith("avx512.maskz.vpdpwssds."))) {
3803 bool ZeroMask = Name[11] == 'z';
3804 bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3805 unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3806 Intrinsic::ID IID;
3807 if (VecWidth == 128 && !IsSaturating)
3808 IID = Intrinsic::x86_avx512_vpdpwssd_128;
3809 else if (VecWidth == 256 && !IsSaturating)
3810 IID = Intrinsic::x86_avx512_vpdpwssd_256;
3811 else if (VecWidth == 512 && !IsSaturating)
3812 IID = Intrinsic::x86_avx512_vpdpwssd_512;
3813 else if (VecWidth == 128 && IsSaturating)
3814 IID = Intrinsic::x86_avx512_vpdpwssds_128;
3815 else if (VecWidth == 256 && IsSaturating)
3816 IID = Intrinsic::x86_avx512_vpdpwssds_256;
3817 else if (VecWidth == 512 && IsSaturating)
3818 IID = Intrinsic::x86_avx512_vpdpwssds_512;
3819 else
3820 llvm_unreachable("Unexpected intrinsic");
3821
3822 Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3823 CI->getArgOperand(2) };
3824 Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3825 Args);
3826 Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3827 : CI->getArgOperand(0);
3828 Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3829 } else if (IsX86 && (Name == "addcarryx.u32" || Name == "addcarryx.u64" ||
3830 Name == "addcarry.u32" || Name == "addcarry.u64" ||
3831 Name == "subborrow.u32" || Name == "subborrow.u64")) {
3832 Intrinsic::ID IID;
3833 if (Name[0] == 'a' && Name.back() == '2')
3834 IID = Intrinsic::x86_addcarry_32;
3835 else if (Name[0] == 'a' && Name.back() == '4')
3836 IID = Intrinsic::x86_addcarry_64;
3837 else if (Name[0] == 's' && Name.back() == '2')
3838 IID = Intrinsic::x86_subborrow_32;
3839 else if (Name[0] == 's' && Name.back() == '4')
3840 IID = Intrinsic::x86_subborrow_64;
3841 else
3842 llvm_unreachable("Unexpected intrinsic");
3843
3844 // Make a call with 3 operands.
3845 Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3846 CI->getArgOperand(2)};
3847 Value *NewCall = Builder.CreateCall(
3848 Intrinsic::getDeclaration(CI->getModule(), IID),
3849 Args);
3850
3851 // Extract the second result and store it.
3852 Value *Data = Builder.CreateExtractValue(NewCall, 1);
3853 // Cast the pointer to the right type.
3854 Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(3),
3855 llvm::PointerType::getUnqual(Data->getType()));
3856 Builder.CreateAlignedStore(Data, Ptr, Align(1));
3857 // Replace the original call result with the first result of the new call.
3858 Value *CF = Builder.CreateExtractValue(NewCall, 0);
3859
3860 CI->replaceAllUsesWith(CF);
3861 Rep = nullptr;
3862 } else if (IsX86 && Name.startswith("avx512.mask.") &&
3863 upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
3864 // Rep will be updated by the call in the condition.
3865 } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
3866 Value *Arg = CI->getArgOperand(0);
3867 Value *Neg = Builder.CreateNeg(Arg, "neg");
3868 Value *Cmp = Builder.CreateICmpSGE(
3869 Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
3870 Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
3871 } else if (IsNVVM && (Name.startswith("atomic.load.add.f32.p") ||
3872 Name.startswith("atomic.load.add.f64.p"))) {
3873 Value *Ptr = CI->getArgOperand(0);
3874 Value *Val = CI->getArgOperand(1);
3875 Rep = Builder.CreateAtomicRMW(AtomicRMWInst::FAdd, Ptr, Val, MaybeAlign(),
3876 AtomicOrdering::SequentiallyConsistent);
3877 } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
3878 Name == "max.ui" || Name == "max.ull")) {
3879 Value *Arg0 = CI->getArgOperand(0);
3880 Value *Arg1 = CI->getArgOperand(1);
3881 Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3882 ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
3883 : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
3884 Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
3885 } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
3886 Name == "min.ui" || Name == "min.ull")) {
3887 Value *Arg0 = CI->getArgOperand(0);
3888 Value *Arg1 = CI->getArgOperand(1);
3889 Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3890 ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
3891 : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
3892 Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
3893 } else if (IsNVVM && Name == "clz.ll") {
3894 // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
3895 Value *Arg = CI->getArgOperand(0);
3896 Value *Ctlz = Builder.CreateCall(
3897 Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
3898 {Arg->getType()}),
3899 {Arg, Builder.getFalse()}, "ctlz");
3900 Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
3901 } else if (IsNVVM && Name == "popc.ll") {
3902 // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
3903 // i64.
3904 Value *Arg = CI->getArgOperand(0);
3905 Value *Popc = Builder.CreateCall(
3906 Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
3907 {Arg->getType()}),
3908 Arg, "ctpop");
3909 Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
3910 } else if (IsNVVM && Name == "h2f") {
3911 Rep = Builder.CreateCall(Intrinsic::getDeclaration(
3912 F->getParent(), Intrinsic::convert_from_fp16,
3913 {Builder.getFloatTy()}),
3914 CI->getArgOperand(0), "h2f");
3915 } else if (IsARM) {
3916 Rep = UpgradeARMIntrinsicCall(Name, CI, F, Builder);
3917 } else {
3918 llvm_unreachable("Unknown function for CallBase upgrade.");
3919 }
3920
3921 if (Rep)
3922 CI->replaceAllUsesWith(Rep);
3923 CI->eraseFromParent();
3924 return;
3925 }
3926
3927 const auto &DefaultCase = [&]() -> void {
3928 if (CI->getFunctionType() == NewFn->getFunctionType()) {
3929 // Handle generic mangling change.
3930 assert(
3931 (CI->getCalledFunction()->getName() != NewFn->getName()) &&
3932 "Unknown function for CallBase upgrade and isn't just a name change");
3933 CI->setCalledFunction(NewFn);
3934 return;
3935 }
3936
3937 // This must be an upgrade from a named to a literal struct.
3938 if (auto *OldST = dyn_cast<StructType>(CI->getType())) {
3939 assert(OldST != NewFn->getReturnType() &&
3940 "Return type must have changed");
3941 assert(OldST->getNumElements() ==
3942 cast<StructType>(NewFn->getReturnType())->getNumElements() &&
3943 "Must have same number of elements");
3944
3945 SmallVector<Value *> Args(CI->args());
3946 Value *NewCI = Builder.CreateCall(NewFn, Args);
3947 Value *Res = PoisonValue::get(OldST);
3948 for (unsigned Idx = 0; Idx < OldST->getNumElements(); ++Idx) {
3949 Value *Elem = Builder.CreateExtractValue(NewCI, Idx);
3950 Res = Builder.CreateInsertValue(Res, Elem, Idx);
3951 }
3952 CI->replaceAllUsesWith(Res);
3953 CI->eraseFromParent();
3954 return;
3955 }
3956
3957 // We're probably about to produce something invalid. Let the verifier catch
3958 // it instead of dying here.
3959 CI->setCalledOperand(
3960 ConstantExpr::getPointerCast(NewFn, CI->getCalledOperand()->getType()));
3961 return;
3962 };
3963 CallInst *NewCall = nullptr;
3964 switch (NewFn->getIntrinsicID()) {
3965 default: {
3966 DefaultCase();
3967 return;
3968 }
3969 case Intrinsic::arm_neon_vst1:
3970 case Intrinsic::arm_neon_vst2:
3971 case Intrinsic::arm_neon_vst3:
3972 case Intrinsic::arm_neon_vst4:
3973 case Intrinsic::arm_neon_vst2lane:
3974 case Intrinsic::arm_neon_vst3lane:
3975 case Intrinsic::arm_neon_vst4lane: {
3976 SmallVector<Value *, 4> Args(CI->args());
3977 NewCall = Builder.CreateCall(NewFn, Args);
3978 break;
3979 }
3980 case Intrinsic::aarch64_sve_bfmlalb_lane_v2:
3981 case Intrinsic::aarch64_sve_bfmlalt_lane_v2:
3982 case Intrinsic::aarch64_sve_bfdot_lane_v2: {
3983 LLVMContext &Ctx = F->getParent()->getContext();
3984 SmallVector<Value *, 4> Args(CI->args());
3985 Args[3] = ConstantInt::get(Type::getInt32Ty(Ctx),
3986 cast<ConstantInt>(Args[3])->getZExtValue());
3987 NewCall = Builder.CreateCall(NewFn, Args);
3988 break;
3989 }
3990 case Intrinsic::aarch64_sve_ld3_sret:
3991 case Intrinsic::aarch64_sve_ld4_sret:
3992 case Intrinsic::aarch64_sve_ld2_sret: {
3993 StringRef Name = F->getName();
3994 Name = Name.substr(5);
3995 unsigned N = StringSwitch<unsigned>(Name)
3996 .StartsWith("aarch64.sve.ld2", 2)
3997 .StartsWith("aarch64.sve.ld3", 3)
3998 .StartsWith("aarch64.sve.ld4", 4)
3999 .Default(0);
4000 ScalableVectorType *RetTy =
4001 dyn_cast<ScalableVectorType>(F->getReturnType());
4002 unsigned MinElts = RetTy->getMinNumElements() / N;
4003 SmallVector<Value *, 2> Args(CI->args());
4004 Value *NewLdCall = Builder.CreateCall(NewFn, Args);
4005 Value *Ret = llvm::PoisonValue::get(RetTy);
4006 for (unsigned I = 0; I < N; I++) {
4007 Value *Idx = ConstantInt::get(Type::getInt64Ty(C), I * MinElts);
4008 Value *SRet = Builder.CreateExtractValue(NewLdCall, I);
4009 Ret = Builder.CreateInsertVector(RetTy, Ret, SRet, Idx);
4010 }
4011 NewCall = dyn_cast<CallInst>(Ret);
4012 break;
4013 }
4014
4015 case Intrinsic::vector_extract: {
4016 StringRef Name = F->getName();
4017 Name = Name.substr(5); // Strip llvm
4018 if (!Name.startswith("aarch64.sve.tuple.get")) {
4019 DefaultCase();
4020 return;
4021 }
4022 ScalableVectorType *RetTy =
4023 dyn_cast<ScalableVectorType>(F->getReturnType());
4024 unsigned MinElts = RetTy->getMinNumElements();
4025 unsigned I = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
4026 Value *NewIdx = ConstantInt::get(Type::getInt64Ty(C), I * MinElts);
4027 NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0), NewIdx});
4028 break;
4029 }
4030
4031 case Intrinsic::vector_insert: {
4032 StringRef Name = F->getName();
4033 Name = Name.substr(5);
4034 if (!Name.startswith("aarch64.sve.tuple")) {
4035 DefaultCase();
4036 return;
4037 }
4038 if (Name.startswith("aarch64.sve.tuple.set")) {
4039 unsigned I = dyn_cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
4040 ScalableVectorType *Ty =
4041 dyn_cast<ScalableVectorType>(CI->getArgOperand(2)->getType());
4042 Value *NewIdx =
4043 ConstantInt::get(Type::getInt64Ty(C), I * Ty->getMinNumElements());
4044 NewCall = Builder.CreateCall(
4045 NewFn, {CI->getArgOperand(0), CI->getArgOperand(2), NewIdx});
4046 break;
4047 }
4048 if (Name.startswith("aarch64.sve.tuple.create")) {
4049 unsigned N = StringSwitch<unsigned>(Name)
4050 .StartsWith("aarch64.sve.tuple.create2", 2)
4051 .StartsWith("aarch64.sve.tuple.create3", 3)
4052 .StartsWith("aarch64.sve.tuple.create4", 4)
4053 .Default(0);
4054 assert(N > 1 && "Create is expected to be between 2-4");
4055 ScalableVectorType *RetTy =
4056 dyn_cast<ScalableVectorType>(F->getReturnType());
4057 Value *Ret = llvm::PoisonValue::get(RetTy);
4058 unsigned MinElts = RetTy->getMinNumElements() / N;
4059 for (unsigned I = 0; I < N; I++) {
4060 Value *Idx = ConstantInt::get(Type::getInt64Ty(C), I * MinElts);
4061 Value *V = CI->getArgOperand(I);
4062 Ret = Builder.CreateInsertVector(RetTy, Ret, V, Idx);
4063 }
4064 NewCall = dyn_cast<CallInst>(Ret);
4065 }
4066 break;
4067 }
4068
4069 case Intrinsic::arm_neon_bfdot:
4070 case Intrinsic::arm_neon_bfmmla:
4071 case Intrinsic::arm_neon_bfmlalb:
4072 case Intrinsic::arm_neon_bfmlalt:
4073 case Intrinsic::aarch64_neon_bfdot:
4074 case Intrinsic::aarch64_neon_bfmmla:
4075 case Intrinsic::aarch64_neon_bfmlalb:
4076 case Intrinsic::aarch64_neon_bfmlalt: {
4077 SmallVector<Value *, 3> Args;
4078 assert(CI->arg_size() == 3 &&
4079 "Mismatch between function args and call args");
4080 size_t OperandWidth =
4081 CI->getArgOperand(1)->getType()->getPrimitiveSizeInBits();
4082 assert((OperandWidth == 64 || OperandWidth == 128) &&
4083 "Unexpected operand width");
4084 Type *NewTy = FixedVectorType::get(Type::getBFloatTy(C), OperandWidth / 16);
4085 auto Iter = CI->args().begin();
4086 Args.push_back(*Iter++);
4087 Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
4088 Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
4089 NewCall = Builder.CreateCall(NewFn, Args);
4090 break;
4091 }
4092
4093 case Intrinsic::bitreverse:
4094 NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
4095 break;
4096
4097 case Intrinsic::ctlz:
4098 case Intrinsic::cttz:
4099 assert(CI->arg_size() == 1 &&
4100 "Mismatch between function args and call args");
4101 NewCall =
4102 Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
4103 break;
4104
4105 case Intrinsic::objectsize: {
4106 Value *NullIsUnknownSize =
4107 CI->arg_size() == 2 ? Builder.getFalse() : CI->getArgOperand(2);
4108 Value *Dynamic =
4109 CI->arg_size() < 4 ? Builder.getFalse() : CI->getArgOperand(3);
4110 NewCall = Builder.CreateCall(
4111 NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize, Dynamic});
4112 break;
4113 }
4114
4115 case Intrinsic::ctpop:
4116 NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
4117 break;
4118
4119 case Intrinsic::convert_from_fp16:
4120 NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
4121 break;
4122
4123 case Intrinsic::dbg_value:
4124 // Upgrade from the old version that had an extra offset argument.
4125 assert(CI->arg_size() == 4);
4126 // Drop nonzero offsets instead of attempting to upgrade them.
4127 if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
4128 if (Offset->isZeroValue()) {
4129 NewCall = Builder.CreateCall(
4130 NewFn,
4131 {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
4132 break;
4133 }
4134 CI->eraseFromParent();
4135 return;
4136
4137 case Intrinsic::ptr_annotation:
4138 // Upgrade from versions that lacked the annotation attribute argument.
4139 if (CI->arg_size() != 4) {
4140 DefaultCase();
4141 return;
4142 }
4143
4144 // Create a new call with an added null annotation attribute argument.
4145 NewCall = Builder.CreateCall(
4146 NewFn,
4147 {CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2),
4148 CI->getArgOperand(3), Constant::getNullValue(Builder.getInt8PtrTy())});
4149 NewCall->takeName(CI);
4150 CI->replaceAllUsesWith(NewCall);
4151 CI->eraseFromParent();
4152 return;
4153
4154 case Intrinsic::var_annotation:
4155 // Upgrade from versions that lacked the annotation attribute argument.
4156 if (CI->arg_size() != 4) {
4157 DefaultCase();
4158 return;
4159 }
4160 // Create a new call with an added null annotation attribute argument.
4161 NewCall = Builder.CreateCall(
4162 NewFn,
4163 {CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2),
4164 CI->getArgOperand(3), Constant::getNullValue(Builder.getInt8PtrTy())});
4165 NewCall->takeName(CI);
4166 CI->replaceAllUsesWith(NewCall);
4167 CI->eraseFromParent();
4168 return;
4169
4170 case Intrinsic::x86_xop_vfrcz_ss:
4171 case Intrinsic::x86_xop_vfrcz_sd:
4172 NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
4173 break;
4174
4175 case Intrinsic::x86_xop_vpermil2pd:
4176 case Intrinsic::x86_xop_vpermil2ps:
4177 case Intrinsic::x86_xop_vpermil2pd_256:
4178 case Intrinsic::x86_xop_vpermil2ps_256: {
4179 SmallVector<Value *, 4> Args(CI->args());
4180 VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
4181 VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
4182 Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
4183 NewCall = Builder.CreateCall(NewFn, Args);
4184 break;
4185 }
4186
4187 case Intrinsic::x86_sse41_ptestc:
4188 case Intrinsic::x86_sse41_ptestz:
4189 case Intrinsic::x86_sse41_ptestnzc: {
4190 // The arguments for these intrinsics used to be v4f32, and changed
4191 // to v2i64. This is purely a nop, since those are bitwise intrinsics.
4192 // So, the only thing required is a bitcast for both arguments.
4193 // First, check the arguments have the old type.
4194 Value *Arg0 = CI->getArgOperand(0);
4195 if (Arg0->getType() != FixedVectorType::get(Type::getFloatTy(C), 4))
4196 return;
4197
4198 // Old intrinsic, add bitcasts
4199 Value *Arg1 = CI->getArgOperand(1);
4200
4201 auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
4202
4203 Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
4204 Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
4205
4206 NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
4207 break;
4208 }
4209
4210 case Intrinsic::x86_rdtscp: {
4211 // This used to take 1 arguments. If we have no arguments, it is already
4212 // upgraded.
4213 if (CI->getNumOperands() == 0)
4214 return;
4215
4216 NewCall = Builder.CreateCall(NewFn);
4217 // Extract the second result and store it.
4218 Value *Data = Builder.CreateExtractValue(NewCall, 1);
4219 // Cast the pointer to the right type.
4220 Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(0),
4221 llvm::PointerType::getUnqual(Data->getType()));
4222 Builder.CreateAlignedStore(Data, Ptr, Align(1));
4223 // Replace the original call result with the first result of the new call.
4224 Value *TSC = Builder.CreateExtractValue(NewCall, 0);
4225
4226 NewCall->takeName(CI);
4227 CI->replaceAllUsesWith(TSC);
4228 CI->eraseFromParent();
4229 return;
4230 }
4231
4232 case Intrinsic::x86_sse41_insertps:
4233 case Intrinsic::x86_sse41_dppd:
4234 case Intrinsic::x86_sse41_dpps:
4235 case Intrinsic::x86_sse41_mpsadbw:
4236 case Intrinsic::x86_avx_dp_ps_256:
4237 case Intrinsic::x86_avx2_mpsadbw: {
4238 // Need to truncate the last argument from i32 to i8 -- this argument models
4239 // an inherently 8-bit immediate operand to these x86 instructions.
4240 SmallVector<Value *, 4> Args(CI->args());
4241
4242 // Replace the last argument with a trunc.
4243 Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
4244 NewCall = Builder.CreateCall(NewFn, Args);
4245 break;
4246 }
4247
4248 case Intrinsic::x86_avx512_mask_cmp_pd_128:
4249 case Intrinsic::x86_avx512_mask_cmp_pd_256:
4250 case Intrinsic::x86_avx512_mask_cmp_pd_512:
4251 case Intrinsic::x86_avx512_mask_cmp_ps_128:
4252 case Intrinsic::x86_avx512_mask_cmp_ps_256:
4253 case Intrinsic::x86_avx512_mask_cmp_ps_512: {
4254 SmallVector<Value *, 4> Args(CI->args());
4255 unsigned NumElts =
4256 cast<FixedVectorType>(Args[0]->getType())->getNumElements();
4257 Args[3] = getX86MaskVec(Builder, Args[3], NumElts);
4258
4259 NewCall = Builder.CreateCall(NewFn, Args);
4260 Value *Res = ApplyX86MaskOn1BitsVec(Builder, NewCall, nullptr);
4261
4262 NewCall->takeName(CI);
4263 CI->replaceAllUsesWith(Res);
4264 CI->eraseFromParent();
4265 return;
4266 }
4267
4268 case Intrinsic::x86_avx512bf16_cvtne2ps2bf16_128:
4269 case Intrinsic::x86_avx512bf16_cvtne2ps2bf16_256:
4270 case Intrinsic::x86_avx512bf16_cvtne2ps2bf16_512:
4271 case Intrinsic::x86_avx512bf16_mask_cvtneps2bf16_128:
4272 case Intrinsic::x86_avx512bf16_cvtneps2bf16_256:
4273 case Intrinsic::x86_avx512bf16_cvtneps2bf16_512: {
4274 SmallVector<Value *, 4> Args(CI->args());
4275 unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
4276 if (NewFn->getIntrinsicID() ==
4277 Intrinsic::x86_avx512bf16_mask_cvtneps2bf16_128)
4278 Args[1] = Builder.CreateBitCast(
4279 Args[1], FixedVectorType::get(Builder.getBFloatTy(), NumElts));
4280
4281 NewCall = Builder.CreateCall(NewFn, Args);
4282 Value *Res = Builder.CreateBitCast(
4283 NewCall, FixedVectorType::get(Builder.getInt16Ty(), NumElts));
4284
4285 NewCall->takeName(CI);
4286 CI->replaceAllUsesWith(Res);
4287 CI->eraseFromParent();
4288 return;
4289 }
4290 case Intrinsic::x86_avx512bf16_dpbf16ps_128:
4291 case Intrinsic::x86_avx512bf16_dpbf16ps_256:
4292 case Intrinsic::x86_avx512bf16_dpbf16ps_512:{
4293 SmallVector<Value *, 4> Args(CI->args());
4294 unsigned NumElts =
4295 cast<FixedVectorType>(CI->getType())->getNumElements() * 2;
4296 Args[1] = Builder.CreateBitCast(
4297 Args[1], FixedVectorType::get(Builder.getBFloatTy(), NumElts));
4298 Args[2] = Builder.CreateBitCast(
4299 Args[2], FixedVectorType::get(Builder.getBFloatTy(), NumElts));
4300
4301 NewCall = Builder.CreateCall(NewFn, Args);
4302 break;
4303 }
4304
4305 case Intrinsic::thread_pointer: {
4306 NewCall = Builder.CreateCall(NewFn, {});
4307 break;
4308 }
4309
4310 case Intrinsic::invariant_start:
4311 case Intrinsic::invariant_end: {
4312 SmallVector<Value *, 4> Args(CI->args());
4313 NewCall = Builder.CreateCall(NewFn, Args);
4314 break;
4315 }
4316 case Intrinsic::masked_load:
4317 case Intrinsic::masked_store:
4318 case Intrinsic::masked_gather:
4319 case Intrinsic::masked_scatter: {
4320 SmallVector<Value *, 4> Args(CI->args());
4321 NewCall = Builder.CreateCall(NewFn, Args);
4322 NewCall->copyMetadata(*CI);
4323 break;
4324 }
4325
4326 case Intrinsic::memcpy:
4327 case Intrinsic::memmove:
4328 case Intrinsic::memset: {
4329 // We have to make sure that the call signature is what we're expecting.
4330 // We only want to change the old signatures by removing the alignment arg:
4331 // @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
4332 // -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
4333 // @llvm.memset...(i8*, i8, i[32|64], i32, i1)
4334 // -> @llvm.memset...(i8*, i8, i[32|64], i1)
4335 // Note: i8*'s in the above can be any pointer type
4336 if (CI->arg_size() != 5) {
4337 DefaultCase();
4338 return;
4339 }
4340 // Remove alignment argument (3), and add alignment attributes to the
4341 // dest/src pointers.
4342 Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
4343 CI->getArgOperand(2), CI->getArgOperand(4)};
4344 NewCall = Builder.CreateCall(NewFn, Args);
4345 AttributeList OldAttrs = CI->getAttributes();
4346 AttributeList NewAttrs = AttributeList::get(
4347 C, OldAttrs.getFnAttrs(), OldAttrs.getRetAttrs(),
4348 {OldAttrs.getParamAttrs(0), OldAttrs.getParamAttrs(1),
4349 OldAttrs.getParamAttrs(2), OldAttrs.getParamAttrs(4)});
4350 NewCall->setAttributes(NewAttrs);
4351 auto *MemCI = cast<MemIntrinsic>(NewCall);
4352 // All mem intrinsics support dest alignment.
4353 const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
4354 MemCI->setDestAlignment(Align->getMaybeAlignValue());
4355 // Memcpy/Memmove also support source alignment.
4356 if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
4357 MTI->setSourceAlignment(Align->getMaybeAlignValue());
4358 break;
4359 }
4360 }
4361 assert(NewCall && "Should have either set this variable or returned through "
4362 "the default case");
4363 NewCall->takeName(CI);
4364 CI->replaceAllUsesWith(NewCall);
4365 CI->eraseFromParent();
4366 }
4367
UpgradeCallsToIntrinsic(Function * F)4368 void llvm::UpgradeCallsToIntrinsic(Function *F) {
4369 assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
4370
4371 // Check if this function should be upgraded and get the replacement function
4372 // if there is one.
4373 Function *NewFn;
4374 if (UpgradeIntrinsicFunction(F, NewFn)) {
4375 // Replace all users of the old function with the new function or new
4376 // instructions. This is not a range loop because the call is deleted.
4377 for (User *U : make_early_inc_range(F->users()))
4378 if (CallBase *CB = dyn_cast<CallBase>(U))
4379 UpgradeIntrinsicCall(CB, NewFn);
4380
4381 // Remove old function, no longer used, from the module.
4382 F->eraseFromParent();
4383 }
4384 }
4385
UpgradeTBAANode(MDNode & MD)4386 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
4387 // Check if the tag uses struct-path aware TBAA format.
4388 if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
4389 return &MD;
4390
4391 auto &Context = MD.getContext();
4392 if (MD.getNumOperands() == 3) {
4393 Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
4394 MDNode *ScalarType = MDNode::get(Context, Elts);
4395 // Create a MDNode <ScalarType, ScalarType, offset 0, const>
4396 Metadata *Elts2[] = {ScalarType, ScalarType,
4397 ConstantAsMetadata::get(
4398 Constant::getNullValue(Type::getInt64Ty(Context))),
4399 MD.getOperand(2)};
4400 return MDNode::get(Context, Elts2);
4401 }
4402 // Create a MDNode <MD, MD, offset 0>
4403 Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
4404 Type::getInt64Ty(Context)))};
4405 return MDNode::get(Context, Elts);
4406 }
4407
UpgradeBitCastInst(unsigned Opc,Value * V,Type * DestTy,Instruction * & Temp)4408 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
4409 Instruction *&Temp) {
4410 if (Opc != Instruction::BitCast)
4411 return nullptr;
4412
4413 Temp = nullptr;
4414 Type *SrcTy = V->getType();
4415 if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
4416 SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
4417 LLVMContext &Context = V->getContext();
4418
4419 // We have no information about target data layout, so we assume that
4420 // the maximum pointer size is 64bit.
4421 Type *MidTy = Type::getInt64Ty(Context);
4422 Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
4423
4424 return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
4425 }
4426
4427 return nullptr;
4428 }
4429
UpgradeBitCastExpr(unsigned Opc,Constant * C,Type * DestTy)4430 Constant *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
4431 if (Opc != Instruction::BitCast)
4432 return nullptr;
4433
4434 Type *SrcTy = C->getType();
4435 if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
4436 SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
4437 LLVMContext &Context = C->getContext();
4438
4439 // We have no information about target data layout, so we assume that
4440 // the maximum pointer size is 64bit.
4441 Type *MidTy = Type::getInt64Ty(Context);
4442
4443 return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
4444 DestTy);
4445 }
4446
4447 return nullptr;
4448 }
4449
4450 /// Check the debug info version number, if it is out-dated, drop the debug
4451 /// info. Return true if module is modified.
UpgradeDebugInfo(Module & M)4452 bool llvm::UpgradeDebugInfo(Module &M) {
4453 unsigned Version = getDebugMetadataVersionFromModule(M);
4454 if (Version == DEBUG_METADATA_VERSION) {
4455 bool BrokenDebugInfo = false;
4456 if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
4457 report_fatal_error("Broken module found, compilation aborted!");
4458 if (!BrokenDebugInfo)
4459 // Everything is ok.
4460 return false;
4461 else {
4462 // Diagnose malformed debug info.
4463 DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
4464 M.getContext().diagnose(Diag);
4465 }
4466 }
4467 bool Modified = StripDebugInfo(M);
4468 if (Modified && Version != DEBUG_METADATA_VERSION) {
4469 // Diagnose a version mismatch.
4470 DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
4471 M.getContext().diagnose(DiagVersion);
4472 }
4473 return Modified;
4474 }
4475
4476 /// This checks for objc retain release marker which should be upgraded. It
4477 /// returns true if module is modified.
UpgradeRetainReleaseMarker(Module & M)4478 static bool UpgradeRetainReleaseMarker(Module &M) {
4479 bool Changed = false;
4480 const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
4481 NamedMDNode *ModRetainReleaseMarker = M.getNamedMetadata(MarkerKey);
4482 if (ModRetainReleaseMarker) {
4483 MDNode *Op = ModRetainReleaseMarker->getOperand(0);
4484 if (Op) {
4485 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
4486 if (ID) {
4487 SmallVector<StringRef, 4> ValueComp;
4488 ID->getString().split(ValueComp, "#");
4489 if (ValueComp.size() == 2) {
4490 std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
4491 ID = MDString::get(M.getContext(), NewValue);
4492 }
4493 M.addModuleFlag(Module::Error, MarkerKey, ID);
4494 M.eraseNamedMetadata(ModRetainReleaseMarker);
4495 Changed = true;
4496 }
4497 }
4498 }
4499 return Changed;
4500 }
4501
UpgradeARCRuntime(Module & M)4502 void llvm::UpgradeARCRuntime(Module &M) {
4503 // This lambda converts normal function calls to ARC runtime functions to
4504 // intrinsic calls.
4505 auto UpgradeToIntrinsic = [&](const char *OldFunc,
4506 llvm::Intrinsic::ID IntrinsicFunc) {
4507 Function *Fn = M.getFunction(OldFunc);
4508
4509 if (!Fn)
4510 return;
4511
4512 Function *NewFn = llvm::Intrinsic::getDeclaration(&M, IntrinsicFunc);
4513
4514 for (User *U : make_early_inc_range(Fn->users())) {
4515 CallInst *CI = dyn_cast<CallInst>(U);
4516 if (!CI || CI->getCalledFunction() != Fn)
4517 continue;
4518
4519 IRBuilder<> Builder(CI->getParent(), CI->getIterator());
4520 FunctionType *NewFuncTy = NewFn->getFunctionType();
4521 SmallVector<Value *, 2> Args;
4522
4523 // Don't upgrade the intrinsic if it's not valid to bitcast the return
4524 // value to the return type of the old function.
4525 if (NewFuncTy->getReturnType() != CI->getType() &&
4526 !CastInst::castIsValid(Instruction::BitCast, CI,
4527 NewFuncTy->getReturnType()))
4528 continue;
4529
4530 bool InvalidCast = false;
4531
4532 for (unsigned I = 0, E = CI->arg_size(); I != E; ++I) {
4533 Value *Arg = CI->getArgOperand(I);
4534
4535 // Bitcast argument to the parameter type of the new function if it's
4536 // not a variadic argument.
4537 if (I < NewFuncTy->getNumParams()) {
4538 // Don't upgrade the intrinsic if it's not valid to bitcast the argument
4539 // to the parameter type of the new function.
4540 if (!CastInst::castIsValid(Instruction::BitCast, Arg,
4541 NewFuncTy->getParamType(I))) {
4542 InvalidCast = true;
4543 break;
4544 }
4545 Arg = Builder.CreateBitCast(Arg, NewFuncTy->getParamType(I));
4546 }
4547 Args.push_back(Arg);
4548 }
4549
4550 if (InvalidCast)
4551 continue;
4552
4553 // Create a call instruction that calls the new function.
4554 CallInst *NewCall = Builder.CreateCall(NewFuncTy, NewFn, Args);
4555 NewCall->setTailCallKind(cast<CallInst>(CI)->getTailCallKind());
4556 NewCall->takeName(CI);
4557
4558 // Bitcast the return value back to the type of the old call.
4559 Value *NewRetVal = Builder.CreateBitCast(NewCall, CI->getType());
4560
4561 if (!CI->use_empty())
4562 CI->replaceAllUsesWith(NewRetVal);
4563 CI->eraseFromParent();
4564 }
4565
4566 if (Fn->use_empty())
4567 Fn->eraseFromParent();
4568 };
4569
4570 // Unconditionally convert a call to "clang.arc.use" to a call to
4571 // "llvm.objc.clang.arc.use".
4572 UpgradeToIntrinsic("clang.arc.use", llvm::Intrinsic::objc_clang_arc_use);
4573
4574 // Upgrade the retain release marker. If there is no need to upgrade
4575 // the marker, that means either the module is already new enough to contain
4576 // new intrinsics or it is not ARC. There is no need to upgrade runtime call.
4577 if (!UpgradeRetainReleaseMarker(M))
4578 return;
4579
4580 std::pair<const char *, llvm::Intrinsic::ID> RuntimeFuncs[] = {
4581 {"objc_autorelease", llvm::Intrinsic::objc_autorelease},
4582 {"objc_autoreleasePoolPop", llvm::Intrinsic::objc_autoreleasePoolPop},
4583 {"objc_autoreleasePoolPush", llvm::Intrinsic::objc_autoreleasePoolPush},
4584 {"objc_autoreleaseReturnValue",
4585 llvm::Intrinsic::objc_autoreleaseReturnValue},
4586 {"objc_copyWeak", llvm::Intrinsic::objc_copyWeak},
4587 {"objc_destroyWeak", llvm::Intrinsic::objc_destroyWeak},
4588 {"objc_initWeak", llvm::Intrinsic::objc_initWeak},
4589 {"objc_loadWeak", llvm::Intrinsic::objc_loadWeak},
4590 {"objc_loadWeakRetained", llvm::Intrinsic::objc_loadWeakRetained},
4591 {"objc_moveWeak", llvm::Intrinsic::objc_moveWeak},
4592 {"objc_release", llvm::Intrinsic::objc_release},
4593 {"objc_retain", llvm::Intrinsic::objc_retain},
4594 {"objc_retainAutorelease", llvm::Intrinsic::objc_retainAutorelease},
4595 {"objc_retainAutoreleaseReturnValue",
4596 llvm::Intrinsic::objc_retainAutoreleaseReturnValue},
4597 {"objc_retainAutoreleasedReturnValue",
4598 llvm::Intrinsic::objc_retainAutoreleasedReturnValue},
4599 {"objc_retainBlock", llvm::Intrinsic::objc_retainBlock},
4600 {"objc_storeStrong", llvm::Intrinsic::objc_storeStrong},
4601 {"objc_storeWeak", llvm::Intrinsic::objc_storeWeak},
4602 {"objc_unsafeClaimAutoreleasedReturnValue",
4603 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue},
4604 {"objc_retainedObject", llvm::Intrinsic::objc_retainedObject},
4605 {"objc_unretainedObject", llvm::Intrinsic::objc_unretainedObject},
4606 {"objc_unretainedPointer", llvm::Intrinsic::objc_unretainedPointer},
4607 {"objc_retain_autorelease", llvm::Intrinsic::objc_retain_autorelease},
4608 {"objc_sync_enter", llvm::Intrinsic::objc_sync_enter},
4609 {"objc_sync_exit", llvm::Intrinsic::objc_sync_exit},
4610 {"objc_arc_annotation_topdown_bbstart",
4611 llvm::Intrinsic::objc_arc_annotation_topdown_bbstart},
4612 {"objc_arc_annotation_topdown_bbend",
4613 llvm::Intrinsic::objc_arc_annotation_topdown_bbend},
4614 {"objc_arc_annotation_bottomup_bbstart",
4615 llvm::Intrinsic::objc_arc_annotation_bottomup_bbstart},
4616 {"objc_arc_annotation_bottomup_bbend",
4617 llvm::Intrinsic::objc_arc_annotation_bottomup_bbend}};
4618
4619 for (auto &I : RuntimeFuncs)
4620 UpgradeToIntrinsic(I.first, I.second);
4621 }
4622
UpgradeModuleFlags(Module & M)4623 bool llvm::UpgradeModuleFlags(Module &M) {
4624 NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
4625 if (!ModFlags)
4626 return false;
4627
4628 bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
4629 bool HasSwiftVersionFlag = false;
4630 uint8_t SwiftMajorVersion, SwiftMinorVersion;
4631 uint32_t SwiftABIVersion;
4632 auto Int8Ty = Type::getInt8Ty(M.getContext());
4633 auto Int32Ty = Type::getInt32Ty(M.getContext());
4634
4635 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
4636 MDNode *Op = ModFlags->getOperand(I);
4637 if (Op->getNumOperands() != 3)
4638 continue;
4639 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
4640 if (!ID)
4641 continue;
4642 auto SetBehavior = [&](Module::ModFlagBehavior B) {
4643 Metadata *Ops[3] = {ConstantAsMetadata::get(ConstantInt::get(
4644 Type::getInt32Ty(M.getContext()), B)),
4645 MDString::get(M.getContext(), ID->getString()),
4646 Op->getOperand(2)};
4647 ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4648 Changed = true;
4649 };
4650
4651 if (ID->getString() == "Objective-C Image Info Version")
4652 HasObjCFlag = true;
4653 if (ID->getString() == "Objective-C Class Properties")
4654 HasClassProperties = true;
4655 // Upgrade PIC from Error/Max to Min.
4656 if (ID->getString() == "PIC Level") {
4657 if (auto *Behavior =
4658 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
4659 uint64_t V = Behavior->getLimitedValue();
4660 if (V == Module::Error || V == Module::Max)
4661 SetBehavior(Module::Min);
4662 }
4663 }
4664 // Upgrade "PIE Level" from Error to Max.
4665 if (ID->getString() == "PIE Level")
4666 if (auto *Behavior =
4667 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)))
4668 if (Behavior->getLimitedValue() == Module::Error)
4669 SetBehavior(Module::Max);
4670
4671 // Upgrade branch protection and return address signing module flags. The
4672 // module flag behavior for these fields were Error and now they are Min.
4673 if (ID->getString() == "branch-target-enforcement" ||
4674 ID->getString().startswith("sign-return-address")) {
4675 if (auto *Behavior =
4676 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
4677 if (Behavior->getLimitedValue() == Module::Error) {
4678 Type *Int32Ty = Type::getInt32Ty(M.getContext());
4679 Metadata *Ops[3] = {
4680 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Min)),
4681 Op->getOperand(1), Op->getOperand(2)};
4682 ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4683 Changed = true;
4684 }
4685 }
4686 }
4687
4688 // Upgrade Objective-C Image Info Section. Removed the whitespce in the
4689 // section name so that llvm-lto will not complain about mismatching
4690 // module flags that is functionally the same.
4691 if (ID->getString() == "Objective-C Image Info Section") {
4692 if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
4693 SmallVector<StringRef, 4> ValueComp;
4694 Value->getString().split(ValueComp, " ");
4695 if (ValueComp.size() != 1) {
4696 std::string NewValue;
4697 for (auto &S : ValueComp)
4698 NewValue += S.str();
4699 Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
4700 MDString::get(M.getContext(), NewValue)};
4701 ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4702 Changed = true;
4703 }
4704 }
4705 }
4706
4707 // IRUpgrader turns a i32 type "Objective-C Garbage Collection" into i8 value.
4708 // If the higher bits are set, it adds new module flag for swift info.
4709 if (ID->getString() == "Objective-C Garbage Collection") {
4710 auto Md = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
4711 if (Md) {
4712 assert(Md->getValue() && "Expected non-empty metadata");
4713 auto Type = Md->getValue()->getType();
4714 if (Type == Int8Ty)
4715 continue;
4716 unsigned Val = Md->getValue()->getUniqueInteger().getZExtValue();
4717 if ((Val & 0xff) != Val) {
4718 HasSwiftVersionFlag = true;
4719 SwiftABIVersion = (Val & 0xff00) >> 8;
4720 SwiftMajorVersion = (Val & 0xff000000) >> 24;
4721 SwiftMinorVersion = (Val & 0xff0000) >> 16;
4722 }
4723 Metadata *Ops[3] = {
4724 ConstantAsMetadata::get(ConstantInt::get(Int32Ty,Module::Error)),
4725 Op->getOperand(1),
4726 ConstantAsMetadata::get(ConstantInt::get(Int8Ty,Val & 0xff))};
4727 ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4728 Changed = true;
4729 }
4730 }
4731 }
4732
4733 // "Objective-C Class Properties" is recently added for Objective-C. We
4734 // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
4735 // flag of value 0, so we can correclty downgrade this flag when trying to
4736 // link an ObjC bitcode without this module flag with an ObjC bitcode with
4737 // this module flag.
4738 if (HasObjCFlag && !HasClassProperties) {
4739 M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
4740 (uint32_t)0);
4741 Changed = true;
4742 }
4743
4744 if (HasSwiftVersionFlag) {
4745 M.addModuleFlag(Module::Error, "Swift ABI Version",
4746 SwiftABIVersion);
4747 M.addModuleFlag(Module::Error, "Swift Major Version",
4748 ConstantInt::get(Int8Ty, SwiftMajorVersion));
4749 M.addModuleFlag(Module::Error, "Swift Minor Version",
4750 ConstantInt::get(Int8Ty, SwiftMinorVersion));
4751 Changed = true;
4752 }
4753
4754 return Changed;
4755 }
4756
UpgradeSectionAttributes(Module & M)4757 void llvm::UpgradeSectionAttributes(Module &M) {
4758 auto TrimSpaces = [](StringRef Section) -> std::string {
4759 SmallVector<StringRef, 5> Components;
4760 Section.split(Components, ',');
4761
4762 SmallString<32> Buffer;
4763 raw_svector_ostream OS(Buffer);
4764
4765 for (auto Component : Components)
4766 OS << ',' << Component.trim();
4767
4768 return std::string(OS.str().substr(1));
4769 };
4770
4771 for (auto &GV : M.globals()) {
4772 if (!GV.hasSection())
4773 continue;
4774
4775 StringRef Section = GV.getSection();
4776
4777 if (!Section.startswith("__DATA, __objc_catlist"))
4778 continue;
4779
4780 // __DATA, __objc_catlist, regular, no_dead_strip
4781 // __DATA,__objc_catlist,regular,no_dead_strip
4782 GV.setSection(TrimSpaces(Section));
4783 }
4784 }
4785
4786 namespace {
4787 // Prior to LLVM 10.0, the strictfp attribute could be used on individual
4788 // callsites within a function that did not also have the strictfp attribute.
4789 // Since 10.0, if strict FP semantics are needed within a function, the
4790 // function must have the strictfp attribute and all calls within the function
4791 // must also have the strictfp attribute. This latter restriction is
4792 // necessary to prevent unwanted libcall simplification when a function is
4793 // being cloned (such as for inlining).
4794 //
4795 // The "dangling" strictfp attribute usage was only used to prevent constant
4796 // folding and other libcall simplification. The nobuiltin attribute on the
4797 // callsite has the same effect.
4798 struct StrictFPUpgradeVisitor : public InstVisitor<StrictFPUpgradeVisitor> {
4799 StrictFPUpgradeVisitor() = default;
4800
visitCallBase__anon0722971b0511::StrictFPUpgradeVisitor4801 void visitCallBase(CallBase &Call) {
4802 if (!Call.isStrictFP())
4803 return;
4804 if (isa<ConstrainedFPIntrinsic>(&Call))
4805 return;
4806 // If we get here, the caller doesn't have the strictfp attribute
4807 // but this callsite does. Replace the strictfp attribute with nobuiltin.
4808 Call.removeFnAttr(Attribute::StrictFP);
4809 Call.addFnAttr(Attribute::NoBuiltin);
4810 }
4811 };
4812 } // namespace
4813
UpgradeFunctionAttributes(Function & F)4814 void llvm::UpgradeFunctionAttributes(Function &F) {
4815 // If a function definition doesn't have the strictfp attribute,
4816 // convert any callsite strictfp attributes to nobuiltin.
4817 if (!F.isDeclaration() && !F.hasFnAttribute(Attribute::StrictFP)) {
4818 StrictFPUpgradeVisitor SFPV;
4819 SFPV.visit(F);
4820 }
4821
4822 // Remove all incompatibile attributes from function.
4823 F.removeRetAttrs(AttributeFuncs::typeIncompatible(F.getReturnType()));
4824 for (auto &Arg : F.args())
4825 Arg.removeAttrs(AttributeFuncs::typeIncompatible(Arg.getType()));
4826 }
4827
isOldLoopArgument(Metadata * MD)4828 static bool isOldLoopArgument(Metadata *MD) {
4829 auto *T = dyn_cast_or_null<MDTuple>(MD);
4830 if (!T)
4831 return false;
4832 if (T->getNumOperands() < 1)
4833 return false;
4834 auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
4835 if (!S)
4836 return false;
4837 return S->getString().startswith("llvm.vectorizer.");
4838 }
4839
upgradeLoopTag(LLVMContext & C,StringRef OldTag)4840 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
4841 StringRef OldPrefix = "llvm.vectorizer.";
4842 assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
4843
4844 if (OldTag == "llvm.vectorizer.unroll")
4845 return MDString::get(C, "llvm.loop.interleave.count");
4846
4847 return MDString::get(
4848 C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
4849 .str());
4850 }
4851
upgradeLoopArgument(Metadata * MD)4852 static Metadata *upgradeLoopArgument(Metadata *MD) {
4853 auto *T = dyn_cast_or_null<MDTuple>(MD);
4854 if (!T)
4855 return MD;
4856 if (T->getNumOperands() < 1)
4857 return MD;
4858 auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
4859 if (!OldTag)
4860 return MD;
4861 if (!OldTag->getString().startswith("llvm.vectorizer."))
4862 return MD;
4863
4864 // This has an old tag. Upgrade it.
4865 SmallVector<Metadata *, 8> Ops;
4866 Ops.reserve(T->getNumOperands());
4867 Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
4868 for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
4869 Ops.push_back(T->getOperand(I));
4870
4871 return MDTuple::get(T->getContext(), Ops);
4872 }
4873
upgradeInstructionLoopAttachment(MDNode & N)4874 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
4875 auto *T = dyn_cast<MDTuple>(&N);
4876 if (!T)
4877 return &N;
4878
4879 if (none_of(T->operands(), isOldLoopArgument))
4880 return &N;
4881
4882 SmallVector<Metadata *, 8> Ops;
4883 Ops.reserve(T->getNumOperands());
4884 for (Metadata *MD : T->operands())
4885 Ops.push_back(upgradeLoopArgument(MD));
4886
4887 return MDTuple::get(T->getContext(), Ops);
4888 }
4889
UpgradeDataLayoutString(StringRef DL,StringRef TT)4890 std::string llvm::UpgradeDataLayoutString(StringRef DL, StringRef TT) {
4891 Triple T(TT);
4892 // For AMDGPU we uprgrade older DataLayouts to include the default globals
4893 // address space of 1.
4894 if (T.isAMDGPU() && !DL.contains("-G") && !DL.startswith("G")) {
4895 return DL.empty() ? std::string("G1") : (DL + "-G1").str();
4896 }
4897
4898 if (T.isRISCV64()) {
4899 // Make i32 a native type for 64-bit RISC-V.
4900 auto I = DL.find("-n64-");
4901 if (I != StringRef::npos)
4902 return (DL.take_front(I) + "-n32:64-" + DL.drop_front(I + 5)).str();
4903 return DL.str();
4904 }
4905
4906 std::string Res = DL.str();
4907 if (!T.isX86())
4908 return Res;
4909
4910 // If the datalayout matches the expected format, add pointer size address
4911 // spaces to the datalayout.
4912 std::string AddrSpaces = "-p270:32:32-p271:32:32-p272:64:64";
4913 if (!DL.contains(AddrSpaces)) {
4914 SmallVector<StringRef, 4> Groups;
4915 Regex R("(e-m:[a-z](-p:32:32)?)(-[if]64:.*$)");
4916 if (R.match(DL, &Groups))
4917 Res = (Groups[1] + AddrSpaces + Groups[3]).str();
4918 }
4919
4920 // For 32-bit MSVC targets, raise the alignment of f80 values to 16 bytes.
4921 // Raising the alignment is safe because Clang did not produce f80 values in
4922 // the MSVC environment before this upgrade was added.
4923 if (T.isWindowsMSVCEnvironment() && !T.isArch64Bit()) {
4924 StringRef Ref = Res;
4925 auto I = Ref.find("-f80:32-");
4926 if (I != StringRef::npos)
4927 Res = (Ref.take_front(I) + "-f80:128-" + Ref.drop_front(I + 8)).str();
4928 }
4929
4930 return Res;
4931 }
4932
UpgradeAttributes(AttrBuilder & B)4933 void llvm::UpgradeAttributes(AttrBuilder &B) {
4934 StringRef FramePointer;
4935 Attribute A = B.getAttribute("no-frame-pointer-elim");
4936 if (A.isValid()) {
4937 // The value can be "true" or "false".
4938 FramePointer = A.getValueAsString() == "true" ? "all" : "none";
4939 B.removeAttribute("no-frame-pointer-elim");
4940 }
4941 if (B.contains("no-frame-pointer-elim-non-leaf")) {
4942 // The value is ignored. "no-frame-pointer-elim"="true" takes priority.
4943 if (FramePointer != "all")
4944 FramePointer = "non-leaf";
4945 B.removeAttribute("no-frame-pointer-elim-non-leaf");
4946 }
4947 if (!FramePointer.empty())
4948 B.addAttribute("frame-pointer", FramePointer);
4949
4950 A = B.getAttribute("null-pointer-is-valid");
4951 if (A.isValid()) {
4952 // The value can be "true" or "false".
4953 bool NullPointerIsValid = A.getValueAsString() == "true";
4954 B.removeAttribute("null-pointer-is-valid");
4955 if (NullPointerIsValid)
4956 B.addAttribute(Attribute::NullPointerIsValid);
4957 }
4958 }
4959
UpgradeOperandBundles(std::vector<OperandBundleDef> & Bundles)4960 void llvm::UpgradeOperandBundles(std::vector<OperandBundleDef> &Bundles) {
4961
4962 // clang.arc.attachedcall bundles are now required to have an operand.
4963 // If they don't, it's okay to drop them entirely: when there is an operand,
4964 // the "attachedcall" is meaningful and required, but without an operand,
4965 // it's just a marker NOP. Dropping it merely prevents an optimization.
4966 erase_if(Bundles, [&](OperandBundleDef &OBD) {
4967 return OBD.getTag() == "clang.arc.attachedcall" &&
4968 OBD.inputs().empty();
4969 });
4970 }
4971