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