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