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