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.vfmsubadd.") || // Added in 7.0
103       Name.startswith("fma.vfnmadd.") || // Added in 7.0
104       Name.startswith("fma.vfnmsub.") || // Added in 7.0
105       Name.startswith("avx512.mask.vfmadd.") || // Added in 7.0
106       Name.startswith("avx512.mask.vfnmadd.") || // Added in 7.0
107       Name.startswith("avx512.mask.vfnmsub.") || // Added in 7.0
108       Name.startswith("avx512.mask3.vfmadd.") || // Added in 7.0
109       Name.startswith("avx512.maskz.vfmadd.") || // Added in 7.0
110       Name.startswith("avx512.mask3.vfmsub.") || // Added in 7.0
111       Name.startswith("avx512.mask3.vfnmsub.") || // Added in 7.0
112       Name.startswith("avx512.mask.vfmaddsub.") || // Added in 7.0
113       Name.startswith("avx512.maskz.vfmaddsub.") || // Added in 7.0
114       Name.startswith("avx512.mask3.vfmaddsub.") || // Added in 7.0
115       Name.startswith("avx512.mask3.vfmsubadd.") || // Added in 7.0
116       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
117       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
118       Name.startswith("avx512.kunpck") || //added in 6.0
119       Name.startswith("avx2.pabs.") || // Added in 6.0
120       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
121       Name.startswith("avx512.broadcastm") || // Added in 6.0
122       Name == "sse.sqrt.ss" || // Added in 7.0
123       Name == "sse2.sqrt.sd" || // Added in 7.0
124       Name.startswith("avx512.mask.sqrt.p") || // Added in 7.0
125       Name.startswith("avx.sqrt.p") || // Added in 7.0
126       Name.startswith("sse2.sqrt.p") || // Added in 7.0
127       Name.startswith("sse.sqrt.p") || // Added in 7.0
128       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
129       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
130       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
131       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
132       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
133       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
134       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
135       Name.startswith("avx.vperm2f128.") || // Added in 6.0
136       Name == "avx2.vperm2i128" || // Added in 6.0
137       Name == "sse.add.ss" || // Added in 4.0
138       Name == "sse2.add.sd" || // Added in 4.0
139       Name == "sse.sub.ss" || // Added in 4.0
140       Name == "sse2.sub.sd" || // Added in 4.0
141       Name == "sse.mul.ss" || // Added in 4.0
142       Name == "sse2.mul.sd" || // Added in 4.0
143       Name == "sse.div.ss" || // Added in 4.0
144       Name == "sse2.div.sd" || // Added in 4.0
145       Name == "sse41.pmaxsb" || // Added in 3.9
146       Name == "sse2.pmaxs.w" || // Added in 3.9
147       Name == "sse41.pmaxsd" || // Added in 3.9
148       Name == "sse2.pmaxu.b" || // Added in 3.9
149       Name == "sse41.pmaxuw" || // Added in 3.9
150       Name == "sse41.pmaxud" || // Added in 3.9
151       Name == "sse41.pminsb" || // Added in 3.9
152       Name == "sse2.pmins.w" || // Added in 3.9
153       Name == "sse41.pminsd" || // Added in 3.9
154       Name == "sse2.pminu.b" || // Added in 3.9
155       Name == "sse41.pminuw" || // Added in 3.9
156       Name == "sse41.pminud" || // Added in 3.9
157       Name == "avx512.kand.w" || // Added in 7.0
158       Name == "avx512.kandn.w" || // Added in 7.0
159       Name == "avx512.knot.w" || // Added in 7.0
160       Name == "avx512.kor.w" || // Added in 7.0
161       Name == "avx512.kxor.w" || // Added in 7.0
162       Name == "avx512.kxnor.w" || // Added in 7.0
163       Name == "avx512.kortestc.w" || // Added in 7.0
164       Name == "avx512.kortestz.w" || // Added in 7.0
165       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
166       Name.startswith("avx2.pmax") || // Added in 3.9
167       Name.startswith("avx2.pmin") || // Added in 3.9
168       Name.startswith("avx512.mask.pmax") || // Added in 4.0
169       Name.startswith("avx512.mask.pmin") || // Added in 4.0
170       Name.startswith("avx2.vbroadcast") || // Added in 3.8
171       Name.startswith("avx2.pbroadcast") || // Added in 3.8
172       Name.startswith("avx.vpermil.") || // Added in 3.1
173       Name.startswith("sse2.pshuf") || // Added in 3.9
174       Name.startswith("avx512.pbroadcast") || // Added in 3.9
175       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
176       Name.startswith("avx512.mask.movddup") || // Added in 3.9
177       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
178       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
179       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
180       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
181       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
182       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
183       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
184       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
185       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
186       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
187       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
188       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
189       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
190       Name.startswith("avx512.mask.pand.") || // Added in 3.9
191       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
192       Name.startswith("avx512.mask.por.") || // Added in 3.9
193       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
194       Name.startswith("avx512.mask.and.") || // Added in 3.9
195       Name.startswith("avx512.mask.andn.") || // Added in 3.9
196       Name.startswith("avx512.mask.or.") || // Added in 3.9
197       Name.startswith("avx512.mask.xor.") || // Added in 3.9
198       Name.startswith("avx512.mask.padd.") || // Added in 4.0
199       Name.startswith("avx512.mask.psub.") || // Added in 4.0
200       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
201       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
202       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
203       Name.startswith("avx512.mask.cvtudq2ps.") || // Added in 7.0 updated 9.0
204       Name.startswith("avx512.mask.cvtqq2pd.") || // Added in 7.0 updated 9.0
205       Name.startswith("avx512.mask.cvtuqq2pd.") || // Added in 7.0 updated 9.0
206       Name.startswith("avx512.mask.cvtdq2ps.") || // Added in 7.0 updated 9.0
207       Name == "avx512.mask.cvtqq2ps.256" || // Added in 9.0
208       Name == "avx512.mask.cvtqq2ps.512" || // Added in 9.0
209       Name == "avx512.mask.cvtuqq2ps.256" || // Added in 9.0
210       Name == "avx512.mask.cvtuqq2ps.512" || // Added in 9.0
211       Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
212       Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
213       Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
214       Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
215       Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
216       Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
217       Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
218       Name == "avx512.cvtusi2sd" || // Added in 7.0
219       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
220       Name == "sse2.pmulu.dq" || // Added in 7.0
221       Name == "sse41.pmuldq" || // Added in 7.0
222       Name == "avx2.pmulu.dq" || // Added in 7.0
223       Name == "avx2.pmul.dq" || // Added in 7.0
224       Name == "avx512.pmulu.dq.512" || // Added in 7.0
225       Name == "avx512.pmul.dq.512" || // Added in 7.0
226       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
227       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
228       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
229       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
230       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
231       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
232       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
233       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
234       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
235       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
236       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
237       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
238       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
239       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
240       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
241       Name.startswith("avx512.mask.cmp.p") || // Added in 7.0
242       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
243       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
244       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
245       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
246       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
247       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
248       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
249       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
250       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
251       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
252       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
253       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
254       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
255       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
256       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
257       Name.startswith("avx512.mask.pslli") || // Added in 4.0
258       Name.startswith("avx512.mask.psrai") || // Added in 4.0
259       Name.startswith("avx512.mask.psrli") || // Added in 4.0
260       Name.startswith("avx512.mask.psllv") || // Added in 4.0
261       Name.startswith("avx512.mask.psrav") || // Added in 4.0
262       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
263       Name.startswith("sse41.pmovsx") || // Added in 3.8
264       Name.startswith("sse41.pmovzx") || // Added in 3.9
265       Name.startswith("avx2.pmovsx") || // Added in 3.9
266       Name.startswith("avx2.pmovzx") || // Added in 3.9
267       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
268       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
269       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
270       Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
271       Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
272       Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
273       Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
274       Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
275       Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
276       Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
277       Name.startswith("avx512.mask.vpdpbusd.") || // Added in 7.0
278       Name.startswith("avx512.maskz.vpdpbusd.") || // Added in 7.0
279       Name.startswith("avx512.mask.vpdpbusds.") || // Added in 7.0
280       Name.startswith("avx512.maskz.vpdpbusds.") || // Added in 7.0
281       Name.startswith("avx512.mask.vpdpwssd.") || // Added in 7.0
282       Name.startswith("avx512.maskz.vpdpwssd.") || // Added in 7.0
283       Name.startswith("avx512.mask.vpdpwssds.") || // Added in 7.0
284       Name.startswith("avx512.maskz.vpdpwssds.") || // Added in 7.0
285       Name.startswith("avx512.mask.dbpsadbw.") || // Added in 7.0
286       Name.startswith("avx512.mask.vpshld.") || // Added in 7.0
287       Name.startswith("avx512.mask.vpshrd.") || // Added in 7.0
288       Name.startswith("avx512.mask.vpshldv.") || // Added in 8.0
289       Name.startswith("avx512.mask.vpshrdv.") || // Added in 8.0
290       Name.startswith("avx512.maskz.vpshldv.") || // Added in 8.0
291       Name.startswith("avx512.maskz.vpshrdv.") || // Added in 8.0
292       Name.startswith("avx512.vpshld.") || // Added in 8.0
293       Name.startswith("avx512.vpshrd.") || // Added in 8.0
294       Name.startswith("avx512.mask.add.p") || // Added in 7.0. 128/256 in 4.0
295       Name.startswith("avx512.mask.sub.p") || // Added in 7.0. 128/256 in 4.0
296       Name.startswith("avx512.mask.mul.p") || // Added in 7.0. 128/256 in 4.0
297       Name.startswith("avx512.mask.div.p") || // Added in 7.0. 128/256 in 4.0
298       Name.startswith("avx512.mask.max.p") || // Added in 7.0. 128/256 in 5.0
299       Name.startswith("avx512.mask.min.p") || // Added in 7.0. 128/256 in 5.0
300       Name.startswith("avx512.mask.fpclass.p") || // Added in 7.0
301       Name.startswith("avx512.mask.vpshufbitqmb.") || // Added in 8.0
302       Name.startswith("avx512.mask.pmultishift.qb.") || // Added in 8.0
303       Name.startswith("avx512.mask.conflict.") || // Added in 9.0
304       Name == "avx512.mask.pmov.qd.256" || // Added in 9.0
305       Name == "avx512.mask.pmov.qd.512" || // Added in 9.0
306       Name == "avx512.mask.pmov.wb.256" || // Added in 9.0
307       Name == "avx512.mask.pmov.wb.512" || // Added in 9.0
308       Name == "sse.cvtsi2ss" || // Added in 7.0
309       Name == "sse.cvtsi642ss" || // Added in 7.0
310       Name == "sse2.cvtsi2sd" || // Added in 7.0
311       Name == "sse2.cvtsi642sd" || // Added in 7.0
312       Name == "sse2.cvtss2sd" || // Added in 7.0
313       Name == "sse2.cvtdq2pd" || // Added in 3.9
314       Name == "sse2.cvtdq2ps" || // Added in 7.0
315       Name == "sse2.cvtps2pd" || // Added in 3.9
316       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
317       Name == "avx.cvtdq2.ps.256" || // Added in 7.0
318       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
319       Name.startswith("avx.vinsertf128.") || // Added in 3.7
320       Name == "avx2.vinserti128" || // Added in 3.7
321       Name.startswith("avx512.mask.insert") || // Added in 4.0
322       Name.startswith("avx.vextractf128.") || // Added in 3.7
323       Name == "avx2.vextracti128" || // Added in 3.7
324       Name.startswith("avx512.mask.vextract") || // Added in 4.0
325       Name.startswith("sse4a.movnt.") || // Added in 3.9
326       Name.startswith("avx.movnt.") || // Added in 3.2
327       Name.startswith("avx512.storent.") || // Added in 3.9
328       Name == "sse41.movntdqa" || // Added in 5.0
329       Name == "avx2.movntdqa" || // Added in 5.0
330       Name == "avx512.movntdqa" || // Added in 5.0
331       Name == "sse2.storel.dq" || // Added in 3.9
332       Name.startswith("sse.storeu.") || // Added in 3.9
333       Name.startswith("sse2.storeu.") || // Added in 3.9
334       Name.startswith("avx.storeu.") || // Added in 3.9
335       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
336       Name.startswith("avx512.mask.store.p") || // Added in 3.9
337       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
338       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
339       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
340       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
341       Name == "avx512.mask.store.ss" || // Added in 7.0
342       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
343       Name.startswith("avx512.mask.load.") || // Added in 3.9
344       Name.startswith("avx512.mask.expand.load.") || // Added in 7.0
345       Name.startswith("avx512.mask.compress.store.") || // Added in 7.0
346       Name.startswith("avx512.mask.expand.b") || // Added in 9.0
347       Name.startswith("avx512.mask.expand.w") || // Added in 9.0
348       Name.startswith("avx512.mask.expand.d") || // Added in 9.0
349       Name.startswith("avx512.mask.expand.q") || // Added in 9.0
350       Name.startswith("avx512.mask.expand.p") || // Added in 9.0
351       Name.startswith("avx512.mask.compress.b") || // Added in 9.0
352       Name.startswith("avx512.mask.compress.w") || // Added in 9.0
353       Name.startswith("avx512.mask.compress.d") || // Added in 9.0
354       Name.startswith("avx512.mask.compress.q") || // Added in 9.0
355       Name.startswith("avx512.mask.compress.p") || // Added in 9.0
356       Name == "sse42.crc32.64.8" || // Added in 3.4
357       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
358       Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
359       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
360       Name.startswith("avx512.mask.valign.") || // Added in 4.0
361       Name.startswith("sse2.psll.dq") || // Added in 3.7
362       Name.startswith("sse2.psrl.dq") || // Added in 3.7
363       Name.startswith("avx2.psll.dq") || // Added in 3.7
364       Name.startswith("avx2.psrl.dq") || // Added in 3.7
365       Name.startswith("avx512.psll.dq") || // Added in 3.9
366       Name.startswith("avx512.psrl.dq") || // Added in 3.9
367       Name == "sse41.pblendw" || // Added in 3.7
368       Name.startswith("sse41.blendp") || // Added in 3.7
369       Name.startswith("avx.blend.p") || // Added in 3.7
370       Name == "avx2.pblendw" || // Added in 3.7
371       Name.startswith("avx2.pblendd.") || // Added in 3.7
372       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
373       Name == "avx2.vbroadcasti128" || // Added in 3.7
374       Name.startswith("avx512.mask.broadcastf") || // Added in 6.0
375       Name.startswith("avx512.mask.broadcasti") || // Added in 6.0
376       Name == "xop.vpcmov" || // Added in 3.8
377       Name == "xop.vpcmov.256" || // Added in 5.0
378       Name.startswith("avx512.mask.move.s") || // Added in 4.0
379       Name.startswith("avx512.cvtmask2") || // Added in 5.0
380       Name.startswith("xop.vpcom") || // Added in 3.2, Updated in 9.0
381       Name.startswith("xop.vprot") || // Added in 8.0
382       Name.startswith("avx512.prol") || // Added in 8.0
383       Name.startswith("avx512.pror") || // Added in 8.0
384       Name.startswith("avx512.mask.prorv.") || // Added in 8.0
385       Name.startswith("avx512.mask.pror.") ||  // Added in 8.0
386       Name.startswith("avx512.mask.prolv.") || // Added in 8.0
387       Name.startswith("avx512.mask.prol.") ||  // Added in 8.0
388       Name.startswith("avx512.ptestm") || //Added in 6.0
389       Name.startswith("avx512.ptestnm") || //Added in 6.0
390       Name.startswith("avx512.mask.pavg")) // Added in 6.0
391     return true;
392 
393   return false;
394 }
395 
396 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
397                                         Function *&NewFn) {
398   // Only handle intrinsics that start with "x86.".
399   if (!Name.startswith("x86."))
400     return false;
401   // Remove "x86." prefix.
402   Name = Name.substr(4);
403 
404   if (ShouldUpgradeX86Intrinsic(F, Name)) {
405     NewFn = nullptr;
406     return true;
407   }
408 
409   if (Name == "rdtscp") { // Added in 8.0
410     // If this intrinsic has 0 operands, it's the new version.
411     if (F->getFunctionType()->getNumParams() == 0)
412       return false;
413 
414     rename(F);
415     NewFn = Intrinsic::getDeclaration(F->getParent(),
416                                       Intrinsic::x86_rdtscp);
417     return true;
418   }
419 
420   // SSE4.1 ptest functions may have an old signature.
421   if (Name.startswith("sse41.ptest")) { // Added in 3.2
422     if (Name.substr(11) == "c")
423       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
424     if (Name.substr(11) == "z")
425       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
426     if (Name.substr(11) == "nzc")
427       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
428   }
429   // Several blend and other instructions with masks used the wrong number of
430   // bits.
431   if (Name == "sse41.insertps") // Added in 3.6
432     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
433                                             NewFn);
434   if (Name == "sse41.dppd") // Added in 3.6
435     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
436                                             NewFn);
437   if (Name == "sse41.dpps") // Added in 3.6
438     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
439                                             NewFn);
440   if (Name == "sse41.mpsadbw") // Added in 3.6
441     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
442                                             NewFn);
443   if (Name == "avx.dp.ps.256") // Added in 3.6
444     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
445                                             NewFn);
446   if (Name == "avx2.mpsadbw") // Added in 3.6
447     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
448                                             NewFn);
449 
450   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
451   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
452     rename(F);
453     NewFn = Intrinsic::getDeclaration(F->getParent(),
454                                       Intrinsic::x86_xop_vfrcz_ss);
455     return true;
456   }
457   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
458     rename(F);
459     NewFn = Intrinsic::getDeclaration(F->getParent(),
460                                       Intrinsic::x86_xop_vfrcz_sd);
461     return true;
462   }
463   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
464   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
465     auto Idx = F->getFunctionType()->getParamType(2);
466     if (Idx->isFPOrFPVectorTy()) {
467       rename(F);
468       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
469       unsigned EltSize = Idx->getScalarSizeInBits();
470       Intrinsic::ID Permil2ID;
471       if (EltSize == 64 && IdxSize == 128)
472         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
473       else if (EltSize == 32 && IdxSize == 128)
474         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
475       else if (EltSize == 64 && IdxSize == 256)
476         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
477       else
478         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
479       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
480       return true;
481     }
482   }
483 
484   if (Name == "seh.recoverfp") {
485     NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_recoverfp);
486     return true;
487   }
488 
489   return false;
490 }
491 
492 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
493   assert(F && "Illegal to upgrade a non-existent Function.");
494 
495   // Quickly eliminate it, if it's not a candidate.
496   StringRef Name = F->getName();
497   if (Name.size() <= 8 || !Name.startswith("llvm."))
498     return false;
499   Name = Name.substr(5); // Strip off "llvm."
500 
501   switch (Name[0]) {
502   default: break;
503   case 'a': {
504     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
505       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
506                                         F->arg_begin()->getType());
507       return true;
508     }
509     if (Name.startswith("arm.neon.vclz")) {
510       Type* args[2] = {
511         F->arg_begin()->getType(),
512         Type::getInt1Ty(F->getContext())
513       };
514       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
515       // the end of the name. Change name from llvm.arm.neon.vclz.* to
516       //  llvm.ctlz.*
517       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
518       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
519                                "llvm.ctlz." + Name.substr(14), F->getParent());
520       return true;
521     }
522     if (Name.startswith("arm.neon.vcnt")) {
523       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
524                                         F->arg_begin()->getType());
525       return true;
526     }
527     static const Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
528     if (vldRegex.match(Name)) {
529       auto fArgs = F->getFunctionType()->params();
530       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
531       // Can't use Intrinsic::getDeclaration here as the return types might
532       // then only be structurally equal.
533       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
534       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
535                                "llvm." + Name + ".p0i8", F->getParent());
536       return true;
537     }
538     static const Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
539     if (vstRegex.match(Name)) {
540       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
541                                                 Intrinsic::arm_neon_vst2,
542                                                 Intrinsic::arm_neon_vst3,
543                                                 Intrinsic::arm_neon_vst4};
544 
545       static const Intrinsic::ID StoreLaneInts[] = {
546         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
547         Intrinsic::arm_neon_vst4lane
548       };
549 
550       auto fArgs = F->getFunctionType()->params();
551       Type *Tys[] = {fArgs[0], fArgs[1]};
552       if (Name.find("lane") == StringRef::npos)
553         NewFn = Intrinsic::getDeclaration(F->getParent(),
554                                           StoreInts[fArgs.size() - 3], Tys);
555       else
556         NewFn = Intrinsic::getDeclaration(F->getParent(),
557                                           StoreLaneInts[fArgs.size() - 5], Tys);
558       return true;
559     }
560     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
561       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
562       return true;
563     }
564     if (Name.startswith("arm.neon.vqadds.")) {
565       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::sadd_sat,
566                                         F->arg_begin()->getType());
567       return true;
568     }
569     if (Name.startswith("arm.neon.vqaddu.")) {
570       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::uadd_sat,
571                                         F->arg_begin()->getType());
572       return true;
573     }
574     if (Name.startswith("arm.neon.vqsubs.")) {
575       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ssub_sat,
576                                         F->arg_begin()->getType());
577       return true;
578     }
579     if (Name.startswith("arm.neon.vqsubu.")) {
580       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::usub_sat,
581                                         F->arg_begin()->getType());
582       return true;
583     }
584     if (Name.startswith("aarch64.neon.addp")) {
585       if (F->arg_size() != 2)
586         break; // Invalid IR.
587       VectorType *Ty = dyn_cast<VectorType>(F->getReturnType());
588       if (Ty && Ty->getElementType()->isFloatingPointTy()) {
589         NewFn = Intrinsic::getDeclaration(F->getParent(),
590                                           Intrinsic::aarch64_neon_faddp, Ty);
591         return true;
592       }
593     }
594     break;
595   }
596 
597   case 'c': {
598     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
599       rename(F);
600       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
601                                         F->arg_begin()->getType());
602       return true;
603     }
604     if (Name.startswith("cttz.") && F->arg_size() == 1) {
605       rename(F);
606       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
607                                         F->arg_begin()->getType());
608       return true;
609     }
610     break;
611   }
612   case 'd': {
613     if (Name == "dbg.value" && F->arg_size() == 4) {
614       rename(F);
615       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
616       return true;
617     }
618     break;
619   }
620   case 'e': {
621     SmallVector<StringRef, 2> Groups;
622     static const Regex R("^experimental.vector.reduce.([a-z]+)\\.[fi][0-9]+");
623     if (R.match(Name, &Groups)) {
624       Intrinsic::ID ID = Intrinsic::not_intrinsic;
625       if (Groups[1] == "fadd")
626         ID = Intrinsic::experimental_vector_reduce_v2_fadd;
627       if (Groups[1] == "fmul")
628         ID = Intrinsic::experimental_vector_reduce_v2_fmul;
629 
630       if (ID != Intrinsic::not_intrinsic) {
631         rename(F);
632         auto Args = F->getFunctionType()->params();
633         Type *Tys[] = {F->getFunctionType()->getReturnType(), Args[1]};
634         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
635         return true;
636       }
637     }
638     break;
639   }
640   case 'i':
641   case 'l': {
642     bool IsLifetimeStart = Name.startswith("lifetime.start");
643     if (IsLifetimeStart || Name.startswith("invariant.start")) {
644       Intrinsic::ID ID = IsLifetimeStart ?
645         Intrinsic::lifetime_start : Intrinsic::invariant_start;
646       auto Args = F->getFunctionType()->params();
647       Type* ObjectPtr[1] = {Args[1]};
648       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
649         rename(F);
650         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
651         return true;
652       }
653     }
654 
655     bool IsLifetimeEnd = Name.startswith("lifetime.end");
656     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
657       Intrinsic::ID ID = IsLifetimeEnd ?
658         Intrinsic::lifetime_end : Intrinsic::invariant_end;
659 
660       auto Args = F->getFunctionType()->params();
661       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
662       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
663         rename(F);
664         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
665         return true;
666       }
667     }
668     if (Name.startswith("invariant.group.barrier")) {
669       // Rename invariant.group.barrier to launder.invariant.group
670       auto Args = F->getFunctionType()->params();
671       Type* ObjectPtr[1] = {Args[0]};
672       rename(F);
673       NewFn = Intrinsic::getDeclaration(F->getParent(),
674           Intrinsic::launder_invariant_group, ObjectPtr);
675       return true;
676 
677     }
678 
679     break;
680   }
681   case 'm': {
682     if (Name.startswith("masked.load.")) {
683       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
684       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
685         rename(F);
686         NewFn = Intrinsic::getDeclaration(F->getParent(),
687                                           Intrinsic::masked_load,
688                                           Tys);
689         return true;
690       }
691     }
692     if (Name.startswith("masked.store.")) {
693       auto Args = F->getFunctionType()->params();
694       Type *Tys[] = { Args[0], Args[1] };
695       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
696         rename(F);
697         NewFn = Intrinsic::getDeclaration(F->getParent(),
698                                           Intrinsic::masked_store,
699                                           Tys);
700         return true;
701       }
702     }
703     // Renaming gather/scatter intrinsics with no address space overloading
704     // to the new overload which includes an address space
705     if (Name.startswith("masked.gather.")) {
706       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
707       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
708         rename(F);
709         NewFn = Intrinsic::getDeclaration(F->getParent(),
710                                           Intrinsic::masked_gather, Tys);
711         return true;
712       }
713     }
714     if (Name.startswith("masked.scatter.")) {
715       auto Args = F->getFunctionType()->params();
716       Type *Tys[] = {Args[0], Args[1]};
717       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
718         rename(F);
719         NewFn = Intrinsic::getDeclaration(F->getParent(),
720                                           Intrinsic::masked_scatter, Tys);
721         return true;
722       }
723     }
724     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
725     // alignment parameter to embedding the alignment as an attribute of
726     // the pointer args.
727     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
728       rename(F);
729       // Get the types of dest, src, and len
730       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
731       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
732                                         ParamTypes);
733       return true;
734     }
735     if (Name.startswith("memmove.") && F->arg_size() == 5) {
736       rename(F);
737       // Get the types of dest, src, and len
738       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
739       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
740                                         ParamTypes);
741       return true;
742     }
743     if (Name.startswith("memset.") && F->arg_size() == 5) {
744       rename(F);
745       // Get the types of dest, and len
746       const auto *FT = F->getFunctionType();
747       Type *ParamTypes[2] = {
748           FT->getParamType(0), // Dest
749           FT->getParamType(2)  // len
750       };
751       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
752                                         ParamTypes);
753       return true;
754     }
755     break;
756   }
757   case 'n': {
758     if (Name.startswith("nvvm.")) {
759       Name = Name.substr(5);
760 
761       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
762       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
763                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
764                               .Case("clz.i", Intrinsic::ctlz)
765                               .Case("popc.i", Intrinsic::ctpop)
766                               .Default(Intrinsic::not_intrinsic);
767       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
768         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
769                                           {F->getReturnType()});
770         return true;
771       }
772 
773       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
774       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
775       //
776       // TODO: We could add lohi.i2d.
777       bool Expand = StringSwitch<bool>(Name)
778                         .Cases("abs.i", "abs.ll", true)
779                         .Cases("clz.ll", "popc.ll", "h2f", true)
780                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
781                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
782                         .StartsWith("atomic.load.add.f32.p", true)
783                         .StartsWith("atomic.load.add.f64.p", true)
784                         .Default(false);
785       if (Expand) {
786         NewFn = nullptr;
787         return true;
788       }
789     }
790     break;
791   }
792   case 'o':
793     // We only need to change the name to match the mangling including the
794     // address space.
795     if (Name.startswith("objectsize.")) {
796       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
797       if (F->arg_size() == 2 || F->arg_size() == 3 ||
798           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
799         rename(F);
800         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
801                                           Tys);
802         return true;
803       }
804     }
805     break;
806 
807   case 'p':
808     if (Name == "prefetch") {
809       // Handle address space overloading.
810       Type *Tys[] = {F->arg_begin()->getType()};
811       if (F->getName() != Intrinsic::getName(Intrinsic::prefetch, Tys)) {
812         rename(F);
813         NewFn =
814             Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch, Tys);
815         return true;
816       }
817     }
818     break;
819 
820   case 's':
821     if (Name == "stackprotectorcheck") {
822       NewFn = nullptr;
823       return true;
824     }
825     break;
826 
827   case 'x':
828     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
829       return true;
830   }
831   // Remangle our intrinsic since we upgrade the mangling
832   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
833   if (Result != None) {
834     NewFn = Result.getValue();
835     return true;
836   }
837 
838   //  This may not belong here. This function is effectively being overloaded
839   //  to both detect an intrinsic which needs upgrading, and to provide the
840   //  upgraded form of the intrinsic. We should perhaps have two separate
841   //  functions for this.
842   return false;
843 }
844 
845 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
846   NewFn = nullptr;
847   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
848   assert(F != NewFn && "Intrinsic function upgraded to the same function");
849 
850   // Upgrade intrinsic attributes.  This does not change the function.
851   if (NewFn)
852     F = NewFn;
853   if (Intrinsic::ID id = F->getIntrinsicID())
854     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
855   return Upgraded;
856 }
857 
858 GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
859   if (!(GV->hasName() && (GV->getName() == "llvm.global_ctors" ||
860                           GV->getName() == "llvm.global_dtors")) ||
861       !GV->hasInitializer())
862     return nullptr;
863   ArrayType *ATy = dyn_cast<ArrayType>(GV->getValueType());
864   if (!ATy)
865     return nullptr;
866   StructType *STy = dyn_cast<StructType>(ATy->getElementType());
867   if (!STy || STy->getNumElements() != 2)
868     return nullptr;
869 
870   LLVMContext &C = GV->getContext();
871   IRBuilder<> IRB(C);
872   auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
873                                IRB.getInt8PtrTy());
874   Constant *Init = GV->getInitializer();
875   unsigned N = Init->getNumOperands();
876   std::vector<Constant *> NewCtors(N);
877   for (unsigned i = 0; i != N; ++i) {
878     auto Ctor = cast<Constant>(Init->getOperand(i));
879     NewCtors[i] = ConstantStruct::get(
880         EltTy, Ctor->getAggregateElement(0u), Ctor->getAggregateElement(1),
881         Constant::getNullValue(IRB.getInt8PtrTy()));
882   }
883   Constant *NewInit = ConstantArray::get(ArrayType::get(EltTy, N), NewCtors);
884 
885   return new GlobalVariable(NewInit->getType(), false, GV->getLinkage(),
886                             NewInit, GV->getName());
887 }
888 
889 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
890 // to byte shuffles.
891 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
892                                          Value *Op, unsigned Shift) {
893   Type *ResultTy = Op->getType();
894   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
895 
896   // Bitcast from a 64-bit element type to a byte element type.
897   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
898   Op = Builder.CreateBitCast(Op, VecTy, "cast");
899 
900   // We'll be shuffling in zeroes.
901   Value *Res = Constant::getNullValue(VecTy);
902 
903   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
904   // we'll just return the zero vector.
905   if (Shift < 16) {
906     uint32_t Idxs[64];
907     // 256/512-bit version is split into 2/4 16-byte lanes.
908     for (unsigned l = 0; l != NumElts; l += 16)
909       for (unsigned i = 0; i != 16; ++i) {
910         unsigned Idx = NumElts + i - Shift;
911         if (Idx < NumElts)
912           Idx -= NumElts - 16; // end of lane, switch operand.
913         Idxs[l + i] = Idx + l;
914       }
915 
916     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
917   }
918 
919   // Bitcast back to a 64-bit element type.
920   return Builder.CreateBitCast(Res, ResultTy, "cast");
921 }
922 
923 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
924 // to byte shuffles.
925 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
926                                          unsigned Shift) {
927   Type *ResultTy = Op->getType();
928   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
929 
930   // Bitcast from a 64-bit element type to a byte element type.
931   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
932   Op = Builder.CreateBitCast(Op, VecTy, "cast");
933 
934   // We'll be shuffling in zeroes.
935   Value *Res = Constant::getNullValue(VecTy);
936 
937   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
938   // we'll just return the zero vector.
939   if (Shift < 16) {
940     uint32_t Idxs[64];
941     // 256/512-bit version is split into 2/4 16-byte lanes.
942     for (unsigned l = 0; l != NumElts; l += 16)
943       for (unsigned i = 0; i != 16; ++i) {
944         unsigned Idx = i + Shift;
945         if (Idx >= 16)
946           Idx += NumElts - 16; // end of lane, switch operand.
947         Idxs[l + i] = Idx + l;
948       }
949 
950     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
951   }
952 
953   // Bitcast back to a 64-bit element type.
954   return Builder.CreateBitCast(Res, ResultTy, "cast");
955 }
956 
957 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
958                             unsigned NumElts) {
959   llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
960                              cast<IntegerType>(Mask->getType())->getBitWidth());
961   Mask = Builder.CreateBitCast(Mask, MaskTy);
962 
963   // If we have less than 8 elements, then the starting mask was an i8 and
964   // we need to extract down to the right number of elements.
965   if (NumElts < 8) {
966     uint32_t Indices[4];
967     for (unsigned i = 0; i != NumElts; ++i)
968       Indices[i] = i;
969     Mask = Builder.CreateShuffleVector(Mask, Mask,
970                                        makeArrayRef(Indices, NumElts),
971                                        "extract");
972   }
973 
974   return Mask;
975 }
976 
977 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
978                             Value *Op0, Value *Op1) {
979   // If the mask is all ones just emit the first operation.
980   if (const auto *C = dyn_cast<Constant>(Mask))
981     if (C->isAllOnesValue())
982       return Op0;
983 
984   Mask = getX86MaskVec(Builder, Mask, Op0->getType()->getVectorNumElements());
985   return Builder.CreateSelect(Mask, Op0, Op1);
986 }
987 
988 static Value *EmitX86ScalarSelect(IRBuilder<> &Builder, Value *Mask,
989                                   Value *Op0, Value *Op1) {
990   // If the mask is all ones just emit the first operation.
991   if (const auto *C = dyn_cast<Constant>(Mask))
992     if (C->isAllOnesValue())
993       return Op0;
994 
995   llvm::VectorType *MaskTy =
996     llvm::VectorType::get(Builder.getInt1Ty(),
997                           Mask->getType()->getIntegerBitWidth());
998   Mask = Builder.CreateBitCast(Mask, MaskTy);
999   Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
1000   return Builder.CreateSelect(Mask, Op0, Op1);
1001 }
1002 
1003 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
1004 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
1005 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
1006 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
1007                                         Value *Op1, Value *Shift,
1008                                         Value *Passthru, Value *Mask,
1009                                         bool IsVALIGN) {
1010   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
1011 
1012   unsigned NumElts = Op0->getType()->getVectorNumElements();
1013   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
1014   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
1015   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
1016 
1017   // Mask the immediate for VALIGN.
1018   if (IsVALIGN)
1019     ShiftVal &= (NumElts - 1);
1020 
1021   // If palignr is shifting the pair of vectors more than the size of two
1022   // lanes, emit zero.
1023   if (ShiftVal >= 32)
1024     return llvm::Constant::getNullValue(Op0->getType());
1025 
1026   // If palignr is shifting the pair of input vectors more than one lane,
1027   // but less than two lanes, convert to shifting in zeroes.
1028   if (ShiftVal > 16) {
1029     ShiftVal -= 16;
1030     Op1 = Op0;
1031     Op0 = llvm::Constant::getNullValue(Op0->getType());
1032   }
1033 
1034   uint32_t Indices[64];
1035   // 256-bit palignr operates on 128-bit lanes so we need to handle that
1036   for (unsigned l = 0; l < NumElts; l += 16) {
1037     for (unsigned i = 0; i != 16; ++i) {
1038       unsigned Idx = ShiftVal + i;
1039       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
1040         Idx += NumElts - 16; // End of lane, switch operand.
1041       Indices[l + i] = Idx + l;
1042     }
1043   }
1044 
1045   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
1046                                              makeArrayRef(Indices, NumElts),
1047                                              "palignr");
1048 
1049   return EmitX86Select(Builder, Mask, Align, Passthru);
1050 }
1051 
1052 static Value *UpgradeX86VPERMT2Intrinsics(IRBuilder<> &Builder, CallInst &CI,
1053                                           bool ZeroMask, bool IndexForm) {
1054   Type *Ty = CI.getType();
1055   unsigned VecWidth = Ty->getPrimitiveSizeInBits();
1056   unsigned EltWidth = Ty->getScalarSizeInBits();
1057   bool IsFloat = Ty->isFPOrFPVectorTy();
1058   Intrinsic::ID IID;
1059   if (VecWidth == 128 && EltWidth == 32 && IsFloat)
1060     IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
1061   else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
1062     IID = Intrinsic::x86_avx512_vpermi2var_d_128;
1063   else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
1064     IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
1065   else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
1066     IID = Intrinsic::x86_avx512_vpermi2var_q_128;
1067   else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1068     IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
1069   else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1070     IID = Intrinsic::x86_avx512_vpermi2var_d_256;
1071   else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1072     IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
1073   else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1074     IID = Intrinsic::x86_avx512_vpermi2var_q_256;
1075   else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1076     IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
1077   else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1078     IID = Intrinsic::x86_avx512_vpermi2var_d_512;
1079   else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1080     IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
1081   else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1082     IID = Intrinsic::x86_avx512_vpermi2var_q_512;
1083   else if (VecWidth == 128 && EltWidth == 16)
1084     IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
1085   else if (VecWidth == 256 && EltWidth == 16)
1086     IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
1087   else if (VecWidth == 512 && EltWidth == 16)
1088     IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
1089   else if (VecWidth == 128 && EltWidth == 8)
1090     IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
1091   else if (VecWidth == 256 && EltWidth == 8)
1092     IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
1093   else if (VecWidth == 512 && EltWidth == 8)
1094     IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
1095   else
1096     llvm_unreachable("Unexpected intrinsic");
1097 
1098   Value *Args[] = { CI.getArgOperand(0) , CI.getArgOperand(1),
1099                     CI.getArgOperand(2) };
1100 
1101   // If this isn't index form we need to swap operand 0 and 1.
1102   if (!IndexForm)
1103     std::swap(Args[0], Args[1]);
1104 
1105   Value *V = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1106                                 Args);
1107   Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty)
1108                              : Builder.CreateBitCast(CI.getArgOperand(1),
1109                                                      Ty);
1110   return EmitX86Select(Builder, CI.getArgOperand(3), V, PassThru);
1111 }
1112 
1113 static Value *UpgradeX86AddSubSatIntrinsics(IRBuilder<> &Builder, CallInst &CI,
1114                                             bool IsSigned, bool IsAddition) {
1115   Type *Ty = CI.getType();
1116   Value *Op0 = CI.getOperand(0);
1117   Value *Op1 = CI.getOperand(1);
1118 
1119   Intrinsic::ID IID =
1120       IsSigned ? (IsAddition ? Intrinsic::sadd_sat : Intrinsic::ssub_sat)
1121                : (IsAddition ? Intrinsic::uadd_sat : Intrinsic::usub_sat);
1122   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1123   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1});
1124 
1125   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1126     Value *VecSrc = CI.getOperand(2);
1127     Value *Mask = CI.getOperand(3);
1128     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1129   }
1130   return Res;
1131 }
1132 
1133 static Value *upgradeX86Rotate(IRBuilder<> &Builder, CallInst &CI,
1134                                bool IsRotateRight) {
1135   Type *Ty = CI.getType();
1136   Value *Src = CI.getArgOperand(0);
1137   Value *Amt = CI.getArgOperand(1);
1138 
1139   // Amount may be scalar immediate, in which case create a splat vector.
1140   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1141   // we only care about the lowest log2 bits anyway.
1142   if (Amt->getType() != Ty) {
1143     unsigned NumElts = Ty->getVectorNumElements();
1144     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1145     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1146   }
1147 
1148   Intrinsic::ID IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1149   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1150   Value *Res = Builder.CreateCall(Intrin, {Src, Src, Amt});
1151 
1152   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1153     Value *VecSrc = CI.getOperand(2);
1154     Value *Mask = CI.getOperand(3);
1155     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1156   }
1157   return Res;
1158 }
1159 
1160 static Value *upgradeX86vpcom(IRBuilder<> &Builder, CallInst &CI, unsigned Imm,
1161                               bool IsSigned) {
1162   Type *Ty = CI.getType();
1163   Value *LHS = CI.getArgOperand(0);
1164   Value *RHS = CI.getArgOperand(1);
1165 
1166   CmpInst::Predicate Pred;
1167   switch (Imm) {
1168   case 0x0:
1169     Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1170     break;
1171   case 0x1:
1172     Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1173     break;
1174   case 0x2:
1175     Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1176     break;
1177   case 0x3:
1178     Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1179     break;
1180   case 0x4:
1181     Pred = ICmpInst::ICMP_EQ;
1182     break;
1183   case 0x5:
1184     Pred = ICmpInst::ICMP_NE;
1185     break;
1186   case 0x6:
1187     return Constant::getNullValue(Ty); // FALSE
1188   case 0x7:
1189     return Constant::getAllOnesValue(Ty); // TRUE
1190   default:
1191     llvm_unreachable("Unknown XOP vpcom/vpcomu predicate");
1192   }
1193 
1194   Value *Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1195   Value *Ext = Builder.CreateSExt(Cmp, Ty);
1196   return Ext;
1197 }
1198 
1199 static Value *upgradeX86ConcatShift(IRBuilder<> &Builder, CallInst &CI,
1200                                     bool IsShiftRight, bool ZeroMask) {
1201   Type *Ty = CI.getType();
1202   Value *Op0 = CI.getArgOperand(0);
1203   Value *Op1 = CI.getArgOperand(1);
1204   Value *Amt = CI.getArgOperand(2);
1205 
1206   if (IsShiftRight)
1207     std::swap(Op0, Op1);
1208 
1209   // Amount may be scalar immediate, in which case create a splat vector.
1210   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1211   // we only care about the lowest log2 bits anyway.
1212   if (Amt->getType() != Ty) {
1213     unsigned NumElts = Ty->getVectorNumElements();
1214     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1215     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1216   }
1217 
1218   Intrinsic::ID IID = IsShiftRight ? Intrinsic::fshr : Intrinsic::fshl;
1219   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1220   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1, Amt});
1221 
1222   unsigned NumArgs = CI.getNumArgOperands();
1223   if (NumArgs >= 4) { // For masked intrinsics.
1224     Value *VecSrc = NumArgs == 5 ? CI.getArgOperand(3) :
1225                     ZeroMask     ? ConstantAggregateZero::get(CI.getType()) :
1226                                    CI.getArgOperand(0);
1227     Value *Mask = CI.getOperand(NumArgs - 1);
1228     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1229   }
1230   return Res;
1231 }
1232 
1233 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
1234                                  Value *Ptr, Value *Data, Value *Mask,
1235                                  bool Aligned) {
1236   // Cast the pointer to the right type.
1237   Ptr = Builder.CreateBitCast(Ptr,
1238                               llvm::PointerType::getUnqual(Data->getType()));
1239   const Align Alignment =
1240       Aligned ? Align(cast<VectorType>(Data->getType())->getBitWidth() / 8)
1241               : Align(1);
1242 
1243   // If the mask is all ones just emit a regular store.
1244   if (const auto *C = dyn_cast<Constant>(Mask))
1245     if (C->isAllOnesValue())
1246       return Builder.CreateAlignedStore(Data, Ptr, Alignment);
1247 
1248   // Convert the mask from an integer type to a vector of i1.
1249   unsigned NumElts = Data->getType()->getVectorNumElements();
1250   Mask = getX86MaskVec(Builder, Mask, NumElts);
1251   return Builder.CreateMaskedStore(Data, Ptr, Alignment, Mask);
1252 }
1253 
1254 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
1255                                 Value *Ptr, Value *Passthru, Value *Mask,
1256                                 bool Aligned) {
1257   Type *ValTy = Passthru->getType();
1258   // Cast the pointer to the right type.
1259   Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ValTy));
1260   const Align Alignment =
1261       Aligned ? Align(cast<VectorType>(Passthru->getType())->getBitWidth() / 8)
1262               : Align(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, Alignment);
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, Alignment, 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, Align(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 =
1734           Builder.CreateAlignedStore(Arg1, BC, Align(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, Align(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, Align(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, Align(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 =
3057           Builder.CreateAlignedLoad(VTy, BC, Align(VTy->getBitWidth() / 8));
3058       LI->setMetadata(M->getMDKindID("nontemporal"), Node);
3059       Rep = LI;
3060     } else if (IsX86 && (Name.startswith("fma.vfmadd.") ||
3061                          Name.startswith("fma.vfmsub.") ||
3062                          Name.startswith("fma.vfnmadd.") ||
3063                          Name.startswith("fma.vfnmsub."))) {
3064       bool NegMul = Name[6] == 'n';
3065       bool NegAcc = NegMul ? Name[8] == 's' : Name[7] == 's';
3066       bool IsScalar = NegMul ? Name[12] == 's' : Name[11] == 's';
3067 
3068       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3069                        CI->getArgOperand(2) };
3070 
3071       if (IsScalar) {
3072         Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3073         Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3074         Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3075       }
3076 
3077       if (NegMul && !IsScalar)
3078         Ops[0] = Builder.CreateFNeg(Ops[0]);
3079       if (NegMul && IsScalar)
3080         Ops[1] = Builder.CreateFNeg(Ops[1]);
3081       if (NegAcc)
3082         Ops[2] = Builder.CreateFNeg(Ops[2]);
3083 
3084       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3085                                                          Intrinsic::fma,
3086                                                          Ops[0]->getType()),
3087                                Ops);
3088 
3089       if (IsScalar)
3090         Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep,
3091                                           (uint64_t)0);
3092     } else if (IsX86 && Name.startswith("fma4.vfmadd.s")) {
3093       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3094                        CI->getArgOperand(2) };
3095 
3096       Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3097       Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3098       Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3099 
3100       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3101                                                          Intrinsic::fma,
3102                                                          Ops[0]->getType()),
3103                                Ops);
3104 
3105       Rep = Builder.CreateInsertElement(Constant::getNullValue(CI->getType()),
3106                                         Rep, (uint64_t)0);
3107     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.s") ||
3108                          Name.startswith("avx512.maskz.vfmadd.s") ||
3109                          Name.startswith("avx512.mask3.vfmadd.s") ||
3110                          Name.startswith("avx512.mask3.vfmsub.s") ||
3111                          Name.startswith("avx512.mask3.vfnmsub.s"))) {
3112       bool IsMask3 = Name[11] == '3';
3113       bool IsMaskZ = Name[11] == 'z';
3114       // Drop the "avx512.mask." to make it easier.
3115       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3116       bool NegMul = Name[2] == 'n';
3117       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3118 
3119       Value *A = CI->getArgOperand(0);
3120       Value *B = CI->getArgOperand(1);
3121       Value *C = CI->getArgOperand(2);
3122 
3123       if (NegMul && (IsMask3 || IsMaskZ))
3124         A = Builder.CreateFNeg(A);
3125       if (NegMul && !(IsMask3 || IsMaskZ))
3126         B = Builder.CreateFNeg(B);
3127       if (NegAcc)
3128         C = Builder.CreateFNeg(C);
3129 
3130       A = Builder.CreateExtractElement(A, (uint64_t)0);
3131       B = Builder.CreateExtractElement(B, (uint64_t)0);
3132       C = Builder.CreateExtractElement(C, (uint64_t)0);
3133 
3134       if (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3135           cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4) {
3136         Value *Ops[] = { A, B, C, CI->getArgOperand(4) };
3137 
3138         Intrinsic::ID IID;
3139         if (Name.back() == 'd')
3140           IID = Intrinsic::x86_avx512_vfmadd_f64;
3141         else
3142           IID = Intrinsic::x86_avx512_vfmadd_f32;
3143         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), IID);
3144         Rep = Builder.CreateCall(FMA, Ops);
3145       } else {
3146         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3147                                                   Intrinsic::fma,
3148                                                   A->getType());
3149         Rep = Builder.CreateCall(FMA, { A, B, C });
3150       }
3151 
3152       Value *PassThru = IsMaskZ ? Constant::getNullValue(Rep->getType()) :
3153                         IsMask3 ? C : A;
3154 
3155       // For Mask3 with NegAcc, we need to create a new extractelement that
3156       // avoids the negation above.
3157       if (NegAcc && IsMask3)
3158         PassThru = Builder.CreateExtractElement(CI->getArgOperand(2),
3159                                                 (uint64_t)0);
3160 
3161       Rep = EmitX86ScalarSelect(Builder, CI->getArgOperand(3),
3162                                 Rep, PassThru);
3163       Rep = Builder.CreateInsertElement(CI->getArgOperand(IsMask3 ? 2 : 0),
3164                                         Rep, (uint64_t)0);
3165     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.p") ||
3166                          Name.startswith("avx512.mask.vfnmadd.p") ||
3167                          Name.startswith("avx512.mask.vfnmsub.p") ||
3168                          Name.startswith("avx512.mask3.vfmadd.p") ||
3169                          Name.startswith("avx512.mask3.vfmsub.p") ||
3170                          Name.startswith("avx512.mask3.vfnmsub.p") ||
3171                          Name.startswith("avx512.maskz.vfmadd.p"))) {
3172       bool IsMask3 = Name[11] == '3';
3173       bool IsMaskZ = Name[11] == 'z';
3174       // Drop the "avx512.mask." to make it easier.
3175       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3176       bool NegMul = Name[2] == 'n';
3177       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3178 
3179       Value *A = CI->getArgOperand(0);
3180       Value *B = CI->getArgOperand(1);
3181       Value *C = CI->getArgOperand(2);
3182 
3183       if (NegMul && (IsMask3 || IsMaskZ))
3184         A = Builder.CreateFNeg(A);
3185       if (NegMul && !(IsMask3 || IsMaskZ))
3186         B = Builder.CreateFNeg(B);
3187       if (NegAcc)
3188         C = Builder.CreateFNeg(C);
3189 
3190       if (CI->getNumArgOperands() == 5 &&
3191           (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3192            cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4)) {
3193         Intrinsic::ID IID;
3194         // Check the character before ".512" in string.
3195         if (Name[Name.size()-5] == 's')
3196           IID = Intrinsic::x86_avx512_vfmadd_ps_512;
3197         else
3198           IID = Intrinsic::x86_avx512_vfmadd_pd_512;
3199 
3200         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3201                                  { A, B, C, CI->getArgOperand(4) });
3202       } else {
3203         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3204                                                   Intrinsic::fma,
3205                                                   A->getType());
3206         Rep = Builder.CreateCall(FMA, { A, B, C });
3207       }
3208 
3209       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3210                         IsMask3 ? CI->getArgOperand(2) :
3211                                   CI->getArgOperand(0);
3212 
3213       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3214     } else if (IsX86 &&  Name.startswith("fma.vfmsubadd.p")) {
3215       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3216       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3217       Intrinsic::ID IID;
3218       if (VecWidth == 128 && EltWidth == 32)
3219         IID = Intrinsic::x86_fma_vfmaddsub_ps;
3220       else if (VecWidth == 256 && EltWidth == 32)
3221         IID = Intrinsic::x86_fma_vfmaddsub_ps_256;
3222       else if (VecWidth == 128 && EltWidth == 64)
3223         IID = Intrinsic::x86_fma_vfmaddsub_pd;
3224       else if (VecWidth == 256 && EltWidth == 64)
3225         IID = Intrinsic::x86_fma_vfmaddsub_pd_256;
3226       else
3227         llvm_unreachable("Unexpected intrinsic");
3228 
3229       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3230                        CI->getArgOperand(2) };
3231       Ops[2] = Builder.CreateFNeg(Ops[2]);
3232       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3233                                Ops);
3234     } else if (IsX86 && (Name.startswith("avx512.mask.vfmaddsub.p") ||
3235                          Name.startswith("avx512.mask3.vfmaddsub.p") ||
3236                          Name.startswith("avx512.maskz.vfmaddsub.p") ||
3237                          Name.startswith("avx512.mask3.vfmsubadd.p"))) {
3238       bool IsMask3 = Name[11] == '3';
3239       bool IsMaskZ = Name[11] == 'z';
3240       // Drop the "avx512.mask." to make it easier.
3241       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3242       bool IsSubAdd = Name[3] == 's';
3243       if (CI->getNumArgOperands() == 5) {
3244         Intrinsic::ID IID;
3245         // Check the character before ".512" in string.
3246         if (Name[Name.size()-5] == 's')
3247           IID = Intrinsic::x86_avx512_vfmaddsub_ps_512;
3248         else
3249           IID = Intrinsic::x86_avx512_vfmaddsub_pd_512;
3250 
3251         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3252                          CI->getArgOperand(2), CI->getArgOperand(4) };
3253         if (IsSubAdd)
3254           Ops[2] = Builder.CreateFNeg(Ops[2]);
3255 
3256         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3257                                  Ops);
3258       } else {
3259         int NumElts = CI->getType()->getVectorNumElements();
3260 
3261         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3262                          CI->getArgOperand(2) };
3263 
3264         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::fma,
3265                                                   Ops[0]->getType());
3266         Value *Odd = Builder.CreateCall(FMA, Ops);
3267         Ops[2] = Builder.CreateFNeg(Ops[2]);
3268         Value *Even = Builder.CreateCall(FMA, Ops);
3269 
3270         if (IsSubAdd)
3271           std::swap(Even, Odd);
3272 
3273         SmallVector<uint32_t, 32> Idxs(NumElts);
3274         for (int i = 0; i != NumElts; ++i)
3275           Idxs[i] = i + (i % 2) * NumElts;
3276 
3277         Rep = Builder.CreateShuffleVector(Even, Odd, Idxs);
3278       }
3279 
3280       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3281                         IsMask3 ? CI->getArgOperand(2) :
3282                                   CI->getArgOperand(0);
3283 
3284       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3285     } else if (IsX86 && (Name.startswith("avx512.mask.pternlog.") ||
3286                          Name.startswith("avx512.maskz.pternlog."))) {
3287       bool ZeroMask = Name[11] == 'z';
3288       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3289       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3290       Intrinsic::ID IID;
3291       if (VecWidth == 128 && EltWidth == 32)
3292         IID = Intrinsic::x86_avx512_pternlog_d_128;
3293       else if (VecWidth == 256 && EltWidth == 32)
3294         IID = Intrinsic::x86_avx512_pternlog_d_256;
3295       else if (VecWidth == 512 && EltWidth == 32)
3296         IID = Intrinsic::x86_avx512_pternlog_d_512;
3297       else if (VecWidth == 128 && EltWidth == 64)
3298         IID = Intrinsic::x86_avx512_pternlog_q_128;
3299       else if (VecWidth == 256 && EltWidth == 64)
3300         IID = Intrinsic::x86_avx512_pternlog_q_256;
3301       else if (VecWidth == 512 && EltWidth == 64)
3302         IID = Intrinsic::x86_avx512_pternlog_q_512;
3303       else
3304         llvm_unreachable("Unexpected intrinsic");
3305 
3306       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3307                         CI->getArgOperand(2), CI->getArgOperand(3) };
3308       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3309                                Args);
3310       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3311                                  : CI->getArgOperand(0);
3312       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep, PassThru);
3313     } else if (IsX86 && (Name.startswith("avx512.mask.vpmadd52") ||
3314                          Name.startswith("avx512.maskz.vpmadd52"))) {
3315       bool ZeroMask = Name[11] == 'z';
3316       bool High = Name[20] == 'h' || Name[21] == 'h';
3317       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3318       Intrinsic::ID IID;
3319       if (VecWidth == 128 && !High)
3320         IID = Intrinsic::x86_avx512_vpmadd52l_uq_128;
3321       else if (VecWidth == 256 && !High)
3322         IID = Intrinsic::x86_avx512_vpmadd52l_uq_256;
3323       else if (VecWidth == 512 && !High)
3324         IID = Intrinsic::x86_avx512_vpmadd52l_uq_512;
3325       else if (VecWidth == 128 && High)
3326         IID = Intrinsic::x86_avx512_vpmadd52h_uq_128;
3327       else if (VecWidth == 256 && High)
3328         IID = Intrinsic::x86_avx512_vpmadd52h_uq_256;
3329       else if (VecWidth == 512 && High)
3330         IID = Intrinsic::x86_avx512_vpmadd52h_uq_512;
3331       else
3332         llvm_unreachable("Unexpected intrinsic");
3333 
3334       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3335                         CI->getArgOperand(2) };
3336       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3337                                Args);
3338       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3339                                  : CI->getArgOperand(0);
3340       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3341     } else if (IsX86 && (Name.startswith("avx512.mask.vpermi2var.") ||
3342                          Name.startswith("avx512.mask.vpermt2var.") ||
3343                          Name.startswith("avx512.maskz.vpermt2var."))) {
3344       bool ZeroMask = Name[11] == 'z';
3345       bool IndexForm = Name[17] == 'i';
3346       Rep = UpgradeX86VPERMT2Intrinsics(Builder, *CI, ZeroMask, IndexForm);
3347     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpbusd.") ||
3348                          Name.startswith("avx512.maskz.vpdpbusd.") ||
3349                          Name.startswith("avx512.mask.vpdpbusds.") ||
3350                          Name.startswith("avx512.maskz.vpdpbusds."))) {
3351       bool ZeroMask = Name[11] == 'z';
3352       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3353       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3354       Intrinsic::ID IID;
3355       if (VecWidth == 128 && !IsSaturating)
3356         IID = Intrinsic::x86_avx512_vpdpbusd_128;
3357       else if (VecWidth == 256 && !IsSaturating)
3358         IID = Intrinsic::x86_avx512_vpdpbusd_256;
3359       else if (VecWidth == 512 && !IsSaturating)
3360         IID = Intrinsic::x86_avx512_vpdpbusd_512;
3361       else if (VecWidth == 128 && IsSaturating)
3362         IID = Intrinsic::x86_avx512_vpdpbusds_128;
3363       else if (VecWidth == 256 && IsSaturating)
3364         IID = Intrinsic::x86_avx512_vpdpbusds_256;
3365       else if (VecWidth == 512 && IsSaturating)
3366         IID = Intrinsic::x86_avx512_vpdpbusds_512;
3367       else
3368         llvm_unreachable("Unexpected intrinsic");
3369 
3370       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3371                         CI->getArgOperand(2)  };
3372       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3373                                Args);
3374       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3375                                  : CI->getArgOperand(0);
3376       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3377     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpwssd.") ||
3378                          Name.startswith("avx512.maskz.vpdpwssd.") ||
3379                          Name.startswith("avx512.mask.vpdpwssds.") ||
3380                          Name.startswith("avx512.maskz.vpdpwssds."))) {
3381       bool ZeroMask = Name[11] == 'z';
3382       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3383       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3384       Intrinsic::ID IID;
3385       if (VecWidth == 128 && !IsSaturating)
3386         IID = Intrinsic::x86_avx512_vpdpwssd_128;
3387       else if (VecWidth == 256 && !IsSaturating)
3388         IID = Intrinsic::x86_avx512_vpdpwssd_256;
3389       else if (VecWidth == 512 && !IsSaturating)
3390         IID = Intrinsic::x86_avx512_vpdpwssd_512;
3391       else if (VecWidth == 128 && IsSaturating)
3392         IID = Intrinsic::x86_avx512_vpdpwssds_128;
3393       else if (VecWidth == 256 && IsSaturating)
3394         IID = Intrinsic::x86_avx512_vpdpwssds_256;
3395       else if (VecWidth == 512 && IsSaturating)
3396         IID = Intrinsic::x86_avx512_vpdpwssds_512;
3397       else
3398         llvm_unreachable("Unexpected intrinsic");
3399 
3400       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3401                         CI->getArgOperand(2)  };
3402       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3403                                Args);
3404       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3405                                  : CI->getArgOperand(0);
3406       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3407     } else if (IsX86 && (Name == "addcarryx.u32" || Name == "addcarryx.u64" ||
3408                          Name == "addcarry.u32" || Name == "addcarry.u64" ||
3409                          Name == "subborrow.u32" || Name == "subborrow.u64")) {
3410       Intrinsic::ID IID;
3411       if (Name[0] == 'a' && Name.back() == '2')
3412         IID = Intrinsic::x86_addcarry_32;
3413       else if (Name[0] == 'a' && Name.back() == '4')
3414         IID = Intrinsic::x86_addcarry_64;
3415       else if (Name[0] == 's' && Name.back() == '2')
3416         IID = Intrinsic::x86_subborrow_32;
3417       else if (Name[0] == 's' && Name.back() == '4')
3418         IID = Intrinsic::x86_subborrow_64;
3419       else
3420         llvm_unreachable("Unexpected intrinsic");
3421 
3422       // Make a call with 3 operands.
3423       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3424                         CI->getArgOperand(2)};
3425       Value *NewCall = Builder.CreateCall(
3426                                 Intrinsic::getDeclaration(CI->getModule(), IID),
3427                                 Args);
3428 
3429       // Extract the second result and store it.
3430       Value *Data = Builder.CreateExtractValue(NewCall, 1);
3431       // Cast the pointer to the right type.
3432       Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(3),
3433                                  llvm::PointerType::getUnqual(Data->getType()));
3434       Builder.CreateAlignedStore(Data, Ptr, Align(1));
3435       // Replace the original call result with the first result of the new call.
3436       Value *CF = Builder.CreateExtractValue(NewCall, 0);
3437 
3438       CI->replaceAllUsesWith(CF);
3439       Rep = nullptr;
3440     } else if (IsX86 && Name.startswith("avx512.mask.") &&
3441                upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
3442       // Rep will be updated by the call in the condition.
3443     } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
3444       Value *Arg = CI->getArgOperand(0);
3445       Value *Neg = Builder.CreateNeg(Arg, "neg");
3446       Value *Cmp = Builder.CreateICmpSGE(
3447           Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
3448       Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
3449     } else if (IsNVVM && (Name.startswith("atomic.load.add.f32.p") ||
3450                           Name.startswith("atomic.load.add.f64.p"))) {
3451       Value *Ptr = CI->getArgOperand(0);
3452       Value *Val = CI->getArgOperand(1);
3453       Rep = Builder.CreateAtomicRMW(AtomicRMWInst::FAdd, Ptr, Val,
3454                                     AtomicOrdering::SequentiallyConsistent);
3455     } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
3456                           Name == "max.ui" || Name == "max.ull")) {
3457       Value *Arg0 = CI->getArgOperand(0);
3458       Value *Arg1 = CI->getArgOperand(1);
3459       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3460                        ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
3461                        : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
3462       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
3463     } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
3464                           Name == "min.ui" || Name == "min.ull")) {
3465       Value *Arg0 = CI->getArgOperand(0);
3466       Value *Arg1 = CI->getArgOperand(1);
3467       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3468                        ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
3469                        : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
3470       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
3471     } else if (IsNVVM && Name == "clz.ll") {
3472       // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
3473       Value *Arg = CI->getArgOperand(0);
3474       Value *Ctlz = Builder.CreateCall(
3475           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
3476                                     {Arg->getType()}),
3477           {Arg, Builder.getFalse()}, "ctlz");
3478       Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
3479     } else if (IsNVVM && Name == "popc.ll") {
3480       // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
3481       // i64.
3482       Value *Arg = CI->getArgOperand(0);
3483       Value *Popc = Builder.CreateCall(
3484           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
3485                                     {Arg->getType()}),
3486           Arg, "ctpop");
3487       Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
3488     } else if (IsNVVM && Name == "h2f") {
3489       Rep = Builder.CreateCall(Intrinsic::getDeclaration(
3490                                    F->getParent(), Intrinsic::convert_from_fp16,
3491                                    {Builder.getFloatTy()}),
3492                                CI->getArgOperand(0), "h2f");
3493     } else {
3494       llvm_unreachable("Unknown function for CallInst upgrade.");
3495     }
3496 
3497     if (Rep)
3498       CI->replaceAllUsesWith(Rep);
3499     CI->eraseFromParent();
3500     return;
3501   }
3502 
3503   const auto &DefaultCase = [&NewFn, &CI]() -> void {
3504     // Handle generic mangling change, but nothing else
3505     assert(
3506         (CI->getCalledFunction()->getName() != NewFn->getName()) &&
3507         "Unknown function for CallInst upgrade and isn't just a name change");
3508     CI->setCalledFunction(NewFn);
3509   };
3510   CallInst *NewCall = nullptr;
3511   switch (NewFn->getIntrinsicID()) {
3512   default: {
3513     DefaultCase();
3514     return;
3515   }
3516   case Intrinsic::experimental_vector_reduce_v2_fmul: {
3517     SmallVector<Value *, 2> Args;
3518     if (CI->isFast())
3519       Args.push_back(ConstantFP::get(CI->getOperand(0)->getType(), 1.0));
3520     else
3521       Args.push_back(CI->getOperand(0));
3522     Args.push_back(CI->getOperand(1));
3523     NewCall = Builder.CreateCall(NewFn, Args);
3524     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3525     break;
3526   }
3527   case Intrinsic::experimental_vector_reduce_v2_fadd: {
3528     SmallVector<Value *, 2> Args;
3529     if (CI->isFast())
3530       Args.push_back(Constant::getNullValue(CI->getOperand(0)->getType()));
3531     else
3532       Args.push_back(CI->getOperand(0));
3533     Args.push_back(CI->getOperand(1));
3534     NewCall = Builder.CreateCall(NewFn, Args);
3535     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3536     break;
3537   }
3538   case Intrinsic::arm_neon_vld1:
3539   case Intrinsic::arm_neon_vld2:
3540   case Intrinsic::arm_neon_vld3:
3541   case Intrinsic::arm_neon_vld4:
3542   case Intrinsic::arm_neon_vld2lane:
3543   case Intrinsic::arm_neon_vld3lane:
3544   case Intrinsic::arm_neon_vld4lane:
3545   case Intrinsic::arm_neon_vst1:
3546   case Intrinsic::arm_neon_vst2:
3547   case Intrinsic::arm_neon_vst3:
3548   case Intrinsic::arm_neon_vst4:
3549   case Intrinsic::arm_neon_vst2lane:
3550   case Intrinsic::arm_neon_vst3lane:
3551   case Intrinsic::arm_neon_vst4lane: {
3552     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3553                                  CI->arg_operands().end());
3554     NewCall = Builder.CreateCall(NewFn, Args);
3555     break;
3556   }
3557 
3558   case Intrinsic::bitreverse:
3559     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3560     break;
3561 
3562   case Intrinsic::ctlz:
3563   case Intrinsic::cttz:
3564     assert(CI->getNumArgOperands() == 1 &&
3565            "Mismatch between function args and call args");
3566     NewCall =
3567         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
3568     break;
3569 
3570   case Intrinsic::objectsize: {
3571     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
3572                                    ? Builder.getFalse()
3573                                    : CI->getArgOperand(2);
3574     Value *Dynamic =
3575         CI->getNumArgOperands() < 4 ? Builder.getFalse() : CI->getArgOperand(3);
3576     NewCall = Builder.CreateCall(
3577         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize, Dynamic});
3578     break;
3579   }
3580 
3581   case Intrinsic::ctpop:
3582     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3583     break;
3584 
3585   case Intrinsic::convert_from_fp16:
3586     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3587     break;
3588 
3589   case Intrinsic::dbg_value:
3590     // Upgrade from the old version that had an extra offset argument.
3591     assert(CI->getNumArgOperands() == 4);
3592     // Drop nonzero offsets instead of attempting to upgrade them.
3593     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
3594       if (Offset->isZeroValue()) {
3595         NewCall = Builder.CreateCall(
3596             NewFn,
3597             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
3598         break;
3599       }
3600     CI->eraseFromParent();
3601     return;
3602 
3603   case Intrinsic::x86_xop_vfrcz_ss:
3604   case Intrinsic::x86_xop_vfrcz_sd:
3605     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
3606     break;
3607 
3608   case Intrinsic::x86_xop_vpermil2pd:
3609   case Intrinsic::x86_xop_vpermil2ps:
3610   case Intrinsic::x86_xop_vpermil2pd_256:
3611   case Intrinsic::x86_xop_vpermil2ps_256: {
3612     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3613                                  CI->arg_operands().end());
3614     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
3615     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
3616     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
3617     NewCall = Builder.CreateCall(NewFn, Args);
3618     break;
3619   }
3620 
3621   case Intrinsic::x86_sse41_ptestc:
3622   case Intrinsic::x86_sse41_ptestz:
3623   case Intrinsic::x86_sse41_ptestnzc: {
3624     // The arguments for these intrinsics used to be v4f32, and changed
3625     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
3626     // So, the only thing required is a bitcast for both arguments.
3627     // First, check the arguments have the old type.
3628     Value *Arg0 = CI->getArgOperand(0);
3629     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
3630       return;
3631 
3632     // Old intrinsic, add bitcasts
3633     Value *Arg1 = CI->getArgOperand(1);
3634 
3635     Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
3636 
3637     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
3638     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
3639 
3640     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
3641     break;
3642   }
3643 
3644   case Intrinsic::x86_rdtscp: {
3645     // This used to take 1 arguments. If we have no arguments, it is already
3646     // upgraded.
3647     if (CI->getNumOperands() == 0)
3648       return;
3649 
3650     NewCall = Builder.CreateCall(NewFn);
3651     // Extract the second result and store it.
3652     Value *Data = Builder.CreateExtractValue(NewCall, 1);
3653     // Cast the pointer to the right type.
3654     Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(0),
3655                                  llvm::PointerType::getUnqual(Data->getType()));
3656     Builder.CreateAlignedStore(Data, Ptr, Align(1));
3657     // Replace the original call result with the first result of the new call.
3658     Value *TSC = Builder.CreateExtractValue(NewCall, 0);
3659 
3660     std::string Name = std::string(CI->getName());
3661     if (!Name.empty()) {
3662       CI->setName(Name + ".old");
3663       NewCall->setName(Name);
3664     }
3665     CI->replaceAllUsesWith(TSC);
3666     CI->eraseFromParent();
3667     return;
3668   }
3669 
3670   case Intrinsic::x86_sse41_insertps:
3671   case Intrinsic::x86_sse41_dppd:
3672   case Intrinsic::x86_sse41_dpps:
3673   case Intrinsic::x86_sse41_mpsadbw:
3674   case Intrinsic::x86_avx_dp_ps_256:
3675   case Intrinsic::x86_avx2_mpsadbw: {
3676     // Need to truncate the last argument from i32 to i8 -- this argument models
3677     // an inherently 8-bit immediate operand to these x86 instructions.
3678     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3679                                  CI->arg_operands().end());
3680 
3681     // Replace the last argument with a trunc.
3682     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
3683     NewCall = Builder.CreateCall(NewFn, Args);
3684     break;
3685   }
3686 
3687   case Intrinsic::thread_pointer: {
3688     NewCall = Builder.CreateCall(NewFn, {});
3689     break;
3690   }
3691 
3692   case Intrinsic::invariant_start:
3693   case Intrinsic::invariant_end:
3694   case Intrinsic::masked_load:
3695   case Intrinsic::masked_store:
3696   case Intrinsic::masked_gather:
3697   case Intrinsic::masked_scatter: {
3698     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3699                                  CI->arg_operands().end());
3700     NewCall = Builder.CreateCall(NewFn, Args);
3701     break;
3702   }
3703 
3704   case Intrinsic::memcpy:
3705   case Intrinsic::memmove:
3706   case Intrinsic::memset: {
3707     // We have to make sure that the call signature is what we're expecting.
3708     // We only want to change the old signatures by removing the alignment arg:
3709     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
3710     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
3711     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
3712     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
3713     // Note: i8*'s in the above can be any pointer type
3714     if (CI->getNumArgOperands() != 5) {
3715       DefaultCase();
3716       return;
3717     }
3718     // Remove alignment argument (3), and add alignment attributes to the
3719     // dest/src pointers.
3720     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
3721                       CI->getArgOperand(2), CI->getArgOperand(4)};
3722     NewCall = Builder.CreateCall(NewFn, Args);
3723     auto *MemCI = cast<MemIntrinsic>(NewCall);
3724     // All mem intrinsics support dest alignment.
3725     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
3726     MemCI->setDestAlignment(Align->getZExtValue());
3727     // Memcpy/Memmove also support source alignment.
3728     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
3729       MTI->setSourceAlignment(Align->getZExtValue());
3730     break;
3731   }
3732   }
3733   assert(NewCall && "Should have either set this variable or returned through "
3734                     "the default case");
3735   std::string Name = std::string(CI->getName());
3736   if (!Name.empty()) {
3737     CI->setName(Name + ".old");
3738     NewCall->setName(Name);
3739   }
3740   CI->replaceAllUsesWith(NewCall);
3741   CI->eraseFromParent();
3742 }
3743 
3744 void llvm::UpgradeCallsToIntrinsic(Function *F) {
3745   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
3746 
3747   // Check if this function should be upgraded and get the replacement function
3748   // if there is one.
3749   Function *NewFn;
3750   if (UpgradeIntrinsicFunction(F, NewFn)) {
3751     // Replace all users of the old function with the new function or new
3752     // instructions. This is not a range loop because the call is deleted.
3753     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
3754       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
3755         UpgradeIntrinsicCall(CI, NewFn);
3756 
3757     // Remove old function, no longer used, from the module.
3758     F->eraseFromParent();
3759   }
3760 }
3761 
3762 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
3763   // Check if the tag uses struct-path aware TBAA format.
3764   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
3765     return &MD;
3766 
3767   auto &Context = MD.getContext();
3768   if (MD.getNumOperands() == 3) {
3769     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
3770     MDNode *ScalarType = MDNode::get(Context, Elts);
3771     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
3772     Metadata *Elts2[] = {ScalarType, ScalarType,
3773                          ConstantAsMetadata::get(
3774                              Constant::getNullValue(Type::getInt64Ty(Context))),
3775                          MD.getOperand(2)};
3776     return MDNode::get(Context, Elts2);
3777   }
3778   // Create a MDNode <MD, MD, offset 0>
3779   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
3780                                     Type::getInt64Ty(Context)))};
3781   return MDNode::get(Context, Elts);
3782 }
3783 
3784 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
3785                                       Instruction *&Temp) {
3786   if (Opc != Instruction::BitCast)
3787     return nullptr;
3788 
3789   Temp = nullptr;
3790   Type *SrcTy = V->getType();
3791   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3792       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3793     LLVMContext &Context = V->getContext();
3794 
3795     // We have no information about target data layout, so we assume that
3796     // the maximum pointer size is 64bit.
3797     Type *MidTy = Type::getInt64Ty(Context);
3798     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
3799 
3800     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
3801   }
3802 
3803   return nullptr;
3804 }
3805 
3806 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
3807   if (Opc != Instruction::BitCast)
3808     return nullptr;
3809 
3810   Type *SrcTy = C->getType();
3811   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3812       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3813     LLVMContext &Context = C->getContext();
3814 
3815     // We have no information about target data layout, so we assume that
3816     // the maximum pointer size is 64bit.
3817     Type *MidTy = Type::getInt64Ty(Context);
3818 
3819     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
3820                                      DestTy);
3821   }
3822 
3823   return nullptr;
3824 }
3825 
3826 /// Check the debug info version number, if it is out-dated, drop the debug
3827 /// info. Return true if module is modified.
3828 bool llvm::UpgradeDebugInfo(Module &M) {
3829   unsigned Version = getDebugMetadataVersionFromModule(M);
3830   if (Version == DEBUG_METADATA_VERSION) {
3831     bool BrokenDebugInfo = false;
3832     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
3833       report_fatal_error("Broken module found, compilation aborted!");
3834     if (!BrokenDebugInfo)
3835       // Everything is ok.
3836       return false;
3837     else {
3838       // Diagnose malformed debug info.
3839       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
3840       M.getContext().diagnose(Diag);
3841     }
3842   }
3843   bool Modified = StripDebugInfo(M);
3844   if (Modified && Version != DEBUG_METADATA_VERSION) {
3845     // Diagnose a version mismatch.
3846     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
3847     M.getContext().diagnose(DiagVersion);
3848   }
3849   return Modified;
3850 }
3851 
3852 /// This checks for objc retain release marker which should be upgraded. It
3853 /// returns true if module is modified.
3854 static bool UpgradeRetainReleaseMarker(Module &M) {
3855   bool Changed = false;
3856   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
3857   NamedMDNode *ModRetainReleaseMarker = M.getNamedMetadata(MarkerKey);
3858   if (ModRetainReleaseMarker) {
3859     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
3860     if (Op) {
3861       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
3862       if (ID) {
3863         SmallVector<StringRef, 4> ValueComp;
3864         ID->getString().split(ValueComp, "#");
3865         if (ValueComp.size() == 2) {
3866           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
3867           ID = MDString::get(M.getContext(), NewValue);
3868         }
3869         M.addModuleFlag(Module::Error, MarkerKey, ID);
3870         M.eraseNamedMetadata(ModRetainReleaseMarker);
3871         Changed = true;
3872       }
3873     }
3874   }
3875   return Changed;
3876 }
3877 
3878 void llvm::UpgradeARCRuntime(Module &M) {
3879   // This lambda converts normal function calls to ARC runtime functions to
3880   // intrinsic calls.
3881   auto UpgradeToIntrinsic = [&](const char *OldFunc,
3882                                 llvm::Intrinsic::ID IntrinsicFunc) {
3883     Function *Fn = M.getFunction(OldFunc);
3884 
3885     if (!Fn)
3886       return;
3887 
3888     Function *NewFn = llvm::Intrinsic::getDeclaration(&M, IntrinsicFunc);
3889 
3890     for (auto I = Fn->user_begin(), E = Fn->user_end(); I != E;) {
3891       CallInst *CI = dyn_cast<CallInst>(*I++);
3892       if (!CI || CI->getCalledFunction() != Fn)
3893         continue;
3894 
3895       IRBuilder<> Builder(CI->getParent(), CI->getIterator());
3896       FunctionType *NewFuncTy = NewFn->getFunctionType();
3897       SmallVector<Value *, 2> Args;
3898 
3899       // Don't upgrade the intrinsic if it's not valid to bitcast the return
3900       // value to the return type of the old function.
3901       if (NewFuncTy->getReturnType() != CI->getType() &&
3902           !CastInst::castIsValid(Instruction::BitCast, CI,
3903                                  NewFuncTy->getReturnType()))
3904         continue;
3905 
3906       bool InvalidCast = false;
3907 
3908       for (unsigned I = 0, E = CI->getNumArgOperands(); I != E; ++I) {
3909         Value *Arg = CI->getArgOperand(I);
3910 
3911         // Bitcast argument to the parameter type of the new function if it's
3912         // not a variadic argument.
3913         if (I < NewFuncTy->getNumParams()) {
3914           // Don't upgrade the intrinsic if it's not valid to bitcast the argument
3915           // to the parameter type of the new function.
3916           if (!CastInst::castIsValid(Instruction::BitCast, Arg,
3917                                      NewFuncTy->getParamType(I))) {
3918             InvalidCast = true;
3919             break;
3920           }
3921           Arg = Builder.CreateBitCast(Arg, NewFuncTy->getParamType(I));
3922         }
3923         Args.push_back(Arg);
3924       }
3925 
3926       if (InvalidCast)
3927         continue;
3928 
3929       // Create a call instruction that calls the new function.
3930       CallInst *NewCall = Builder.CreateCall(NewFuncTy, NewFn, Args);
3931       NewCall->setTailCallKind(cast<CallInst>(CI)->getTailCallKind());
3932       NewCall->setName(CI->getName());
3933 
3934       // Bitcast the return value back to the type of the old call.
3935       Value *NewRetVal = Builder.CreateBitCast(NewCall, CI->getType());
3936 
3937       if (!CI->use_empty())
3938         CI->replaceAllUsesWith(NewRetVal);
3939       CI->eraseFromParent();
3940     }
3941 
3942     if (Fn->use_empty())
3943       Fn->eraseFromParent();
3944   };
3945 
3946   // Unconditionally convert a call to "clang.arc.use" to a call to
3947   // "llvm.objc.clang.arc.use".
3948   UpgradeToIntrinsic("clang.arc.use", llvm::Intrinsic::objc_clang_arc_use);
3949 
3950   // Upgrade the retain release marker. If there is no need to upgrade
3951   // the marker, that means either the module is already new enough to contain
3952   // new intrinsics or it is not ARC. There is no need to upgrade runtime call.
3953   if (!UpgradeRetainReleaseMarker(M))
3954     return;
3955 
3956   std::pair<const char *, llvm::Intrinsic::ID> RuntimeFuncs[] = {
3957       {"objc_autorelease", llvm::Intrinsic::objc_autorelease},
3958       {"objc_autoreleasePoolPop", llvm::Intrinsic::objc_autoreleasePoolPop},
3959       {"objc_autoreleasePoolPush", llvm::Intrinsic::objc_autoreleasePoolPush},
3960       {"objc_autoreleaseReturnValue",
3961        llvm::Intrinsic::objc_autoreleaseReturnValue},
3962       {"objc_copyWeak", llvm::Intrinsic::objc_copyWeak},
3963       {"objc_destroyWeak", llvm::Intrinsic::objc_destroyWeak},
3964       {"objc_initWeak", llvm::Intrinsic::objc_initWeak},
3965       {"objc_loadWeak", llvm::Intrinsic::objc_loadWeak},
3966       {"objc_loadWeakRetained", llvm::Intrinsic::objc_loadWeakRetained},
3967       {"objc_moveWeak", llvm::Intrinsic::objc_moveWeak},
3968       {"objc_release", llvm::Intrinsic::objc_release},
3969       {"objc_retain", llvm::Intrinsic::objc_retain},
3970       {"objc_retainAutorelease", llvm::Intrinsic::objc_retainAutorelease},
3971       {"objc_retainAutoreleaseReturnValue",
3972        llvm::Intrinsic::objc_retainAutoreleaseReturnValue},
3973       {"objc_retainAutoreleasedReturnValue",
3974        llvm::Intrinsic::objc_retainAutoreleasedReturnValue},
3975       {"objc_retainBlock", llvm::Intrinsic::objc_retainBlock},
3976       {"objc_storeStrong", llvm::Intrinsic::objc_storeStrong},
3977       {"objc_storeWeak", llvm::Intrinsic::objc_storeWeak},
3978       {"objc_unsafeClaimAutoreleasedReturnValue",
3979        llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue},
3980       {"objc_retainedObject", llvm::Intrinsic::objc_retainedObject},
3981       {"objc_unretainedObject", llvm::Intrinsic::objc_unretainedObject},
3982       {"objc_unretainedPointer", llvm::Intrinsic::objc_unretainedPointer},
3983       {"objc_retain_autorelease", llvm::Intrinsic::objc_retain_autorelease},
3984       {"objc_sync_enter", llvm::Intrinsic::objc_sync_enter},
3985       {"objc_sync_exit", llvm::Intrinsic::objc_sync_exit},
3986       {"objc_arc_annotation_topdown_bbstart",
3987        llvm::Intrinsic::objc_arc_annotation_topdown_bbstart},
3988       {"objc_arc_annotation_topdown_bbend",
3989        llvm::Intrinsic::objc_arc_annotation_topdown_bbend},
3990       {"objc_arc_annotation_bottomup_bbstart",
3991        llvm::Intrinsic::objc_arc_annotation_bottomup_bbstart},
3992       {"objc_arc_annotation_bottomup_bbend",
3993        llvm::Intrinsic::objc_arc_annotation_bottomup_bbend}};
3994 
3995   for (auto &I : RuntimeFuncs)
3996     UpgradeToIntrinsic(I.first, I.second);
3997 }
3998 
3999 bool llvm::UpgradeModuleFlags(Module &M) {
4000   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
4001   if (!ModFlags)
4002     return false;
4003 
4004   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
4005   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
4006     MDNode *Op = ModFlags->getOperand(I);
4007     if (Op->getNumOperands() != 3)
4008       continue;
4009     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
4010     if (!ID)
4011       continue;
4012     if (ID->getString() == "Objective-C Image Info Version")
4013       HasObjCFlag = true;
4014     if (ID->getString() == "Objective-C Class Properties")
4015       HasClassProperties = true;
4016     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
4017     // field was Error and now they are Max.
4018     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
4019       if (auto *Behavior =
4020               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
4021         if (Behavior->getLimitedValue() == Module::Error) {
4022           Type *Int32Ty = Type::getInt32Ty(M.getContext());
4023           Metadata *Ops[3] = {
4024               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
4025               MDString::get(M.getContext(), ID->getString()),
4026               Op->getOperand(2)};
4027           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4028           Changed = true;
4029         }
4030       }
4031     }
4032     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
4033     // section name so that llvm-lto will not complain about mismatching
4034     // module flags that is functionally the same.
4035     if (ID->getString() == "Objective-C Image Info Section") {
4036       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
4037         SmallVector<StringRef, 4> ValueComp;
4038         Value->getString().split(ValueComp, " ");
4039         if (ValueComp.size() != 1) {
4040           std::string NewValue;
4041           for (auto &S : ValueComp)
4042             NewValue += S.str();
4043           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
4044                               MDString::get(M.getContext(), NewValue)};
4045           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4046           Changed = true;
4047         }
4048       }
4049     }
4050   }
4051 
4052   // "Objective-C Class Properties" is recently added for Objective-C. We
4053   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
4054   // flag of value 0, so we can correclty downgrade this flag when trying to
4055   // link an ObjC bitcode without this module flag with an ObjC bitcode with
4056   // this module flag.
4057   if (HasObjCFlag && !HasClassProperties) {
4058     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
4059                     (uint32_t)0);
4060     Changed = true;
4061   }
4062 
4063   return Changed;
4064 }
4065 
4066 void llvm::UpgradeSectionAttributes(Module &M) {
4067   auto TrimSpaces = [](StringRef Section) -> std::string {
4068     SmallVector<StringRef, 5> Components;
4069     Section.split(Components, ',');
4070 
4071     SmallString<32> Buffer;
4072     raw_svector_ostream OS(Buffer);
4073 
4074     for (auto Component : Components)
4075       OS << ',' << Component.trim();
4076 
4077     return std::string(OS.str().substr(1));
4078   };
4079 
4080   for (auto &GV : M.globals()) {
4081     if (!GV.hasSection())
4082       continue;
4083 
4084     StringRef Section = GV.getSection();
4085 
4086     if (!Section.startswith("__DATA, __objc_catlist"))
4087       continue;
4088 
4089     // __DATA, __objc_catlist, regular, no_dead_strip
4090     // __DATA,__objc_catlist,regular,no_dead_strip
4091     GV.setSection(TrimSpaces(Section));
4092   }
4093 }
4094 
4095 static bool isOldLoopArgument(Metadata *MD) {
4096   auto *T = dyn_cast_or_null<MDTuple>(MD);
4097   if (!T)
4098     return false;
4099   if (T->getNumOperands() < 1)
4100     return false;
4101   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
4102   if (!S)
4103     return false;
4104   return S->getString().startswith("llvm.vectorizer.");
4105 }
4106 
4107 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
4108   StringRef OldPrefix = "llvm.vectorizer.";
4109   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
4110 
4111   if (OldTag == "llvm.vectorizer.unroll")
4112     return MDString::get(C, "llvm.loop.interleave.count");
4113 
4114   return MDString::get(
4115       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
4116              .str());
4117 }
4118 
4119 static Metadata *upgradeLoopArgument(Metadata *MD) {
4120   auto *T = dyn_cast_or_null<MDTuple>(MD);
4121   if (!T)
4122     return MD;
4123   if (T->getNumOperands() < 1)
4124     return MD;
4125   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
4126   if (!OldTag)
4127     return MD;
4128   if (!OldTag->getString().startswith("llvm.vectorizer."))
4129     return MD;
4130 
4131   // This has an old tag.  Upgrade it.
4132   SmallVector<Metadata *, 8> Ops;
4133   Ops.reserve(T->getNumOperands());
4134   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
4135   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
4136     Ops.push_back(T->getOperand(I));
4137 
4138   return MDTuple::get(T->getContext(), Ops);
4139 }
4140 
4141 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
4142   auto *T = dyn_cast<MDTuple>(&N);
4143   if (!T)
4144     return &N;
4145 
4146   if (none_of(T->operands(), isOldLoopArgument))
4147     return &N;
4148 
4149   SmallVector<Metadata *, 8> Ops;
4150   Ops.reserve(T->getNumOperands());
4151   for (Metadata *MD : T->operands())
4152     Ops.push_back(upgradeLoopArgument(MD));
4153 
4154   return MDTuple::get(T->getContext(), Ops);
4155 }
4156 
4157 std::string llvm::UpgradeDataLayoutString(StringRef DL, StringRef TT) {
4158   std::string AddrSpaces = "-p270:32:32-p271:32:32-p272:64:64";
4159 
4160   // If X86, and the datalayout matches the expected format, add pointer size
4161   // address spaces to the datalayout.
4162   if (!Triple(TT).isX86() || DL.contains(AddrSpaces))
4163     return std::string(DL);
4164 
4165   SmallVector<StringRef, 4> Groups;
4166   Regex R("(e-m:[a-z](-p:32:32)?)(-[if]64:.*$)");
4167   if (!R.match(DL, &Groups))
4168     return std::string(DL);
4169 
4170   SmallString<1024> Buf;
4171   std::string Res = (Groups[1] + AddrSpaces + Groups[3]).toStringRef(Buf).str();
4172   return Res;
4173 }
4174 
4175 void llvm::UpgradeFramePointerAttributes(AttrBuilder &B) {
4176   StringRef FramePointer;
4177   if (B.contains("no-frame-pointer-elim")) {
4178     // The value can be "true" or "false".
4179     for (const auto &I : B.td_attrs())
4180       if (I.first == "no-frame-pointer-elim")
4181         FramePointer = I.second == "true" ? "all" : "none";
4182     B.removeAttribute("no-frame-pointer-elim");
4183   }
4184   if (B.contains("no-frame-pointer-elim-non-leaf")) {
4185     // The value is ignored. "no-frame-pointer-elim"="true" takes priority.
4186     if (FramePointer != "all")
4187       FramePointer = "non-leaf";
4188     B.removeAttribute("no-frame-pointer-elim-non-leaf");
4189   }
4190 
4191   if (!FramePointer.empty())
4192     B.addAttribute("frame-pointer", FramePointer);
4193 }
4194