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