1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the auto-upgrade helper functions.
10 // This is where deprecated IR intrinsics and other IR features are updated to
11 // current specifications.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DIBuilder.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/InstVisitor.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/IntrinsicsAArch64.h"
27 #include "llvm/IR/IntrinsicsARM.h"
28 #include "llvm/IR/IntrinsicsX86.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/Regex.h"
34 #include <cstring>
35 using namespace llvm;
36 
37 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
38 
39 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
40 // changed their type from v4f32 to v2i64.
41 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
42                                   Function *&NewFn) {
43   // Check whether this is an old version of the function, which received
44   // v4f32 arguments.
45   Type *Arg0Type = F->getFunctionType()->getParamType(0);
46   if (Arg0Type != FixedVectorType::get(Type::getFloatTy(F->getContext()), 4))
47     return false;
48 
49   // Yes, it's old, replace it with new version.
50   rename(F);
51   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
52   return true;
53 }
54 
55 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
56 // arguments have changed their type from i32 to i8.
57 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
58                                              Function *&NewFn) {
59   // Check that the last argument is an i32.
60   Type *LastArgType = F->getFunctionType()->getParamType(
61      F->getFunctionType()->getNumParams() - 1);
62   if (!LastArgType->isIntegerTy(32))
63     return false;
64 
65   // Move this function aside and map down.
66   rename(F);
67   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
68   return true;
69 }
70 
71 // Upgrade the declaration of fp compare intrinsics that change return type
72 // from scalar to vXi1 mask.
73 static bool UpgradeX86MaskedFPCompare(Function *F, Intrinsic::ID IID,
74                                       Function *&NewFn) {
75   // Check if the return type is a vector.
76   if (F->getReturnType()->isVectorTy())
77     return false;
78 
79   rename(F);
80   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
81   return true;
82 }
83 
84 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
85   // All of the intrinsics matches below should be marked with which llvm
86   // version started autoupgrading them. At some point in the future we would
87   // like to use this information to remove upgrade code for some older
88   // intrinsics. It is currently undecided how we will determine that future
89   // point.
90   if (Name == "addcarryx.u32" || // Added in 8.0
91       Name == "addcarryx.u64" || // Added in 8.0
92       Name == "addcarry.u32" || // Added in 8.0
93       Name == "addcarry.u64" || // Added in 8.0
94       Name == "subborrow.u32" || // Added in 8.0
95       Name == "subborrow.u64" || // Added in 8.0
96       Name.startswith("sse2.padds.") || // Added in 8.0
97       Name.startswith("sse2.psubs.") || // Added in 8.0
98       Name.startswith("sse2.paddus.") || // Added in 8.0
99       Name.startswith("sse2.psubus.") || // Added in 8.0
100       Name.startswith("avx2.padds.") || // Added in 8.0
101       Name.startswith("avx2.psubs.") || // Added in 8.0
102       Name.startswith("avx2.paddus.") || // Added in 8.0
103       Name.startswith("avx2.psubus.") || // Added in 8.0
104       Name.startswith("avx512.padds.") || // Added in 8.0
105       Name.startswith("avx512.psubs.") || // Added in 8.0
106       Name.startswith("avx512.mask.padds.") || // Added in 8.0
107       Name.startswith("avx512.mask.psubs.") || // Added in 8.0
108       Name.startswith("avx512.mask.paddus.") || // Added in 8.0
109       Name.startswith("avx512.mask.psubus.") || // Added in 8.0
110       Name=="ssse3.pabs.b.128" || // Added in 6.0
111       Name=="ssse3.pabs.w.128" || // Added in 6.0
112       Name=="ssse3.pabs.d.128" || // Added in 6.0
113       Name.startswith("fma4.vfmadd.s") || // Added in 7.0
114       Name.startswith("fma.vfmadd.") || // Added in 7.0
115       Name.startswith("fma.vfmsub.") || // Added in 7.0
116       Name.startswith("fma.vfmsubadd.") || // Added in 7.0
117       Name.startswith("fma.vfnmadd.") || // Added in 7.0
118       Name.startswith("fma.vfnmsub.") || // Added in 7.0
119       Name.startswith("avx512.mask.vfmadd.") || // Added in 7.0
120       Name.startswith("avx512.mask.vfnmadd.") || // Added in 7.0
121       Name.startswith("avx512.mask.vfnmsub.") || // Added in 7.0
122       Name.startswith("avx512.mask3.vfmadd.") || // Added in 7.0
123       Name.startswith("avx512.maskz.vfmadd.") || // Added in 7.0
124       Name.startswith("avx512.mask3.vfmsub.") || // Added in 7.0
125       Name.startswith("avx512.mask3.vfnmsub.") || // Added in 7.0
126       Name.startswith("avx512.mask.vfmaddsub.") || // Added in 7.0
127       Name.startswith("avx512.maskz.vfmaddsub.") || // Added in 7.0
128       Name.startswith("avx512.mask3.vfmaddsub.") || // Added in 7.0
129       Name.startswith("avx512.mask3.vfmsubadd.") || // Added in 7.0
130       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
131       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
132       Name.startswith("avx512.kunpck") || //added in 6.0
133       Name.startswith("avx2.pabs.") || // Added in 6.0
134       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
135       Name.startswith("avx512.broadcastm") || // Added in 6.0
136       Name == "sse.sqrt.ss" || // Added in 7.0
137       Name == "sse2.sqrt.sd" || // Added in 7.0
138       Name.startswith("avx512.mask.sqrt.p") || // Added in 7.0
139       Name.startswith("avx.sqrt.p") || // Added in 7.0
140       Name.startswith("sse2.sqrt.p") || // Added in 7.0
141       Name.startswith("sse.sqrt.p") || // Added in 7.0
142       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
143       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
144       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
145       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
146       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
147       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
148       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
149       Name.startswith("avx.vperm2f128.") || // Added in 6.0
150       Name == "avx2.vperm2i128" || // Added in 6.0
151       Name == "sse.add.ss" || // Added in 4.0
152       Name == "sse2.add.sd" || // Added in 4.0
153       Name == "sse.sub.ss" || // Added in 4.0
154       Name == "sse2.sub.sd" || // Added in 4.0
155       Name == "sse.mul.ss" || // Added in 4.0
156       Name == "sse2.mul.sd" || // Added in 4.0
157       Name == "sse.div.ss" || // Added in 4.0
158       Name == "sse2.div.sd" || // Added in 4.0
159       Name == "sse41.pmaxsb" || // Added in 3.9
160       Name == "sse2.pmaxs.w" || // Added in 3.9
161       Name == "sse41.pmaxsd" || // Added in 3.9
162       Name == "sse2.pmaxu.b" || // Added in 3.9
163       Name == "sse41.pmaxuw" || // Added in 3.9
164       Name == "sse41.pmaxud" || // Added in 3.9
165       Name == "sse41.pminsb" || // Added in 3.9
166       Name == "sse2.pmins.w" || // Added in 3.9
167       Name == "sse41.pminsd" || // Added in 3.9
168       Name == "sse2.pminu.b" || // Added in 3.9
169       Name == "sse41.pminuw" || // Added in 3.9
170       Name == "sse41.pminud" || // Added in 3.9
171       Name == "avx512.kand.w" || // Added in 7.0
172       Name == "avx512.kandn.w" || // Added in 7.0
173       Name == "avx512.knot.w" || // Added in 7.0
174       Name == "avx512.kor.w" || // Added in 7.0
175       Name == "avx512.kxor.w" || // Added in 7.0
176       Name == "avx512.kxnor.w" || // Added in 7.0
177       Name == "avx512.kortestc.w" || // Added in 7.0
178       Name == "avx512.kortestz.w" || // Added in 7.0
179       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
180       Name.startswith("avx2.pmax") || // Added in 3.9
181       Name.startswith("avx2.pmin") || // Added in 3.9
182       Name.startswith("avx512.mask.pmax") || // Added in 4.0
183       Name.startswith("avx512.mask.pmin") || // Added in 4.0
184       Name.startswith("avx2.vbroadcast") || // Added in 3.8
185       Name.startswith("avx2.pbroadcast") || // Added in 3.8
186       Name.startswith("avx.vpermil.") || // Added in 3.1
187       Name.startswith("sse2.pshuf") || // Added in 3.9
188       Name.startswith("avx512.pbroadcast") || // Added in 3.9
189       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
190       Name.startswith("avx512.mask.movddup") || // Added in 3.9
191       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
192       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
193       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
194       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
195       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
196       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
197       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
198       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
199       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
200       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
201       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
202       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
203       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
204       Name.startswith("avx512.mask.pand.") || // Added in 3.9
205       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
206       Name.startswith("avx512.mask.por.") || // Added in 3.9
207       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
208       Name.startswith("avx512.mask.and.") || // Added in 3.9
209       Name.startswith("avx512.mask.andn.") || // Added in 3.9
210       Name.startswith("avx512.mask.or.") || // Added in 3.9
211       Name.startswith("avx512.mask.xor.") || // Added in 3.9
212       Name.startswith("avx512.mask.padd.") || // Added in 4.0
213       Name.startswith("avx512.mask.psub.") || // Added in 4.0
214       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
215       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
216       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
217       Name.startswith("avx512.mask.cvtudq2ps.") || // Added in 7.0 updated 9.0
218       Name.startswith("avx512.mask.cvtqq2pd.") || // Added in 7.0 updated 9.0
219       Name.startswith("avx512.mask.cvtuqq2pd.") || // Added in 7.0 updated 9.0
220       Name.startswith("avx512.mask.cvtdq2ps.") || // Added in 7.0 updated 9.0
221       Name == "avx512.mask.vcvtph2ps.128" || // Added in 11.0
222       Name == "avx512.mask.vcvtph2ps.256" || // Added in 11.0
223       Name == "avx512.mask.cvtqq2ps.256" || // Added in 9.0
224       Name == "avx512.mask.cvtqq2ps.512" || // Added in 9.0
225       Name == "avx512.mask.cvtuqq2ps.256" || // Added in 9.0
226       Name == "avx512.mask.cvtuqq2ps.512" || // Added in 9.0
227       Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
228       Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
229       Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
230       Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
231       Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
232       Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
233       Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
234       Name == "avx512.cvtusi2sd" || // Added in 7.0
235       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
236       Name == "sse2.pmulu.dq" || // Added in 7.0
237       Name == "sse41.pmuldq" || // Added in 7.0
238       Name == "avx2.pmulu.dq" || // Added in 7.0
239       Name == "avx2.pmul.dq" || // Added in 7.0
240       Name == "avx512.pmulu.dq.512" || // Added in 7.0
241       Name == "avx512.pmul.dq.512" || // Added in 7.0
242       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
243       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
244       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
245       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
246       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
247       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
248       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
249       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
250       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
251       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
252       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
253       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
254       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
255       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
256       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
257       Name.startswith("avx512.cmp.p") || // Added in 12.0
258       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
259       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
260       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
261       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
262       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
263       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
264       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
265       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
266       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
267       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
268       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
269       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
270       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
271       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
272       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
273       Name.startswith("avx512.mask.pslli") || // Added in 4.0
274       Name.startswith("avx512.mask.psrai") || // Added in 4.0
275       Name.startswith("avx512.mask.psrli") || // Added in 4.0
276       Name.startswith("avx512.mask.psllv") || // Added in 4.0
277       Name.startswith("avx512.mask.psrav") || // Added in 4.0
278       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
279       Name.startswith("sse41.pmovsx") || // Added in 3.8
280       Name.startswith("sse41.pmovzx") || // Added in 3.9
281       Name.startswith("avx2.pmovsx") || // Added in 3.9
282       Name.startswith("avx2.pmovzx") || // Added in 3.9
283       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
284       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
285       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
286       Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
287       Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
288       Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
289       Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
290       Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
291       Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
292       Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
293       Name.startswith("avx512.mask.vpdpbusd.") || // Added in 7.0
294       Name.startswith("avx512.maskz.vpdpbusd.") || // Added in 7.0
295       Name.startswith("avx512.mask.vpdpbusds.") || // Added in 7.0
296       Name.startswith("avx512.maskz.vpdpbusds.") || // Added in 7.0
297       Name.startswith("avx512.mask.vpdpwssd.") || // Added in 7.0
298       Name.startswith("avx512.maskz.vpdpwssd.") || // Added in 7.0
299       Name.startswith("avx512.mask.vpdpwssds.") || // Added in 7.0
300       Name.startswith("avx512.maskz.vpdpwssds.") || // Added in 7.0
301       Name.startswith("avx512.mask.dbpsadbw.") || // Added in 7.0
302       Name.startswith("avx512.mask.vpshld.") || // Added in 7.0
303       Name.startswith("avx512.mask.vpshrd.") || // Added in 7.0
304       Name.startswith("avx512.mask.vpshldv.") || // Added in 8.0
305       Name.startswith("avx512.mask.vpshrdv.") || // Added in 8.0
306       Name.startswith("avx512.maskz.vpshldv.") || // Added in 8.0
307       Name.startswith("avx512.maskz.vpshrdv.") || // Added in 8.0
308       Name.startswith("avx512.vpshld.") || // Added in 8.0
309       Name.startswith("avx512.vpshrd.") || // Added in 8.0
310       Name.startswith("avx512.mask.add.p") || // Added in 7.0. 128/256 in 4.0
311       Name.startswith("avx512.mask.sub.p") || // Added in 7.0. 128/256 in 4.0
312       Name.startswith("avx512.mask.mul.p") || // Added in 7.0. 128/256 in 4.0
313       Name.startswith("avx512.mask.div.p") || // Added in 7.0. 128/256 in 4.0
314       Name.startswith("avx512.mask.max.p") || // Added in 7.0. 128/256 in 5.0
315       Name.startswith("avx512.mask.min.p") || // Added in 7.0. 128/256 in 5.0
316       Name.startswith("avx512.mask.fpclass.p") || // Added in 7.0
317       Name.startswith("avx512.mask.vpshufbitqmb.") || // Added in 8.0
318       Name.startswith("avx512.mask.pmultishift.qb.") || // Added in 8.0
319       Name.startswith("avx512.mask.conflict.") || // Added in 9.0
320       Name == "avx512.mask.pmov.qd.256" || // Added in 9.0
321       Name == "avx512.mask.pmov.qd.512" || // Added in 9.0
322       Name == "avx512.mask.pmov.wb.256" || // Added in 9.0
323       Name == "avx512.mask.pmov.wb.512" || // Added in 9.0
324       Name == "sse.cvtsi2ss" || // Added in 7.0
325       Name == "sse.cvtsi642ss" || // Added in 7.0
326       Name == "sse2.cvtsi2sd" || // Added in 7.0
327       Name == "sse2.cvtsi642sd" || // Added in 7.0
328       Name == "sse2.cvtss2sd" || // Added in 7.0
329       Name == "sse2.cvtdq2pd" || // Added in 3.9
330       Name == "sse2.cvtdq2ps" || // Added in 7.0
331       Name == "sse2.cvtps2pd" || // Added in 3.9
332       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
333       Name == "avx.cvtdq2.ps.256" || // Added in 7.0
334       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
335       Name.startswith("vcvtph2ps.") || // Added in 11.0
336       Name.startswith("avx.vinsertf128.") || // Added in 3.7
337       Name == "avx2.vinserti128" || // Added in 3.7
338       Name.startswith("avx512.mask.insert") || // Added in 4.0
339       Name.startswith("avx.vextractf128.") || // Added in 3.7
340       Name == "avx2.vextracti128" || // Added in 3.7
341       Name.startswith("avx512.mask.vextract") || // Added in 4.0
342       Name.startswith("sse4a.movnt.") || // Added in 3.9
343       Name.startswith("avx.movnt.") || // Added in 3.2
344       Name.startswith("avx512.storent.") || // Added in 3.9
345       Name == "sse41.movntdqa" || // Added in 5.0
346       Name == "avx2.movntdqa" || // Added in 5.0
347       Name == "avx512.movntdqa" || // Added in 5.0
348       Name == "sse2.storel.dq" || // Added in 3.9
349       Name.startswith("sse.storeu.") || // Added in 3.9
350       Name.startswith("sse2.storeu.") || // Added in 3.9
351       Name.startswith("avx.storeu.") || // Added in 3.9
352       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
353       Name.startswith("avx512.mask.store.p") || // Added in 3.9
354       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
355       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
356       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
357       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
358       Name == "avx512.mask.store.ss" || // Added in 7.0
359       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
360       Name.startswith("avx512.mask.load.") || // Added in 3.9
361       Name.startswith("avx512.mask.expand.load.") || // Added in 7.0
362       Name.startswith("avx512.mask.compress.store.") || // Added in 7.0
363       Name.startswith("avx512.mask.expand.b") || // Added in 9.0
364       Name.startswith("avx512.mask.expand.w") || // Added in 9.0
365       Name.startswith("avx512.mask.expand.d") || // Added in 9.0
366       Name.startswith("avx512.mask.expand.q") || // Added in 9.0
367       Name.startswith("avx512.mask.expand.p") || // Added in 9.0
368       Name.startswith("avx512.mask.compress.b") || // Added in 9.0
369       Name.startswith("avx512.mask.compress.w") || // Added in 9.0
370       Name.startswith("avx512.mask.compress.d") || // Added in 9.0
371       Name.startswith("avx512.mask.compress.q") || // Added in 9.0
372       Name.startswith("avx512.mask.compress.p") || // Added in 9.0
373       Name == "sse42.crc32.64.8" || // Added in 3.4
374       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
375       Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
376       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
377       Name.startswith("avx512.mask.valign.") || // Added in 4.0
378       Name.startswith("sse2.psll.dq") || // Added in 3.7
379       Name.startswith("sse2.psrl.dq") || // Added in 3.7
380       Name.startswith("avx2.psll.dq") || // Added in 3.7
381       Name.startswith("avx2.psrl.dq") || // Added in 3.7
382       Name.startswith("avx512.psll.dq") || // Added in 3.9
383       Name.startswith("avx512.psrl.dq") || // Added in 3.9
384       Name == "sse41.pblendw" || // Added in 3.7
385       Name.startswith("sse41.blendp") || // Added in 3.7
386       Name.startswith("avx.blend.p") || // Added in 3.7
387       Name == "avx2.pblendw" || // Added in 3.7
388       Name.startswith("avx2.pblendd.") || // Added in 3.7
389       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
390       Name == "avx2.vbroadcasti128" || // Added in 3.7
391       Name.startswith("avx512.mask.broadcastf32x4.") || // Added in 6.0
392       Name.startswith("avx512.mask.broadcastf64x2.") || // Added in 6.0
393       Name.startswith("avx512.mask.broadcastf32x8.") || // Added in 6.0
394       Name.startswith("avx512.mask.broadcastf64x4.") || // Added in 6.0
395       Name.startswith("avx512.mask.broadcasti32x4.") || // Added in 6.0
396       Name.startswith("avx512.mask.broadcasti64x2.") || // Added in 6.0
397       Name.startswith("avx512.mask.broadcasti32x8.") || // Added in 6.0
398       Name.startswith("avx512.mask.broadcasti64x4.") || // Added in 6.0
399       Name == "xop.vpcmov" || // Added in 3.8
400       Name == "xop.vpcmov.256" || // Added in 5.0
401       Name.startswith("avx512.mask.move.s") || // Added in 4.0
402       Name.startswith("avx512.cvtmask2") || // Added in 5.0
403       Name.startswith("xop.vpcom") || // Added in 3.2, Updated in 9.0
404       Name.startswith("xop.vprot") || // Added in 8.0
405       Name.startswith("avx512.prol") || // Added in 8.0
406       Name.startswith("avx512.pror") || // Added in 8.0
407       Name.startswith("avx512.mask.prorv.") || // Added in 8.0
408       Name.startswith("avx512.mask.pror.") ||  // Added in 8.0
409       Name.startswith("avx512.mask.prolv.") || // Added in 8.0
410       Name.startswith("avx512.mask.prol.") ||  // Added in 8.0
411       Name.startswith("avx512.ptestm") || //Added in 6.0
412       Name.startswith("avx512.ptestnm") || //Added in 6.0
413       Name.startswith("avx512.mask.pavg")) // Added in 6.0
414     return true;
415 
416   return false;
417 }
418 
419 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
420                                         Function *&NewFn) {
421   // Only handle intrinsics that start with "x86.".
422   if (!Name.startswith("x86."))
423     return false;
424   // Remove "x86." prefix.
425   Name = Name.substr(4);
426 
427   if (ShouldUpgradeX86Intrinsic(F, Name)) {
428     NewFn = nullptr;
429     return true;
430   }
431 
432   if (Name == "rdtscp") { // Added in 8.0
433     // If this intrinsic has 0 operands, it's the new version.
434     if (F->getFunctionType()->getNumParams() == 0)
435       return false;
436 
437     rename(F);
438     NewFn = Intrinsic::getDeclaration(F->getParent(),
439                                       Intrinsic::x86_rdtscp);
440     return true;
441   }
442 
443   // SSE4.1 ptest functions may have an old signature.
444   if (Name.startswith("sse41.ptest")) { // Added in 3.2
445     if (Name.substr(11) == "c")
446       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
447     if (Name.substr(11) == "z")
448       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
449     if (Name.substr(11) == "nzc")
450       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
451   }
452   // Several blend and other instructions with masks used the wrong number of
453   // bits.
454   if (Name == "sse41.insertps") // Added in 3.6
455     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
456                                             NewFn);
457   if (Name == "sse41.dppd") // Added in 3.6
458     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
459                                             NewFn);
460   if (Name == "sse41.dpps") // Added in 3.6
461     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
462                                             NewFn);
463   if (Name == "sse41.mpsadbw") // Added in 3.6
464     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
465                                             NewFn);
466   if (Name == "avx.dp.ps.256") // Added in 3.6
467     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
468                                             NewFn);
469   if (Name == "avx2.mpsadbw") // Added in 3.6
470     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
471                                             NewFn);
472   if (Name == "avx512.mask.cmp.pd.128") // Added in 7.0
473     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_128,
474                                      NewFn);
475   if (Name == "avx512.mask.cmp.pd.256") // Added in 7.0
476     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_256,
477                                      NewFn);
478   if (Name == "avx512.mask.cmp.pd.512") // Added in 7.0
479     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
480                                      NewFn);
481   if (Name == "avx512.mask.cmp.ps.128") // Added in 7.0
482     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_128,
483                                      NewFn);
484   if (Name == "avx512.mask.cmp.ps.256") // Added in 7.0
485     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_256,
486                                      NewFn);
487   if (Name == "avx512.mask.cmp.ps.512") // Added in 7.0
488     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
489                                      NewFn);
490 
491   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
492   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
493     rename(F);
494     NewFn = Intrinsic::getDeclaration(F->getParent(),
495                                       Intrinsic::x86_xop_vfrcz_ss);
496     return true;
497   }
498   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
499     rename(F);
500     NewFn = Intrinsic::getDeclaration(F->getParent(),
501                                       Intrinsic::x86_xop_vfrcz_sd);
502     return true;
503   }
504   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
505   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
506     auto Idx = F->getFunctionType()->getParamType(2);
507     if (Idx->isFPOrFPVectorTy()) {
508       rename(F);
509       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
510       unsigned EltSize = Idx->getScalarSizeInBits();
511       Intrinsic::ID Permil2ID;
512       if (EltSize == 64 && IdxSize == 128)
513         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
514       else if (EltSize == 32 && IdxSize == 128)
515         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
516       else if (EltSize == 64 && IdxSize == 256)
517         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
518       else
519         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
520       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
521       return true;
522     }
523   }
524 
525   if (Name == "seh.recoverfp") {
526     NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_recoverfp);
527     return true;
528   }
529 
530   return false;
531 }
532 
533 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
534   assert(F && "Illegal to upgrade a non-existent Function.");
535 
536   // Quickly eliminate it, if it's not a candidate.
537   StringRef Name = F->getName();
538   if (Name.size() <= 8 || !Name.startswith("llvm."))
539     return false;
540   Name = Name.substr(5); // Strip off "llvm."
541 
542   switch (Name[0]) {
543   default: break;
544   case 'a': {
545     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
546       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
547                                         F->arg_begin()->getType());
548       return true;
549     }
550     if (Name.startswith("arm.neon.vclz")) {
551       Type* args[2] = {
552         F->arg_begin()->getType(),
553         Type::getInt1Ty(F->getContext())
554       };
555       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
556       // the end of the name. Change name from llvm.arm.neon.vclz.* to
557       //  llvm.ctlz.*
558       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
559       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
560                                "llvm.ctlz." + Name.substr(14), F->getParent());
561       return true;
562     }
563     if (Name.startswith("arm.neon.vcnt")) {
564       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
565                                         F->arg_begin()->getType());
566       return true;
567     }
568     static const Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
569     if (vldRegex.match(Name)) {
570       auto fArgs = F->getFunctionType()->params();
571       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
572       // Can't use Intrinsic::getDeclaration here as the return types might
573       // then only be structurally equal.
574       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
575       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
576                                "llvm." + Name + ".p0i8", F->getParent());
577       return true;
578     }
579     static const Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
580     if (vstRegex.match(Name)) {
581       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
582                                                 Intrinsic::arm_neon_vst2,
583                                                 Intrinsic::arm_neon_vst3,
584                                                 Intrinsic::arm_neon_vst4};
585 
586       static const Intrinsic::ID StoreLaneInts[] = {
587         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
588         Intrinsic::arm_neon_vst4lane
589       };
590 
591       auto fArgs = F->getFunctionType()->params();
592       Type *Tys[] = {fArgs[0], fArgs[1]};
593       if (Name.find("lane") == StringRef::npos)
594         NewFn = Intrinsic::getDeclaration(F->getParent(),
595                                           StoreInts[fArgs.size() - 3], Tys);
596       else
597         NewFn = Intrinsic::getDeclaration(F->getParent(),
598                                           StoreLaneInts[fArgs.size() - 5], Tys);
599       return true;
600     }
601     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
602       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
603       return true;
604     }
605     if (Name.startswith("arm.neon.vqadds.")) {
606       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::sadd_sat,
607                                         F->arg_begin()->getType());
608       return true;
609     }
610     if (Name.startswith("arm.neon.vqaddu.")) {
611       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::uadd_sat,
612                                         F->arg_begin()->getType());
613       return true;
614     }
615     if (Name.startswith("arm.neon.vqsubs.")) {
616       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ssub_sat,
617                                         F->arg_begin()->getType());
618       return true;
619     }
620     if (Name.startswith("arm.neon.vqsubu.")) {
621       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::usub_sat,
622                                         F->arg_begin()->getType());
623       return true;
624     }
625     if (Name.startswith("aarch64.neon.addp")) {
626       if (F->arg_size() != 2)
627         break; // Invalid IR.
628       VectorType *Ty = dyn_cast<VectorType>(F->getReturnType());
629       if (Ty && Ty->getElementType()->isFloatingPointTy()) {
630         NewFn = Intrinsic::getDeclaration(F->getParent(),
631                                           Intrinsic::aarch64_neon_faddp, Ty);
632         return true;
633       }
634     }
635 
636     // Changed in 12.0: bfdot accept v4bf16 and v8bf16 instead of v8i8 and v16i8
637     // respectively
638     if ((Name.startswith("arm.neon.bfdot.") ||
639          Name.startswith("aarch64.neon.bfdot.")) &&
640         Name.endswith("i8")) {
641       Intrinsic::ID IID =
642           StringSwitch<Intrinsic::ID>(Name)
643               .Cases("arm.neon.bfdot.v2f32.v8i8",
644                      "arm.neon.bfdot.v4f32.v16i8",
645                      Intrinsic::arm_neon_bfdot)
646               .Cases("aarch64.neon.bfdot.v2f32.v8i8",
647                      "aarch64.neon.bfdot.v4f32.v16i8",
648                      Intrinsic::aarch64_neon_bfdot)
649               .Default(Intrinsic::not_intrinsic);
650       if (IID == Intrinsic::not_intrinsic)
651         break;
652 
653       size_t OperandWidth = F->getReturnType()->getPrimitiveSizeInBits();
654       assert((OperandWidth == 64 || OperandWidth == 128) &&
655              "Unexpected operand width");
656       LLVMContext &Ctx = F->getParent()->getContext();
657       std::array<Type *, 2> Tys {{
658         F->getReturnType(),
659         FixedVectorType::get(Type::getBFloatTy(Ctx), OperandWidth / 16)
660       }};
661       NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
662       return true;
663     }
664 
665     // Changed in 12.0: bfmmla, bfmlalb and bfmlalt are not polymorphic anymore
666     // and accept v8bf16 instead of v16i8
667     if ((Name.startswith("arm.neon.bfm") ||
668          Name.startswith("aarch64.neon.bfm")) &&
669         Name.endswith(".v4f32.v16i8")) {
670       Intrinsic::ID IID =
671           StringSwitch<Intrinsic::ID>(Name)
672               .Case("arm.neon.bfmmla.v4f32.v16i8",
673                     Intrinsic::arm_neon_bfmmla)
674               .Case("arm.neon.bfmlalb.v4f32.v16i8",
675                     Intrinsic::arm_neon_bfmlalb)
676               .Case("arm.neon.bfmlalt.v4f32.v16i8",
677                     Intrinsic::arm_neon_bfmlalt)
678               .Case("aarch64.neon.bfmmla.v4f32.v16i8",
679                     Intrinsic::aarch64_neon_bfmmla)
680               .Case("aarch64.neon.bfmlalb.v4f32.v16i8",
681                     Intrinsic::aarch64_neon_bfmlalb)
682               .Case("aarch64.neon.bfmlalt.v4f32.v16i8",
683                     Intrinsic::aarch64_neon_bfmlalt)
684               .Default(Intrinsic::not_intrinsic);
685       if (IID == Intrinsic::not_intrinsic)
686         break;
687 
688       std::array<Type *, 0> Tys;
689       NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
690       return true;
691     }
692     break;
693   }
694 
695   case 'c': {
696     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
697       rename(F);
698       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
699                                         F->arg_begin()->getType());
700       return true;
701     }
702     if (Name.startswith("cttz.") && F->arg_size() == 1) {
703       rename(F);
704       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
705                                         F->arg_begin()->getType());
706       return true;
707     }
708     break;
709   }
710   case 'd': {
711     if (Name == "dbg.value" && F->arg_size() == 4) {
712       rename(F);
713       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
714       return true;
715     }
716     break;
717   }
718   case 'e': {
719     SmallVector<StringRef, 2> Groups;
720     static const Regex R("^experimental.vector.reduce.([a-z]+)\\.[fi][0-9]+");
721     if (R.match(Name, &Groups)) {
722       Intrinsic::ID ID = Intrinsic::not_intrinsic;
723       if (Groups[1] == "fadd")
724         ID = Intrinsic::experimental_vector_reduce_v2_fadd;
725       if (Groups[1] == "fmul")
726         ID = Intrinsic::experimental_vector_reduce_v2_fmul;
727 
728       if (ID != Intrinsic::not_intrinsic) {
729         rename(F);
730         auto Args = F->getFunctionType()->params();
731         Type *Tys[] = {F->getFunctionType()->getReturnType(), Args[1]};
732         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
733         return true;
734       }
735     }
736     break;
737   }
738   case 'i':
739   case 'l': {
740     bool IsLifetimeStart = Name.startswith("lifetime.start");
741     if (IsLifetimeStart || Name.startswith("invariant.start")) {
742       Intrinsic::ID ID = IsLifetimeStart ?
743         Intrinsic::lifetime_start : Intrinsic::invariant_start;
744       auto Args = F->getFunctionType()->params();
745       Type* ObjectPtr[1] = {Args[1]};
746       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
747         rename(F);
748         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
749         return true;
750       }
751     }
752 
753     bool IsLifetimeEnd = Name.startswith("lifetime.end");
754     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
755       Intrinsic::ID ID = IsLifetimeEnd ?
756         Intrinsic::lifetime_end : Intrinsic::invariant_end;
757 
758       auto Args = F->getFunctionType()->params();
759       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
760       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
761         rename(F);
762         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
763         return true;
764       }
765     }
766     if (Name.startswith("invariant.group.barrier")) {
767       // Rename invariant.group.barrier to launder.invariant.group
768       auto Args = F->getFunctionType()->params();
769       Type* ObjectPtr[1] = {Args[0]};
770       rename(F);
771       NewFn = Intrinsic::getDeclaration(F->getParent(),
772           Intrinsic::launder_invariant_group, ObjectPtr);
773       return true;
774 
775     }
776 
777     break;
778   }
779   case 'm': {
780     if (Name.startswith("masked.load.")) {
781       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
782       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
783         rename(F);
784         NewFn = Intrinsic::getDeclaration(F->getParent(),
785                                           Intrinsic::masked_load,
786                                           Tys);
787         return true;
788       }
789     }
790     if (Name.startswith("masked.store.")) {
791       auto Args = F->getFunctionType()->params();
792       Type *Tys[] = { Args[0], Args[1] };
793       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
794         rename(F);
795         NewFn = Intrinsic::getDeclaration(F->getParent(),
796                                           Intrinsic::masked_store,
797                                           Tys);
798         return true;
799       }
800     }
801     // Renaming gather/scatter intrinsics with no address space overloading
802     // to the new overload which includes an address space
803     if (Name.startswith("masked.gather.")) {
804       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
805       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
806         rename(F);
807         NewFn = Intrinsic::getDeclaration(F->getParent(),
808                                           Intrinsic::masked_gather, Tys);
809         return true;
810       }
811     }
812     if (Name.startswith("masked.scatter.")) {
813       auto Args = F->getFunctionType()->params();
814       Type *Tys[] = {Args[0], Args[1]};
815       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
816         rename(F);
817         NewFn = Intrinsic::getDeclaration(F->getParent(),
818                                           Intrinsic::masked_scatter, Tys);
819         return true;
820       }
821     }
822     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
823     // alignment parameter to embedding the alignment as an attribute of
824     // the pointer args.
825     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
826       rename(F);
827       // Get the types of dest, src, and len
828       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
829       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
830                                         ParamTypes);
831       return true;
832     }
833     if (Name.startswith("memmove.") && F->arg_size() == 5) {
834       rename(F);
835       // Get the types of dest, src, and len
836       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
837       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
838                                         ParamTypes);
839       return true;
840     }
841     if (Name.startswith("memset.") && F->arg_size() == 5) {
842       rename(F);
843       // Get the types of dest, and len
844       const auto *FT = F->getFunctionType();
845       Type *ParamTypes[2] = {
846           FT->getParamType(0), // Dest
847           FT->getParamType(2)  // len
848       };
849       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
850                                         ParamTypes);
851       return true;
852     }
853     break;
854   }
855   case 'n': {
856     if (Name.startswith("nvvm.")) {
857       Name = Name.substr(5);
858 
859       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
860       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
861                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
862                               .Case("clz.i", Intrinsic::ctlz)
863                               .Case("popc.i", Intrinsic::ctpop)
864                               .Default(Intrinsic::not_intrinsic);
865       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
866         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
867                                           {F->getReturnType()});
868         return true;
869       }
870 
871       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
872       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
873       //
874       // TODO: We could add lohi.i2d.
875       bool Expand = StringSwitch<bool>(Name)
876                         .Cases("abs.i", "abs.ll", true)
877                         .Cases("clz.ll", "popc.ll", "h2f", true)
878                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
879                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
880                         .StartsWith("atomic.load.add.f32.p", true)
881                         .StartsWith("atomic.load.add.f64.p", true)
882                         .Default(false);
883       if (Expand) {
884         NewFn = nullptr;
885         return true;
886       }
887     }
888     break;
889   }
890   case 'o':
891     // We only need to change the name to match the mangling including the
892     // address space.
893     if (Name.startswith("objectsize.")) {
894       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
895       if (F->arg_size() == 2 || F->arg_size() == 3 ||
896           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
897         rename(F);
898         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
899                                           Tys);
900         return true;
901       }
902     }
903     break;
904 
905   case 'p':
906     if (Name == "prefetch") {
907       // Handle address space overloading.
908       Type *Tys[] = {F->arg_begin()->getType()};
909       if (F->getName() != Intrinsic::getName(Intrinsic::prefetch, Tys)) {
910         rename(F);
911         NewFn =
912             Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch, Tys);
913         return true;
914       }
915     }
916     break;
917 
918   case 's':
919     if (Name == "stackprotectorcheck") {
920       NewFn = nullptr;
921       return true;
922     }
923     break;
924 
925   case 'x':
926     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
927       return true;
928   }
929   // Remangle our intrinsic since we upgrade the mangling
930   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
931   if (Result != None) {
932     NewFn = Result.getValue();
933     return true;
934   }
935 
936   //  This may not belong here. This function is effectively being overloaded
937   //  to both detect an intrinsic which needs upgrading, and to provide the
938   //  upgraded form of the intrinsic. We should perhaps have two separate
939   //  functions for this.
940   return false;
941 }
942 
943 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
944   NewFn = nullptr;
945   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
946   assert(F != NewFn && "Intrinsic function upgraded to the same function");
947 
948   // Upgrade intrinsic attributes.  This does not change the function.
949   if (NewFn)
950     F = NewFn;
951   if (Intrinsic::ID id = F->getIntrinsicID())
952     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
953   return Upgraded;
954 }
955 
956 GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
957   if (!(GV->hasName() && (GV->getName() == "llvm.global_ctors" ||
958                           GV->getName() == "llvm.global_dtors")) ||
959       !GV->hasInitializer())
960     return nullptr;
961   ArrayType *ATy = dyn_cast<ArrayType>(GV->getValueType());
962   if (!ATy)
963     return nullptr;
964   StructType *STy = dyn_cast<StructType>(ATy->getElementType());
965   if (!STy || STy->getNumElements() != 2)
966     return nullptr;
967 
968   LLVMContext &C = GV->getContext();
969   IRBuilder<> IRB(C);
970   auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
971                                IRB.getInt8PtrTy());
972   Constant *Init = GV->getInitializer();
973   unsigned N = Init->getNumOperands();
974   std::vector<Constant *> NewCtors(N);
975   for (unsigned i = 0; i != N; ++i) {
976     auto Ctor = cast<Constant>(Init->getOperand(i));
977     NewCtors[i] = ConstantStruct::get(
978         EltTy, Ctor->getAggregateElement(0u), Ctor->getAggregateElement(1),
979         Constant::getNullValue(IRB.getInt8PtrTy()));
980   }
981   Constant *NewInit = ConstantArray::get(ArrayType::get(EltTy, N), NewCtors);
982 
983   return new GlobalVariable(NewInit->getType(), false, GV->getLinkage(),
984                             NewInit, GV->getName());
985 }
986 
987 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
988 // to byte shuffles.
989 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
990                                          Value *Op, unsigned Shift) {
991   auto *ResultTy = cast<FixedVectorType>(Op->getType());
992   unsigned NumElts = ResultTy->getNumElements() * 8;
993 
994   // Bitcast from a 64-bit element type to a byte element type.
995   Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
996   Op = Builder.CreateBitCast(Op, VecTy, "cast");
997 
998   // We'll be shuffling in zeroes.
999   Value *Res = Constant::getNullValue(VecTy);
1000 
1001   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1002   // we'll just return the zero vector.
1003   if (Shift < 16) {
1004     int Idxs[64];
1005     // 256/512-bit version is split into 2/4 16-byte lanes.
1006     for (unsigned l = 0; l != NumElts; l += 16)
1007       for (unsigned i = 0; i != 16; ++i) {
1008         unsigned Idx = NumElts + i - Shift;
1009         if (Idx < NumElts)
1010           Idx -= NumElts - 16; // end of lane, switch operand.
1011         Idxs[l + i] = Idx + l;
1012       }
1013 
1014     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
1015   }
1016 
1017   // Bitcast back to a 64-bit element type.
1018   return Builder.CreateBitCast(Res, ResultTy, "cast");
1019 }
1020 
1021 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
1022 // to byte shuffles.
1023 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
1024                                          unsigned Shift) {
1025   auto *ResultTy = cast<FixedVectorType>(Op->getType());
1026   unsigned NumElts = ResultTy->getNumElements() * 8;
1027 
1028   // Bitcast from a 64-bit element type to a byte element type.
1029   Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
1030   Op = Builder.CreateBitCast(Op, VecTy, "cast");
1031 
1032   // We'll be shuffling in zeroes.
1033   Value *Res = Constant::getNullValue(VecTy);
1034 
1035   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1036   // we'll just return the zero vector.
1037   if (Shift < 16) {
1038     int Idxs[64];
1039     // 256/512-bit version is split into 2/4 16-byte lanes.
1040     for (unsigned l = 0; l != NumElts; l += 16)
1041       for (unsigned i = 0; i != 16; ++i) {
1042         unsigned Idx = i + Shift;
1043         if (Idx >= 16)
1044           Idx += NumElts - 16; // end of lane, switch operand.
1045         Idxs[l + i] = Idx + l;
1046       }
1047 
1048     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
1049   }
1050 
1051   // Bitcast back to a 64-bit element type.
1052   return Builder.CreateBitCast(Res, ResultTy, "cast");
1053 }
1054 
1055 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
1056                             unsigned NumElts) {
1057   assert(isPowerOf2_32(NumElts) && "Expected power-of-2 mask elements");
1058   llvm::VectorType *MaskTy = FixedVectorType::get(
1059       Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
1060   Mask = Builder.CreateBitCast(Mask, MaskTy);
1061 
1062   // If we have less than 8 elements (1, 2 or 4), then the starting mask was an
1063   // i8 and we need to extract down to the right number of elements.
1064   if (NumElts <= 4) {
1065     int Indices[4];
1066     for (unsigned i = 0; i != NumElts; ++i)
1067       Indices[i] = i;
1068     Mask = Builder.CreateShuffleVector(
1069         Mask, Mask, makeArrayRef(Indices, NumElts), "extract");
1070   }
1071 
1072   return Mask;
1073 }
1074 
1075 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
1076                             Value *Op0, Value *Op1) {
1077   // If the mask is all ones just emit the first operation.
1078   if (const auto *C = dyn_cast<Constant>(Mask))
1079     if (C->isAllOnesValue())
1080       return Op0;
1081 
1082   Mask = getX86MaskVec(Builder, Mask,
1083                        cast<FixedVectorType>(Op0->getType())->getNumElements());
1084   return Builder.CreateSelect(Mask, Op0, Op1);
1085 }
1086 
1087 static Value *EmitX86ScalarSelect(IRBuilder<> &Builder, Value *Mask,
1088                                   Value *Op0, Value *Op1) {
1089   // If the mask is all ones just emit the first operation.
1090   if (const auto *C = dyn_cast<Constant>(Mask))
1091     if (C->isAllOnesValue())
1092       return Op0;
1093 
1094   auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(),
1095                                       Mask->getType()->getIntegerBitWidth());
1096   Mask = Builder.CreateBitCast(Mask, MaskTy);
1097   Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
1098   return Builder.CreateSelect(Mask, Op0, Op1);
1099 }
1100 
1101 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
1102 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
1103 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
1104 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
1105                                         Value *Op1, Value *Shift,
1106                                         Value *Passthru, Value *Mask,
1107                                         bool IsVALIGN) {
1108   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
1109 
1110   unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1111   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
1112   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
1113   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
1114 
1115   // Mask the immediate for VALIGN.
1116   if (IsVALIGN)
1117     ShiftVal &= (NumElts - 1);
1118 
1119   // If palignr is shifting the pair of vectors more than the size of two
1120   // lanes, emit zero.
1121   if (ShiftVal >= 32)
1122     return llvm::Constant::getNullValue(Op0->getType());
1123 
1124   // If palignr is shifting the pair of input vectors more than one lane,
1125   // but less than two lanes, convert to shifting in zeroes.
1126   if (ShiftVal > 16) {
1127     ShiftVal -= 16;
1128     Op1 = Op0;
1129     Op0 = llvm::Constant::getNullValue(Op0->getType());
1130   }
1131 
1132   int Indices[64];
1133   // 256-bit palignr operates on 128-bit lanes so we need to handle that
1134   for (unsigned l = 0; l < NumElts; l += 16) {
1135     for (unsigned i = 0; i != 16; ++i) {
1136       unsigned Idx = ShiftVal + i;
1137       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
1138         Idx += NumElts - 16; // End of lane, switch operand.
1139       Indices[l + i] = Idx + l;
1140     }
1141   }
1142 
1143   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
1144                                              makeArrayRef(Indices, NumElts),
1145                                              "palignr");
1146 
1147   return EmitX86Select(Builder, Mask, Align, Passthru);
1148 }
1149 
1150 static Value *UpgradeX86VPERMT2Intrinsics(IRBuilder<> &Builder, CallInst &CI,
1151                                           bool ZeroMask, bool IndexForm) {
1152   Type *Ty = CI.getType();
1153   unsigned VecWidth = Ty->getPrimitiveSizeInBits();
1154   unsigned EltWidth = Ty->getScalarSizeInBits();
1155   bool IsFloat = Ty->isFPOrFPVectorTy();
1156   Intrinsic::ID IID;
1157   if (VecWidth == 128 && EltWidth == 32 && IsFloat)
1158     IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
1159   else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
1160     IID = Intrinsic::x86_avx512_vpermi2var_d_128;
1161   else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
1162     IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
1163   else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
1164     IID = Intrinsic::x86_avx512_vpermi2var_q_128;
1165   else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1166     IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
1167   else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1168     IID = Intrinsic::x86_avx512_vpermi2var_d_256;
1169   else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1170     IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
1171   else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1172     IID = Intrinsic::x86_avx512_vpermi2var_q_256;
1173   else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1174     IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
1175   else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1176     IID = Intrinsic::x86_avx512_vpermi2var_d_512;
1177   else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1178     IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
1179   else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1180     IID = Intrinsic::x86_avx512_vpermi2var_q_512;
1181   else if (VecWidth == 128 && EltWidth == 16)
1182     IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
1183   else if (VecWidth == 256 && EltWidth == 16)
1184     IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
1185   else if (VecWidth == 512 && EltWidth == 16)
1186     IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
1187   else if (VecWidth == 128 && EltWidth == 8)
1188     IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
1189   else if (VecWidth == 256 && EltWidth == 8)
1190     IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
1191   else if (VecWidth == 512 && EltWidth == 8)
1192     IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
1193   else
1194     llvm_unreachable("Unexpected intrinsic");
1195 
1196   Value *Args[] = { CI.getArgOperand(0) , CI.getArgOperand(1),
1197                     CI.getArgOperand(2) };
1198 
1199   // If this isn't index form we need to swap operand 0 and 1.
1200   if (!IndexForm)
1201     std::swap(Args[0], Args[1]);
1202 
1203   Value *V = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1204                                 Args);
1205   Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty)
1206                              : Builder.CreateBitCast(CI.getArgOperand(1),
1207                                                      Ty);
1208   return EmitX86Select(Builder, CI.getArgOperand(3), V, PassThru);
1209 }
1210 
1211 static Value *UpgradeX86AddSubSatIntrinsics(IRBuilder<> &Builder, CallInst &CI,
1212                                             bool IsSigned, bool IsAddition) {
1213   Type *Ty = CI.getType();
1214   Value *Op0 = CI.getOperand(0);
1215   Value *Op1 = CI.getOperand(1);
1216 
1217   Intrinsic::ID IID =
1218       IsSigned ? (IsAddition ? Intrinsic::sadd_sat : Intrinsic::ssub_sat)
1219                : (IsAddition ? Intrinsic::uadd_sat : Intrinsic::usub_sat);
1220   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1221   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1});
1222 
1223   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1224     Value *VecSrc = CI.getOperand(2);
1225     Value *Mask = CI.getOperand(3);
1226     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1227   }
1228   return Res;
1229 }
1230 
1231 static Value *upgradeX86Rotate(IRBuilder<> &Builder, CallInst &CI,
1232                                bool IsRotateRight) {
1233   Type *Ty = CI.getType();
1234   Value *Src = CI.getArgOperand(0);
1235   Value *Amt = CI.getArgOperand(1);
1236 
1237   // Amount may be scalar immediate, in which case create a splat vector.
1238   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1239   // we only care about the lowest log2 bits anyway.
1240   if (Amt->getType() != Ty) {
1241     unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1242     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1243     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1244   }
1245 
1246   Intrinsic::ID IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1247   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1248   Value *Res = Builder.CreateCall(Intrin, {Src, Src, Amt});
1249 
1250   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1251     Value *VecSrc = CI.getOperand(2);
1252     Value *Mask = CI.getOperand(3);
1253     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1254   }
1255   return Res;
1256 }
1257 
1258 static Value *upgradeX86vpcom(IRBuilder<> &Builder, CallInst &CI, unsigned Imm,
1259                               bool IsSigned) {
1260   Type *Ty = CI.getType();
1261   Value *LHS = CI.getArgOperand(0);
1262   Value *RHS = CI.getArgOperand(1);
1263 
1264   CmpInst::Predicate Pred;
1265   switch (Imm) {
1266   case 0x0:
1267     Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1268     break;
1269   case 0x1:
1270     Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1271     break;
1272   case 0x2:
1273     Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1274     break;
1275   case 0x3:
1276     Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1277     break;
1278   case 0x4:
1279     Pred = ICmpInst::ICMP_EQ;
1280     break;
1281   case 0x5:
1282     Pred = ICmpInst::ICMP_NE;
1283     break;
1284   case 0x6:
1285     return Constant::getNullValue(Ty); // FALSE
1286   case 0x7:
1287     return Constant::getAllOnesValue(Ty); // TRUE
1288   default:
1289     llvm_unreachable("Unknown XOP vpcom/vpcomu predicate");
1290   }
1291 
1292   Value *Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1293   Value *Ext = Builder.CreateSExt(Cmp, Ty);
1294   return Ext;
1295 }
1296 
1297 static Value *upgradeX86ConcatShift(IRBuilder<> &Builder, CallInst &CI,
1298                                     bool IsShiftRight, bool ZeroMask) {
1299   Type *Ty = CI.getType();
1300   Value *Op0 = CI.getArgOperand(0);
1301   Value *Op1 = CI.getArgOperand(1);
1302   Value *Amt = CI.getArgOperand(2);
1303 
1304   if (IsShiftRight)
1305     std::swap(Op0, Op1);
1306 
1307   // Amount may be scalar immediate, in which case create a splat vector.
1308   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1309   // we only care about the lowest log2 bits anyway.
1310   if (Amt->getType() != Ty) {
1311     unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1312     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1313     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1314   }
1315 
1316   Intrinsic::ID IID = IsShiftRight ? Intrinsic::fshr : Intrinsic::fshl;
1317   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1318   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1, Amt});
1319 
1320   unsigned NumArgs = CI.getNumArgOperands();
1321   if (NumArgs >= 4) { // For masked intrinsics.
1322     Value *VecSrc = NumArgs == 5 ? CI.getArgOperand(3) :
1323                     ZeroMask     ? ConstantAggregateZero::get(CI.getType()) :
1324                                    CI.getArgOperand(0);
1325     Value *Mask = CI.getOperand(NumArgs - 1);
1326     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1327   }
1328   return Res;
1329 }
1330 
1331 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
1332                                  Value *Ptr, Value *Data, Value *Mask,
1333                                  bool Aligned) {
1334   // Cast the pointer to the right type.
1335   Ptr = Builder.CreateBitCast(Ptr,
1336                               llvm::PointerType::getUnqual(Data->getType()));
1337   const Align Alignment =
1338       Aligned
1339           ? Align(Data->getType()->getPrimitiveSizeInBits().getFixedSize() / 8)
1340           : Align(1);
1341 
1342   // If the mask is all ones just emit a regular store.
1343   if (const auto *C = dyn_cast<Constant>(Mask))
1344     if (C->isAllOnesValue())
1345       return Builder.CreateAlignedStore(Data, Ptr, Alignment);
1346 
1347   // Convert the mask from an integer type to a vector of i1.
1348   unsigned NumElts = cast<FixedVectorType>(Data->getType())->getNumElements();
1349   Mask = getX86MaskVec(Builder, Mask, NumElts);
1350   return Builder.CreateMaskedStore(Data, Ptr, Alignment, Mask);
1351 }
1352 
1353 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
1354                                 Value *Ptr, Value *Passthru, Value *Mask,
1355                                 bool Aligned) {
1356   Type *ValTy = Passthru->getType();
1357   // Cast the pointer to the right type.
1358   Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ValTy));
1359   const Align Alignment =
1360       Aligned
1361           ? Align(Passthru->getType()->getPrimitiveSizeInBits().getFixedSize() /
1362                   8)
1363           : Align(1);
1364 
1365   // If the mask is all ones just emit a regular store.
1366   if (const auto *C = dyn_cast<Constant>(Mask))
1367     if (C->isAllOnesValue())
1368       return Builder.CreateAlignedLoad(ValTy, Ptr, Alignment);
1369 
1370   // Convert the mask from an integer type to a vector of i1.
1371   unsigned NumElts =
1372       cast<FixedVectorType>(Passthru->getType())->getNumElements();
1373   Mask = getX86MaskVec(Builder, Mask, NumElts);
1374   return Builder.CreateMaskedLoad(Ptr, Alignment, Mask, Passthru);
1375 }
1376 
1377 static Value *upgradeAbs(IRBuilder<> &Builder, CallInst &CI) {
1378   Value *Op0 = CI.getArgOperand(0);
1379   llvm::Type *Ty = Op0->getType();
1380   Value *Zero = llvm::Constant::getNullValue(Ty);
1381   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_SGT, Op0, Zero);
1382   Value *Neg = Builder.CreateNeg(Op0);
1383   Value *Res = Builder.CreateSelect(Cmp, Op0, Neg);
1384 
1385   if (CI.getNumArgOperands() == 3)
1386     Res = EmitX86Select(Builder,CI.getArgOperand(2), Res, CI.getArgOperand(1));
1387 
1388   return Res;
1389 }
1390 
1391 static Value *upgradeIntMinMax(IRBuilder<> &Builder, CallInst &CI,
1392                                ICmpInst::Predicate Pred) {
1393   Value *Op0 = CI.getArgOperand(0);
1394   Value *Op1 = CI.getArgOperand(1);
1395   Value *Cmp = Builder.CreateICmp(Pred, Op0, Op1);
1396   Value *Res = Builder.CreateSelect(Cmp, Op0, Op1);
1397 
1398   if (CI.getNumArgOperands() == 4)
1399     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1400 
1401   return Res;
1402 }
1403 
1404 static Value *upgradePMULDQ(IRBuilder<> &Builder, CallInst &CI, bool IsSigned) {
1405   Type *Ty = CI.getType();
1406 
1407   // Arguments have a vXi32 type so cast to vXi64.
1408   Value *LHS = Builder.CreateBitCast(CI.getArgOperand(0), Ty);
1409   Value *RHS = Builder.CreateBitCast(CI.getArgOperand(1), Ty);
1410 
1411   if (IsSigned) {
1412     // Shift left then arithmetic shift right.
1413     Constant *ShiftAmt = ConstantInt::get(Ty, 32);
1414     LHS = Builder.CreateShl(LHS, ShiftAmt);
1415     LHS = Builder.CreateAShr(LHS, ShiftAmt);
1416     RHS = Builder.CreateShl(RHS, ShiftAmt);
1417     RHS = Builder.CreateAShr(RHS, ShiftAmt);
1418   } else {
1419     // Clear the upper bits.
1420     Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
1421     LHS = Builder.CreateAnd(LHS, Mask);
1422     RHS = Builder.CreateAnd(RHS, Mask);
1423   }
1424 
1425   Value *Res = Builder.CreateMul(LHS, RHS);
1426 
1427   if (CI.getNumArgOperands() == 4)
1428     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1429 
1430   return Res;
1431 }
1432 
1433 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
1434 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder, Value *Vec,
1435                                      Value *Mask) {
1436   unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1437   if (Mask) {
1438     const auto *C = dyn_cast<Constant>(Mask);
1439     if (!C || !C->isAllOnesValue())
1440       Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
1441   }
1442 
1443   if (NumElts < 8) {
1444     int Indices[8];
1445     for (unsigned i = 0; i != NumElts; ++i)
1446       Indices[i] = i;
1447     for (unsigned i = NumElts; i != 8; ++i)
1448       Indices[i] = NumElts + i % NumElts;
1449     Vec = Builder.CreateShuffleVector(Vec,
1450                                       Constant::getNullValue(Vec->getType()),
1451                                       Indices);
1452   }
1453   return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
1454 }
1455 
1456 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
1457                                    unsigned CC, bool Signed) {
1458   Value *Op0 = CI.getArgOperand(0);
1459   unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1460 
1461   Value *Cmp;
1462   if (CC == 3) {
1463     Cmp = Constant::getNullValue(
1464         FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1465   } else if (CC == 7) {
1466     Cmp = Constant::getAllOnesValue(
1467         FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1468   } else {
1469     ICmpInst::Predicate Pred;
1470     switch (CC) {
1471     default: llvm_unreachable("Unknown condition code");
1472     case 0: Pred = ICmpInst::ICMP_EQ;  break;
1473     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
1474     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
1475     case 4: Pred = ICmpInst::ICMP_NE;  break;
1476     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
1477     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
1478     }
1479     Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
1480   }
1481 
1482   Value *Mask = CI.getArgOperand(CI.getNumArgOperands() - 1);
1483 
1484   return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask);
1485 }
1486 
1487 // Replace a masked intrinsic with an older unmasked intrinsic.
1488 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
1489                                     Intrinsic::ID IID) {
1490   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
1491   Value *Rep = Builder.CreateCall(Intrin,
1492                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
1493   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
1494 }
1495 
1496 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallInst &CI) {
1497   Value* A = CI.getArgOperand(0);
1498   Value* B = CI.getArgOperand(1);
1499   Value* Src = CI.getArgOperand(2);
1500   Value* Mask = CI.getArgOperand(3);
1501 
1502   Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
1503   Value* Cmp = Builder.CreateIsNotNull(AndNode);
1504   Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
1505   Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
1506   Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
1507   return Builder.CreateInsertElement(A, Select, (uint64_t)0);
1508 }
1509 
1510 
1511 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallInst &CI) {
1512   Value* Op = CI.getArgOperand(0);
1513   Type* ReturnOp = CI.getType();
1514   unsigned NumElts = cast<FixedVectorType>(CI.getType())->getNumElements();
1515   Value *Mask = getX86MaskVec(Builder, Op, NumElts);
1516   return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
1517 }
1518 
1519 // Replace intrinsic with unmasked version and a select.
1520 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
1521                                       CallInst &CI, Value *&Rep) {
1522   Name = Name.substr(12); // Remove avx512.mask.
1523 
1524   unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
1525   unsigned EltWidth = CI.getType()->getScalarSizeInBits();
1526   Intrinsic::ID IID;
1527   if (Name.startswith("max.p")) {
1528     if (VecWidth == 128 && EltWidth == 32)
1529       IID = Intrinsic::x86_sse_max_ps;
1530     else if (VecWidth == 128 && EltWidth == 64)
1531       IID = Intrinsic::x86_sse2_max_pd;
1532     else if (VecWidth == 256 && EltWidth == 32)
1533       IID = Intrinsic::x86_avx_max_ps_256;
1534     else if (VecWidth == 256 && EltWidth == 64)
1535       IID = Intrinsic::x86_avx_max_pd_256;
1536     else
1537       llvm_unreachable("Unexpected intrinsic");
1538   } else if (Name.startswith("min.p")) {
1539     if (VecWidth == 128 && EltWidth == 32)
1540       IID = Intrinsic::x86_sse_min_ps;
1541     else if (VecWidth == 128 && EltWidth == 64)
1542       IID = Intrinsic::x86_sse2_min_pd;
1543     else if (VecWidth == 256 && EltWidth == 32)
1544       IID = Intrinsic::x86_avx_min_ps_256;
1545     else if (VecWidth == 256 && EltWidth == 64)
1546       IID = Intrinsic::x86_avx_min_pd_256;
1547     else
1548       llvm_unreachable("Unexpected intrinsic");
1549   } else if (Name.startswith("pshuf.b.")) {
1550     if (VecWidth == 128)
1551       IID = Intrinsic::x86_ssse3_pshuf_b_128;
1552     else if (VecWidth == 256)
1553       IID = Intrinsic::x86_avx2_pshuf_b;
1554     else if (VecWidth == 512)
1555       IID = Intrinsic::x86_avx512_pshuf_b_512;
1556     else
1557       llvm_unreachable("Unexpected intrinsic");
1558   } else if (Name.startswith("pmul.hr.sw.")) {
1559     if (VecWidth == 128)
1560       IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1561     else if (VecWidth == 256)
1562       IID = Intrinsic::x86_avx2_pmul_hr_sw;
1563     else if (VecWidth == 512)
1564       IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1565     else
1566       llvm_unreachable("Unexpected intrinsic");
1567   } else if (Name.startswith("pmulh.w.")) {
1568     if (VecWidth == 128)
1569       IID = Intrinsic::x86_sse2_pmulh_w;
1570     else if (VecWidth == 256)
1571       IID = Intrinsic::x86_avx2_pmulh_w;
1572     else if (VecWidth == 512)
1573       IID = Intrinsic::x86_avx512_pmulh_w_512;
1574     else
1575       llvm_unreachable("Unexpected intrinsic");
1576   } else if (Name.startswith("pmulhu.w.")) {
1577     if (VecWidth == 128)
1578       IID = Intrinsic::x86_sse2_pmulhu_w;
1579     else if (VecWidth == 256)
1580       IID = Intrinsic::x86_avx2_pmulhu_w;
1581     else if (VecWidth == 512)
1582       IID = Intrinsic::x86_avx512_pmulhu_w_512;
1583     else
1584       llvm_unreachable("Unexpected intrinsic");
1585   } else if (Name.startswith("pmaddw.d.")) {
1586     if (VecWidth == 128)
1587       IID = Intrinsic::x86_sse2_pmadd_wd;
1588     else if (VecWidth == 256)
1589       IID = Intrinsic::x86_avx2_pmadd_wd;
1590     else if (VecWidth == 512)
1591       IID = Intrinsic::x86_avx512_pmaddw_d_512;
1592     else
1593       llvm_unreachable("Unexpected intrinsic");
1594   } else if (Name.startswith("pmaddubs.w.")) {
1595     if (VecWidth == 128)
1596       IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1597     else if (VecWidth == 256)
1598       IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1599     else if (VecWidth == 512)
1600       IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1601     else
1602       llvm_unreachable("Unexpected intrinsic");
1603   } else if (Name.startswith("packsswb.")) {
1604     if (VecWidth == 128)
1605       IID = Intrinsic::x86_sse2_packsswb_128;
1606     else if (VecWidth == 256)
1607       IID = Intrinsic::x86_avx2_packsswb;
1608     else if (VecWidth == 512)
1609       IID = Intrinsic::x86_avx512_packsswb_512;
1610     else
1611       llvm_unreachable("Unexpected intrinsic");
1612   } else if (Name.startswith("packssdw.")) {
1613     if (VecWidth == 128)
1614       IID = Intrinsic::x86_sse2_packssdw_128;
1615     else if (VecWidth == 256)
1616       IID = Intrinsic::x86_avx2_packssdw;
1617     else if (VecWidth == 512)
1618       IID = Intrinsic::x86_avx512_packssdw_512;
1619     else
1620       llvm_unreachable("Unexpected intrinsic");
1621   } else if (Name.startswith("packuswb.")) {
1622     if (VecWidth == 128)
1623       IID = Intrinsic::x86_sse2_packuswb_128;
1624     else if (VecWidth == 256)
1625       IID = Intrinsic::x86_avx2_packuswb;
1626     else if (VecWidth == 512)
1627       IID = Intrinsic::x86_avx512_packuswb_512;
1628     else
1629       llvm_unreachable("Unexpected intrinsic");
1630   } else if (Name.startswith("packusdw.")) {
1631     if (VecWidth == 128)
1632       IID = Intrinsic::x86_sse41_packusdw;
1633     else if (VecWidth == 256)
1634       IID = Intrinsic::x86_avx2_packusdw;
1635     else if (VecWidth == 512)
1636       IID = Intrinsic::x86_avx512_packusdw_512;
1637     else
1638       llvm_unreachable("Unexpected intrinsic");
1639   } else if (Name.startswith("vpermilvar.")) {
1640     if (VecWidth == 128 && EltWidth == 32)
1641       IID = Intrinsic::x86_avx_vpermilvar_ps;
1642     else if (VecWidth == 128 && EltWidth == 64)
1643       IID = Intrinsic::x86_avx_vpermilvar_pd;
1644     else if (VecWidth == 256 && EltWidth == 32)
1645       IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1646     else if (VecWidth == 256 && EltWidth == 64)
1647       IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1648     else if (VecWidth == 512 && EltWidth == 32)
1649       IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1650     else if (VecWidth == 512 && EltWidth == 64)
1651       IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1652     else
1653       llvm_unreachable("Unexpected intrinsic");
1654   } else if (Name == "cvtpd2dq.256") {
1655     IID = Intrinsic::x86_avx_cvt_pd2dq_256;
1656   } else if (Name == "cvtpd2ps.256") {
1657     IID = Intrinsic::x86_avx_cvt_pd2_ps_256;
1658   } else if (Name == "cvttpd2dq.256") {
1659     IID = Intrinsic::x86_avx_cvtt_pd2dq_256;
1660   } else if (Name == "cvttps2dq.128") {
1661     IID = Intrinsic::x86_sse2_cvttps2dq;
1662   } else if (Name == "cvttps2dq.256") {
1663     IID = Intrinsic::x86_avx_cvtt_ps2dq_256;
1664   } else if (Name.startswith("permvar.")) {
1665     bool IsFloat = CI.getType()->isFPOrFPVectorTy();
1666     if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1667       IID = Intrinsic::x86_avx2_permps;
1668     else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1669       IID = Intrinsic::x86_avx2_permd;
1670     else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1671       IID = Intrinsic::x86_avx512_permvar_df_256;
1672     else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1673       IID = Intrinsic::x86_avx512_permvar_di_256;
1674     else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1675       IID = Intrinsic::x86_avx512_permvar_sf_512;
1676     else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1677       IID = Intrinsic::x86_avx512_permvar_si_512;
1678     else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1679       IID = Intrinsic::x86_avx512_permvar_df_512;
1680     else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1681       IID = Intrinsic::x86_avx512_permvar_di_512;
1682     else if (VecWidth == 128 && EltWidth == 16)
1683       IID = Intrinsic::x86_avx512_permvar_hi_128;
1684     else if (VecWidth == 256 && EltWidth == 16)
1685       IID = Intrinsic::x86_avx512_permvar_hi_256;
1686     else if (VecWidth == 512 && EltWidth == 16)
1687       IID = Intrinsic::x86_avx512_permvar_hi_512;
1688     else if (VecWidth == 128 && EltWidth == 8)
1689       IID = Intrinsic::x86_avx512_permvar_qi_128;
1690     else if (VecWidth == 256 && EltWidth == 8)
1691       IID = Intrinsic::x86_avx512_permvar_qi_256;
1692     else if (VecWidth == 512 && EltWidth == 8)
1693       IID = Intrinsic::x86_avx512_permvar_qi_512;
1694     else
1695       llvm_unreachable("Unexpected intrinsic");
1696   } else if (Name.startswith("dbpsadbw.")) {
1697     if (VecWidth == 128)
1698       IID = Intrinsic::x86_avx512_dbpsadbw_128;
1699     else if (VecWidth == 256)
1700       IID = Intrinsic::x86_avx512_dbpsadbw_256;
1701     else if (VecWidth == 512)
1702       IID = Intrinsic::x86_avx512_dbpsadbw_512;
1703     else
1704       llvm_unreachable("Unexpected intrinsic");
1705   } else if (Name.startswith("pmultishift.qb.")) {
1706     if (VecWidth == 128)
1707       IID = Intrinsic::x86_avx512_pmultishift_qb_128;
1708     else if (VecWidth == 256)
1709       IID = Intrinsic::x86_avx512_pmultishift_qb_256;
1710     else if (VecWidth == 512)
1711       IID = Intrinsic::x86_avx512_pmultishift_qb_512;
1712     else
1713       llvm_unreachable("Unexpected intrinsic");
1714   } else if (Name.startswith("conflict.")) {
1715     if (Name[9] == 'd' && VecWidth == 128)
1716       IID = Intrinsic::x86_avx512_conflict_d_128;
1717     else if (Name[9] == 'd' && VecWidth == 256)
1718       IID = Intrinsic::x86_avx512_conflict_d_256;
1719     else if (Name[9] == 'd' && VecWidth == 512)
1720       IID = Intrinsic::x86_avx512_conflict_d_512;
1721     else if (Name[9] == 'q' && VecWidth == 128)
1722       IID = Intrinsic::x86_avx512_conflict_q_128;
1723     else if (Name[9] == 'q' && VecWidth == 256)
1724       IID = Intrinsic::x86_avx512_conflict_q_256;
1725     else if (Name[9] == 'q' && VecWidth == 512)
1726       IID = Intrinsic::x86_avx512_conflict_q_512;
1727     else
1728       llvm_unreachable("Unexpected intrinsic");
1729   } else if (Name.startswith("pavg.")) {
1730     if (Name[5] == 'b' && VecWidth == 128)
1731       IID = Intrinsic::x86_sse2_pavg_b;
1732     else if (Name[5] == 'b' && VecWidth == 256)
1733       IID = Intrinsic::x86_avx2_pavg_b;
1734     else if (Name[5] == 'b' && VecWidth == 512)
1735       IID = Intrinsic::x86_avx512_pavg_b_512;
1736     else if (Name[5] == 'w' && VecWidth == 128)
1737       IID = Intrinsic::x86_sse2_pavg_w;
1738     else if (Name[5] == 'w' && VecWidth == 256)
1739       IID = Intrinsic::x86_avx2_pavg_w;
1740     else if (Name[5] == 'w' && VecWidth == 512)
1741       IID = Intrinsic::x86_avx512_pavg_w_512;
1742     else
1743       llvm_unreachable("Unexpected intrinsic");
1744   } else
1745     return false;
1746 
1747   SmallVector<Value *, 4> Args(CI.arg_operands().begin(),
1748                                CI.arg_operands().end());
1749   Args.pop_back();
1750   Args.pop_back();
1751   Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1752                            Args);
1753   unsigned NumArgs = CI.getNumArgOperands();
1754   Rep = EmitX86Select(Builder, CI.getArgOperand(NumArgs - 1), Rep,
1755                       CI.getArgOperand(NumArgs - 2));
1756   return true;
1757 }
1758 
1759 /// Upgrade comment in call to inline asm that represents an objc retain release
1760 /// marker.
1761 void llvm::UpgradeInlineAsmString(std::string *AsmStr) {
1762   size_t Pos;
1763   if (AsmStr->find("mov\tfp") == 0 &&
1764       AsmStr->find("objc_retainAutoreleaseReturnValue") != std::string::npos &&
1765       (Pos = AsmStr->find("# marker")) != std::string::npos) {
1766     AsmStr->replace(Pos, 1, ";");
1767   }
1768   return;
1769 }
1770 
1771 /// Upgrade a call to an old intrinsic. All argument and return casting must be
1772 /// provided to seamlessly integrate with existing context.
1773 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
1774   Function *F = CI->getCalledFunction();
1775   LLVMContext &C = CI->getContext();
1776   IRBuilder<> Builder(C);
1777   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
1778 
1779   assert(F && "Intrinsic call is not direct?");
1780 
1781   if (!NewFn) {
1782     // Get the Function's name.
1783     StringRef Name = F->getName();
1784 
1785     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
1786     Name = Name.substr(5);
1787 
1788     bool IsX86 = Name.startswith("x86.");
1789     if (IsX86)
1790       Name = Name.substr(4);
1791     bool IsNVVM = Name.startswith("nvvm.");
1792     if (IsNVVM)
1793       Name = Name.substr(5);
1794 
1795     if (IsX86 && Name.startswith("sse4a.movnt.")) {
1796       Module *M = F->getParent();
1797       SmallVector<Metadata *, 1> Elts;
1798       Elts.push_back(
1799           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1800       MDNode *Node = MDNode::get(C, Elts);
1801 
1802       Value *Arg0 = CI->getArgOperand(0);
1803       Value *Arg1 = CI->getArgOperand(1);
1804 
1805       // Nontemporal (unaligned) store of the 0'th element of the float/double
1806       // vector.
1807       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
1808       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
1809       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
1810       Value *Extract =
1811           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
1812 
1813       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, Align(1));
1814       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1815 
1816       // Remove intrinsic.
1817       CI->eraseFromParent();
1818       return;
1819     }
1820 
1821     if (IsX86 && (Name.startswith("avx.movnt.") ||
1822                   Name.startswith("avx512.storent."))) {
1823       Module *M = F->getParent();
1824       SmallVector<Metadata *, 1> Elts;
1825       Elts.push_back(
1826           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1827       MDNode *Node = MDNode::get(C, Elts);
1828 
1829       Value *Arg0 = CI->getArgOperand(0);
1830       Value *Arg1 = CI->getArgOperand(1);
1831 
1832       // Convert the type of the pointer to a pointer to the stored type.
1833       Value *BC = Builder.CreateBitCast(Arg0,
1834                                         PointerType::getUnqual(Arg1->getType()),
1835                                         "cast");
1836       StoreInst *SI = Builder.CreateAlignedStore(
1837           Arg1, BC,
1838           Align(Arg1->getType()->getPrimitiveSizeInBits().getFixedSize() / 8));
1839       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1840 
1841       // Remove intrinsic.
1842       CI->eraseFromParent();
1843       return;
1844     }
1845 
1846     if (IsX86 && Name == "sse2.storel.dq") {
1847       Value *Arg0 = CI->getArgOperand(0);
1848       Value *Arg1 = CI->getArgOperand(1);
1849 
1850       auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
1851       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1852       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
1853       Value *BC = Builder.CreateBitCast(Arg0,
1854                                         PointerType::getUnqual(Elt->getType()),
1855                                         "cast");
1856       Builder.CreateAlignedStore(Elt, BC, Align(1));
1857 
1858       // Remove intrinsic.
1859       CI->eraseFromParent();
1860       return;
1861     }
1862 
1863     if (IsX86 && (Name.startswith("sse.storeu.") ||
1864                   Name.startswith("sse2.storeu.") ||
1865                   Name.startswith("avx.storeu."))) {
1866       Value *Arg0 = CI->getArgOperand(0);
1867       Value *Arg1 = CI->getArgOperand(1);
1868 
1869       Arg0 = Builder.CreateBitCast(Arg0,
1870                                    PointerType::getUnqual(Arg1->getType()),
1871                                    "cast");
1872       Builder.CreateAlignedStore(Arg1, Arg0, Align(1));
1873 
1874       // Remove intrinsic.
1875       CI->eraseFromParent();
1876       return;
1877     }
1878 
1879     if (IsX86 && Name == "avx512.mask.store.ss") {
1880       Value *Mask = Builder.CreateAnd(CI->getArgOperand(2), Builder.getInt8(1));
1881       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1882                          Mask, false);
1883 
1884       // Remove intrinsic.
1885       CI->eraseFromParent();
1886       return;
1887     }
1888 
1889     if (IsX86 && (Name.startswith("avx512.mask.store"))) {
1890       // "avx512.mask.storeu." or "avx512.mask.store."
1891       bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
1892       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1893                          CI->getArgOperand(2), Aligned);
1894 
1895       // Remove intrinsic.
1896       CI->eraseFromParent();
1897       return;
1898     }
1899 
1900     Value *Rep;
1901     // Upgrade packed integer vector compare intrinsics to compare instructions.
1902     if (IsX86 && (Name.startswith("sse2.pcmp") ||
1903                   Name.startswith("avx2.pcmp"))) {
1904       // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
1905       bool CmpEq = Name[9] == 'e';
1906       Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
1907                                CI->getArgOperand(0), CI->getArgOperand(1));
1908       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
1909     } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
1910       Type *ExtTy = Type::getInt32Ty(C);
1911       if (CI->getOperand(0)->getType()->isIntegerTy(8))
1912         ExtTy = Type::getInt64Ty(C);
1913       unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
1914                          ExtTy->getPrimitiveSizeInBits();
1915       Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
1916       Rep = Builder.CreateVectorSplat(NumElts, Rep);
1917     } else if (IsX86 && (Name == "sse.sqrt.ss" ||
1918                          Name == "sse2.sqrt.sd")) {
1919       Value *Vec = CI->getArgOperand(0);
1920       Value *Elt0 = Builder.CreateExtractElement(Vec, (uint64_t)0);
1921       Function *Intr = Intrinsic::getDeclaration(F->getParent(),
1922                                                  Intrinsic::sqrt, Elt0->getType());
1923       Elt0 = Builder.CreateCall(Intr, Elt0);
1924       Rep = Builder.CreateInsertElement(Vec, Elt0, (uint64_t)0);
1925     } else if (IsX86 && (Name.startswith("avx.sqrt.p") ||
1926                          Name.startswith("sse2.sqrt.p") ||
1927                          Name.startswith("sse.sqrt.p"))) {
1928       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1929                                                          Intrinsic::sqrt,
1930                                                          CI->getType()),
1931                                {CI->getArgOperand(0)});
1932     } else if (IsX86 && (Name.startswith("avx512.mask.sqrt.p"))) {
1933       if (CI->getNumArgOperands() == 4 &&
1934           (!isa<ConstantInt>(CI->getArgOperand(3)) ||
1935            cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
1936         Intrinsic::ID IID = Name[18] == 's' ? Intrinsic::x86_avx512_sqrt_ps_512
1937                                             : Intrinsic::x86_avx512_sqrt_pd_512;
1938 
1939         Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(3) };
1940         Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
1941                                                            IID), Args);
1942       } else {
1943         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1944                                                            Intrinsic::sqrt,
1945                                                            CI->getType()),
1946                                  {CI->getArgOperand(0)});
1947       }
1948       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1949                           CI->getArgOperand(1));
1950     } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
1951                          Name.startswith("avx512.ptestnm"))) {
1952       Value *Op0 = CI->getArgOperand(0);
1953       Value *Op1 = CI->getArgOperand(1);
1954       Value *Mask = CI->getArgOperand(2);
1955       Rep = Builder.CreateAnd(Op0, Op1);
1956       llvm::Type *Ty = Op0->getType();
1957       Value *Zero = llvm::Constant::getNullValue(Ty);
1958       ICmpInst::Predicate Pred =
1959         Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1960       Rep = Builder.CreateICmp(Pred, Rep, Zero);
1961       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask);
1962     } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
1963       unsigned NumElts = cast<FixedVectorType>(CI->getArgOperand(1)->getType())
1964                              ->getNumElements();
1965       Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
1966       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1967                           CI->getArgOperand(1));
1968     } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
1969       unsigned NumElts = CI->getType()->getScalarSizeInBits();
1970       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
1971       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
1972       int Indices[64];
1973       for (unsigned i = 0; i != NumElts; ++i)
1974         Indices[i] = i;
1975 
1976       // First extract half of each vector. This gives better codegen than
1977       // doing it in a single shuffle.
1978       LHS = Builder.CreateShuffleVector(LHS, LHS,
1979                                         makeArrayRef(Indices, NumElts / 2));
1980       RHS = Builder.CreateShuffleVector(RHS, RHS,
1981                                         makeArrayRef(Indices, NumElts / 2));
1982       // Concat the vectors.
1983       // NOTE: Operands have to be swapped to match intrinsic definition.
1984       Rep = Builder.CreateShuffleVector(RHS, LHS,
1985                                         makeArrayRef(Indices, NumElts));
1986       Rep = Builder.CreateBitCast(Rep, CI->getType());
1987     } else if (IsX86 && Name == "avx512.kand.w") {
1988       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1989       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1990       Rep = Builder.CreateAnd(LHS, RHS);
1991       Rep = Builder.CreateBitCast(Rep, CI->getType());
1992     } else if (IsX86 && Name == "avx512.kandn.w") {
1993       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1994       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1995       LHS = Builder.CreateNot(LHS);
1996       Rep = Builder.CreateAnd(LHS, RHS);
1997       Rep = Builder.CreateBitCast(Rep, CI->getType());
1998     } else if (IsX86 && Name == "avx512.kor.w") {
1999       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2000       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2001       Rep = Builder.CreateOr(LHS, RHS);
2002       Rep = Builder.CreateBitCast(Rep, CI->getType());
2003     } else if (IsX86 && Name == "avx512.kxor.w") {
2004       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2005       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2006       Rep = Builder.CreateXor(LHS, RHS);
2007       Rep = Builder.CreateBitCast(Rep, CI->getType());
2008     } else if (IsX86 && Name == "avx512.kxnor.w") {
2009       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2010       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2011       LHS = Builder.CreateNot(LHS);
2012       Rep = Builder.CreateXor(LHS, RHS);
2013       Rep = Builder.CreateBitCast(Rep, CI->getType());
2014     } else if (IsX86 && Name == "avx512.knot.w") {
2015       Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2016       Rep = Builder.CreateNot(Rep);
2017       Rep = Builder.CreateBitCast(Rep, CI->getType());
2018     } else if (IsX86 &&
2019                (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
2020       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2021       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2022       Rep = Builder.CreateOr(LHS, RHS);
2023       Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
2024       Value *C;
2025       if (Name[14] == 'c')
2026         C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
2027       else
2028         C = ConstantInt::getNullValue(Builder.getInt16Ty());
2029       Rep = Builder.CreateICmpEQ(Rep, C);
2030       Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
2031     } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd" ||
2032                          Name == "sse.sub.ss" || Name == "sse2.sub.sd" ||
2033                          Name == "sse.mul.ss" || Name == "sse2.mul.sd" ||
2034                          Name == "sse.div.ss" || Name == "sse2.div.sd")) {
2035       Type *I32Ty = Type::getInt32Ty(C);
2036       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
2037                                                  ConstantInt::get(I32Ty, 0));
2038       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
2039                                                  ConstantInt::get(I32Ty, 0));
2040       Value *EltOp;
2041       if (Name.contains(".add."))
2042         EltOp = Builder.CreateFAdd(Elt0, Elt1);
2043       else if (Name.contains(".sub."))
2044         EltOp = Builder.CreateFSub(Elt0, Elt1);
2045       else if (Name.contains(".mul."))
2046         EltOp = Builder.CreateFMul(Elt0, Elt1);
2047       else
2048         EltOp = Builder.CreateFDiv(Elt0, Elt1);
2049       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), EltOp,
2050                                         ConstantInt::get(I32Ty, 0));
2051     } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
2052       // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
2053       bool CmpEq = Name[16] == 'e';
2054       Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
2055     } else if (IsX86 && Name.startswith("avx512.mask.vpshufbitqmb.")) {
2056       Type *OpTy = CI->getArgOperand(0)->getType();
2057       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2058       Intrinsic::ID IID;
2059       switch (VecWidth) {
2060       default: llvm_unreachable("Unexpected intrinsic");
2061       case 128: IID = Intrinsic::x86_avx512_vpshufbitqmb_128; break;
2062       case 256: IID = Intrinsic::x86_avx512_vpshufbitqmb_256; break;
2063       case 512: IID = Intrinsic::x86_avx512_vpshufbitqmb_512; break;
2064       }
2065 
2066       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2067                                { CI->getOperand(0), CI->getArgOperand(1) });
2068       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2069     } else if (IsX86 && Name.startswith("avx512.mask.fpclass.p")) {
2070       Type *OpTy = CI->getArgOperand(0)->getType();
2071       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2072       unsigned EltWidth = OpTy->getScalarSizeInBits();
2073       Intrinsic::ID IID;
2074       if (VecWidth == 128 && EltWidth == 32)
2075         IID = Intrinsic::x86_avx512_fpclass_ps_128;
2076       else if (VecWidth == 256 && EltWidth == 32)
2077         IID = Intrinsic::x86_avx512_fpclass_ps_256;
2078       else if (VecWidth == 512 && EltWidth == 32)
2079         IID = Intrinsic::x86_avx512_fpclass_ps_512;
2080       else if (VecWidth == 128 && EltWidth == 64)
2081         IID = Intrinsic::x86_avx512_fpclass_pd_128;
2082       else if (VecWidth == 256 && EltWidth == 64)
2083         IID = Intrinsic::x86_avx512_fpclass_pd_256;
2084       else if (VecWidth == 512 && EltWidth == 64)
2085         IID = Intrinsic::x86_avx512_fpclass_pd_512;
2086       else
2087         llvm_unreachable("Unexpected intrinsic");
2088 
2089       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2090                                { CI->getOperand(0), CI->getArgOperand(1) });
2091       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2092     } else if (IsX86 && Name.startswith("avx512.cmp.p")) {
2093       SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2094                                    CI->arg_operands().end());
2095       Type *OpTy = Args[0]->getType();
2096       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2097       unsigned EltWidth = OpTy->getScalarSizeInBits();
2098       Intrinsic::ID IID;
2099       if (VecWidth == 128 && EltWidth == 32)
2100         IID = Intrinsic::x86_avx512_mask_cmp_ps_128;
2101       else if (VecWidth == 256 && EltWidth == 32)
2102         IID = Intrinsic::x86_avx512_mask_cmp_ps_256;
2103       else if (VecWidth == 512 && EltWidth == 32)
2104         IID = Intrinsic::x86_avx512_mask_cmp_ps_512;
2105       else if (VecWidth == 128 && EltWidth == 64)
2106         IID = Intrinsic::x86_avx512_mask_cmp_pd_128;
2107       else if (VecWidth == 256 && EltWidth == 64)
2108         IID = Intrinsic::x86_avx512_mask_cmp_pd_256;
2109       else if (VecWidth == 512 && EltWidth == 64)
2110         IID = Intrinsic::x86_avx512_mask_cmp_pd_512;
2111       else
2112         llvm_unreachable("Unexpected intrinsic");
2113 
2114       Value *Mask = Constant::getAllOnesValue(CI->getType());
2115       if (VecWidth == 512)
2116         std::swap(Mask, Args.back());
2117       Args.push_back(Mask);
2118 
2119       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2120                                Args);
2121     } else if (IsX86 && Name.startswith("avx512.mask.cmp.")) {
2122       // Integer compare intrinsics.
2123       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2124       Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
2125     } else if (IsX86 && Name.startswith("avx512.mask.ucmp.")) {
2126       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2127       Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
2128     } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
2129                          Name.startswith("avx512.cvtw2mask.") ||
2130                          Name.startswith("avx512.cvtd2mask.") ||
2131                          Name.startswith("avx512.cvtq2mask."))) {
2132       Value *Op = CI->getArgOperand(0);
2133       Value *Zero = llvm::Constant::getNullValue(Op->getType());
2134       Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
2135       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr);
2136     } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
2137                         Name == "ssse3.pabs.w.128" ||
2138                         Name == "ssse3.pabs.d.128" ||
2139                         Name.startswith("avx2.pabs") ||
2140                         Name.startswith("avx512.mask.pabs"))) {
2141       Rep = upgradeAbs(Builder, *CI);
2142     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
2143                          Name == "sse2.pmaxs.w" ||
2144                          Name == "sse41.pmaxsd" ||
2145                          Name.startswith("avx2.pmaxs") ||
2146                          Name.startswith("avx512.mask.pmaxs"))) {
2147       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SGT);
2148     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
2149                          Name == "sse41.pmaxuw" ||
2150                          Name == "sse41.pmaxud" ||
2151                          Name.startswith("avx2.pmaxu") ||
2152                          Name.startswith("avx512.mask.pmaxu"))) {
2153       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_UGT);
2154     } else if (IsX86 && (Name == "sse41.pminsb" ||
2155                          Name == "sse2.pmins.w" ||
2156                          Name == "sse41.pminsd" ||
2157                          Name.startswith("avx2.pmins") ||
2158                          Name.startswith("avx512.mask.pmins"))) {
2159       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SLT);
2160     } else if (IsX86 && (Name == "sse2.pminu.b" ||
2161                          Name == "sse41.pminuw" ||
2162                          Name == "sse41.pminud" ||
2163                          Name.startswith("avx2.pminu") ||
2164                          Name.startswith("avx512.mask.pminu"))) {
2165       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_ULT);
2166     } else if (IsX86 && (Name == "sse2.pmulu.dq" ||
2167                          Name == "avx2.pmulu.dq" ||
2168                          Name == "avx512.pmulu.dq.512" ||
2169                          Name.startswith("avx512.mask.pmulu.dq."))) {
2170       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/false);
2171     } else if (IsX86 && (Name == "sse41.pmuldq" ||
2172                          Name == "avx2.pmul.dq" ||
2173                          Name == "avx512.pmul.dq.512" ||
2174                          Name.startswith("avx512.mask.pmul.dq."))) {
2175       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/true);
2176     } else if (IsX86 && (Name == "sse.cvtsi2ss" ||
2177                          Name == "sse2.cvtsi2sd" ||
2178                          Name == "sse.cvtsi642ss" ||
2179                          Name == "sse2.cvtsi642sd")) {
2180       Rep = Builder.CreateSIToFP(
2181           CI->getArgOperand(1),
2182           cast<VectorType>(CI->getType())->getElementType());
2183       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2184     } else if (IsX86 && Name == "avx512.cvtusi2sd") {
2185       Rep = Builder.CreateUIToFP(
2186           CI->getArgOperand(1),
2187           cast<VectorType>(CI->getType())->getElementType());
2188       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2189     } else if (IsX86 && Name == "sse2.cvtss2sd") {
2190       Rep = Builder.CreateExtractElement(CI->getArgOperand(1), (uint64_t)0);
2191       Rep = Builder.CreateFPExt(
2192           Rep, cast<VectorType>(CI->getType())->getElementType());
2193       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2194     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
2195                          Name == "sse2.cvtdq2ps" ||
2196                          Name == "avx.cvtdq2.pd.256" ||
2197                          Name == "avx.cvtdq2.ps.256" ||
2198                          Name.startswith("avx512.mask.cvtdq2pd.") ||
2199                          Name.startswith("avx512.mask.cvtudq2pd.") ||
2200                          Name.startswith("avx512.mask.cvtdq2ps.") ||
2201                          Name.startswith("avx512.mask.cvtudq2ps.") ||
2202                          Name.startswith("avx512.mask.cvtqq2pd.") ||
2203                          Name.startswith("avx512.mask.cvtuqq2pd.") ||
2204                          Name == "avx512.mask.cvtqq2ps.256" ||
2205                          Name == "avx512.mask.cvtqq2ps.512" ||
2206                          Name == "avx512.mask.cvtuqq2ps.256" ||
2207                          Name == "avx512.mask.cvtuqq2ps.512" ||
2208                          Name == "sse2.cvtps2pd" ||
2209                          Name == "avx.cvt.ps2.pd.256" ||
2210                          Name == "avx512.mask.cvtps2pd.128" ||
2211                          Name == "avx512.mask.cvtps2pd.256")) {
2212       auto *DstTy = cast<FixedVectorType>(CI->getType());
2213       Rep = CI->getArgOperand(0);
2214       auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2215 
2216       unsigned NumDstElts = DstTy->getNumElements();
2217       if (NumDstElts < SrcTy->getNumElements()) {
2218         assert(NumDstElts == 2 && "Unexpected vector size");
2219         Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1});
2220       }
2221 
2222       bool IsPS2PD = SrcTy->getElementType()->isFloatTy();
2223       bool IsUnsigned = (StringRef::npos != Name.find("cvtu"));
2224       if (IsPS2PD)
2225         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
2226       else if (CI->getNumArgOperands() == 4 &&
2227                (!isa<ConstantInt>(CI->getArgOperand(3)) ||
2228                 cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
2229         Intrinsic::ID IID = IsUnsigned ? Intrinsic::x86_avx512_uitofp_round
2230                                        : Intrinsic::x86_avx512_sitofp_round;
2231         Function *F = Intrinsic::getDeclaration(CI->getModule(), IID,
2232                                                 { DstTy, SrcTy });
2233         Rep = Builder.CreateCall(F, { Rep, CI->getArgOperand(3) });
2234       } else {
2235         Rep = IsUnsigned ? Builder.CreateUIToFP(Rep, DstTy, "cvt")
2236                          : Builder.CreateSIToFP(Rep, DstTy, "cvt");
2237       }
2238 
2239       if (CI->getNumArgOperands() >= 3)
2240         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2241                             CI->getArgOperand(1));
2242     } else if (IsX86 && (Name.startswith("avx512.mask.vcvtph2ps.") ||
2243                          Name.startswith("vcvtph2ps."))) {
2244       auto *DstTy = cast<FixedVectorType>(CI->getType());
2245       Rep = CI->getArgOperand(0);
2246       auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2247       unsigned NumDstElts = DstTy->getNumElements();
2248       if (NumDstElts != SrcTy->getNumElements()) {
2249         assert(NumDstElts == 4 && "Unexpected vector size");
2250         Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1, 2, 3});
2251       }
2252       Rep = Builder.CreateBitCast(
2253           Rep, FixedVectorType::get(Type::getHalfTy(C), NumDstElts));
2254       Rep = Builder.CreateFPExt(Rep, DstTy, "cvtph2ps");
2255       if (CI->getNumArgOperands() >= 3)
2256         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2257                             CI->getArgOperand(1));
2258     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
2259       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2260                               CI->getArgOperand(1), CI->getArgOperand(2),
2261                               /*Aligned*/false);
2262     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
2263       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2264                               CI->getArgOperand(1),CI->getArgOperand(2),
2265                               /*Aligned*/true);
2266     } else if (IsX86 && Name.startswith("avx512.mask.expand.load.")) {
2267       auto *ResultTy = cast<FixedVectorType>(CI->getType());
2268       Type *PtrTy = ResultTy->getElementType();
2269 
2270       // Cast the pointer to element type.
2271       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2272                                          llvm::PointerType::getUnqual(PtrTy));
2273 
2274       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2275                                      ResultTy->getNumElements());
2276 
2277       Function *ELd = Intrinsic::getDeclaration(F->getParent(),
2278                                                 Intrinsic::masked_expandload,
2279                                                 ResultTy);
2280       Rep = Builder.CreateCall(ELd, { Ptr, MaskVec, CI->getOperand(1) });
2281     } else if (IsX86 && Name.startswith("avx512.mask.compress.store.")) {
2282       auto *ResultTy = cast<VectorType>(CI->getArgOperand(1)->getType());
2283       Type *PtrTy = ResultTy->getElementType();
2284 
2285       // Cast the pointer to element type.
2286       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2287                                          llvm::PointerType::getUnqual(PtrTy));
2288 
2289       Value *MaskVec =
2290           getX86MaskVec(Builder, CI->getArgOperand(2),
2291                         cast<FixedVectorType>(ResultTy)->getNumElements());
2292 
2293       Function *CSt = Intrinsic::getDeclaration(F->getParent(),
2294                                                 Intrinsic::masked_compressstore,
2295                                                 ResultTy);
2296       Rep = Builder.CreateCall(CSt, { CI->getArgOperand(1), Ptr, MaskVec });
2297     } else if (IsX86 && (Name.startswith("avx512.mask.compress.") ||
2298                          Name.startswith("avx512.mask.expand."))) {
2299       auto *ResultTy = cast<FixedVectorType>(CI->getType());
2300 
2301       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2302                                      ResultTy->getNumElements());
2303 
2304       bool IsCompress = Name[12] == 'c';
2305       Intrinsic::ID IID = IsCompress ? Intrinsic::x86_avx512_mask_compress
2306                                      : Intrinsic::x86_avx512_mask_expand;
2307       Function *Intr = Intrinsic::getDeclaration(F->getParent(), IID, ResultTy);
2308       Rep = Builder.CreateCall(Intr, { CI->getOperand(0), CI->getOperand(1),
2309                                        MaskVec });
2310     } else if (IsX86 && Name.startswith("xop.vpcom")) {
2311       bool IsSigned;
2312       if (Name.endswith("ub") || Name.endswith("uw") || Name.endswith("ud") ||
2313           Name.endswith("uq"))
2314         IsSigned = false;
2315       else if (Name.endswith("b") || Name.endswith("w") || Name.endswith("d") ||
2316                Name.endswith("q"))
2317         IsSigned = true;
2318       else
2319         llvm_unreachable("Unknown suffix");
2320 
2321       unsigned Imm;
2322       if (CI->getNumArgOperands() == 3) {
2323         Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2324       } else {
2325         Name = Name.substr(9); // strip off "xop.vpcom"
2326         if (Name.startswith("lt"))
2327           Imm = 0;
2328         else if (Name.startswith("le"))
2329           Imm = 1;
2330         else if (Name.startswith("gt"))
2331           Imm = 2;
2332         else if (Name.startswith("ge"))
2333           Imm = 3;
2334         else if (Name.startswith("eq"))
2335           Imm = 4;
2336         else if (Name.startswith("ne"))
2337           Imm = 5;
2338         else if (Name.startswith("false"))
2339           Imm = 6;
2340         else if (Name.startswith("true"))
2341           Imm = 7;
2342         else
2343           llvm_unreachable("Unknown condition");
2344       }
2345 
2346       Rep = upgradeX86vpcom(Builder, *CI, Imm, IsSigned);
2347     } else if (IsX86 && Name.startswith("xop.vpcmov")) {
2348       Value *Sel = CI->getArgOperand(2);
2349       Value *NotSel = Builder.CreateNot(Sel);
2350       Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
2351       Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
2352       Rep = Builder.CreateOr(Sel0, Sel1);
2353     } else if (IsX86 && (Name.startswith("xop.vprot") ||
2354                          Name.startswith("avx512.prol") ||
2355                          Name.startswith("avx512.mask.prol"))) {
2356       Rep = upgradeX86Rotate(Builder, *CI, false);
2357     } else if (IsX86 && (Name.startswith("avx512.pror") ||
2358                          Name.startswith("avx512.mask.pror"))) {
2359       Rep = upgradeX86Rotate(Builder, *CI, true);
2360     } else if (IsX86 && (Name.startswith("avx512.vpshld.") ||
2361                          Name.startswith("avx512.mask.vpshld") ||
2362                          Name.startswith("avx512.maskz.vpshld"))) {
2363       bool ZeroMask = Name[11] == 'z';
2364       Rep = upgradeX86ConcatShift(Builder, *CI, false, ZeroMask);
2365     } else if (IsX86 && (Name.startswith("avx512.vpshrd.") ||
2366                          Name.startswith("avx512.mask.vpshrd") ||
2367                          Name.startswith("avx512.maskz.vpshrd"))) {
2368       bool ZeroMask = Name[11] == 'z';
2369       Rep = upgradeX86ConcatShift(Builder, *CI, true, ZeroMask);
2370     } else if (IsX86 && Name == "sse42.crc32.64.8") {
2371       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
2372                                                Intrinsic::x86_sse42_crc32_32_8);
2373       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
2374       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
2375       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
2376     } else if (IsX86 && (Name.startswith("avx.vbroadcast.s") ||
2377                          Name.startswith("avx512.vbroadcast.s"))) {
2378       // Replace broadcasts with a series of insertelements.
2379       auto *VecTy = cast<FixedVectorType>(CI->getType());
2380       Type *EltTy = VecTy->getElementType();
2381       unsigned EltNum = VecTy->getNumElements();
2382       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
2383                                           EltTy->getPointerTo());
2384       Value *Load = Builder.CreateLoad(EltTy, Cast);
2385       Type *I32Ty = Type::getInt32Ty(C);
2386       Rep = UndefValue::get(VecTy);
2387       for (unsigned I = 0; I < EltNum; ++I)
2388         Rep = Builder.CreateInsertElement(Rep, Load,
2389                                           ConstantInt::get(I32Ty, I));
2390     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
2391                          Name.startswith("sse41.pmovzx") ||
2392                          Name.startswith("avx2.pmovsx") ||
2393                          Name.startswith("avx2.pmovzx") ||
2394                          Name.startswith("avx512.mask.pmovsx") ||
2395                          Name.startswith("avx512.mask.pmovzx"))) {
2396       auto *SrcTy = cast<FixedVectorType>(CI->getArgOperand(0)->getType());
2397       auto *DstTy = cast<FixedVectorType>(CI->getType());
2398       unsigned NumDstElts = DstTy->getNumElements();
2399 
2400       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
2401       SmallVector<int, 8> ShuffleMask(NumDstElts);
2402       for (unsigned i = 0; i != NumDstElts; ++i)
2403         ShuffleMask[i] = i;
2404 
2405       Value *SV = Builder.CreateShuffleVector(
2406           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
2407 
2408       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
2409       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
2410                    : Builder.CreateZExt(SV, DstTy);
2411       // If there are 3 arguments, it's a masked intrinsic so we need a select.
2412       if (CI->getNumArgOperands() == 3)
2413         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2414                             CI->getArgOperand(1));
2415     } else if (Name == "avx512.mask.pmov.qd.256" ||
2416                Name == "avx512.mask.pmov.qd.512" ||
2417                Name == "avx512.mask.pmov.wb.256" ||
2418                Name == "avx512.mask.pmov.wb.512") {
2419       Type *Ty = CI->getArgOperand(1)->getType();
2420       Rep = Builder.CreateTrunc(CI->getArgOperand(0), Ty);
2421       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2422                           CI->getArgOperand(1));
2423     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
2424                          Name == "avx2.vbroadcasti128")) {
2425       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
2426       Type *EltTy = cast<VectorType>(CI->getType())->getElementType();
2427       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
2428       auto *VT = FixedVectorType::get(EltTy, NumSrcElts);
2429       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
2430                                             PointerType::getUnqual(VT));
2431       Value *Load = Builder.CreateAlignedLoad(VT, Op, Align(1));
2432       if (NumSrcElts == 2)
2433         Rep = Builder.CreateShuffleVector(
2434             Load, UndefValue::get(Load->getType()), ArrayRef<int>{0, 1, 0, 1});
2435       else
2436         Rep =
2437             Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
2438                                         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       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
2487                                         Constant::getNullValue(MaskTy));
2488 
2489       if (CI->getNumArgOperands() == 3)
2490         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2491                             CI->getArgOperand(1));
2492     } else if (IsX86 && (Name.startswith("sse2.padds.") ||
2493                          Name.startswith("sse2.psubs.") ||
2494                          Name.startswith("avx2.padds.") ||
2495                          Name.startswith("avx2.psubs.") ||
2496                          Name.startswith("avx512.padds.") ||
2497                          Name.startswith("avx512.psubs.") ||
2498                          Name.startswith("avx512.mask.padds.") ||
2499                          Name.startswith("avx512.mask.psubs."))) {
2500       bool IsAdd = Name.contains(".padds");
2501       Rep = UpgradeX86AddSubSatIntrinsics(Builder, *CI, true, IsAdd);
2502     } else if (IsX86 && (Name.startswith("sse2.paddus.") ||
2503                          Name.startswith("sse2.psubus.") ||
2504                          Name.startswith("avx2.paddus.") ||
2505                          Name.startswith("avx2.psubus.") ||
2506                          Name.startswith("avx512.mask.paddus.") ||
2507                          Name.startswith("avx512.mask.psubus."))) {
2508       bool IsAdd = Name.contains(".paddus");
2509       Rep = UpgradeX86AddSubSatIntrinsics(Builder, *CI, false, IsAdd);
2510     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
2511       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2512                                       CI->getArgOperand(1),
2513                                       CI->getArgOperand(2),
2514                                       CI->getArgOperand(3),
2515                                       CI->getArgOperand(4),
2516                                       false);
2517     } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
2518       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2519                                       CI->getArgOperand(1),
2520                                       CI->getArgOperand(2),
2521                                       CI->getArgOperand(3),
2522                                       CI->getArgOperand(4),
2523                                       true);
2524     } else if (IsX86 && (Name == "sse2.psll.dq" ||
2525                          Name == "avx2.psll.dq")) {
2526       // 128/256-bit shift left specified in bits.
2527       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2528       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
2529                                        Shift / 8); // Shift is in bits.
2530     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
2531                          Name == "avx2.psrl.dq")) {
2532       // 128/256-bit shift right specified in bits.
2533       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2534       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
2535                                        Shift / 8); // Shift is in bits.
2536     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
2537                          Name == "avx2.psll.dq.bs" ||
2538                          Name == "avx512.psll.dq.512")) {
2539       // 128/256/512-bit shift left specified in bytes.
2540       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2541       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2542     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
2543                          Name == "avx2.psrl.dq.bs" ||
2544                          Name == "avx512.psrl.dq.512")) {
2545       // 128/256/512-bit shift right specified in bytes.
2546       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2547       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2548     } else if (IsX86 && (Name == "sse41.pblendw" ||
2549                          Name.startswith("sse41.blendp") ||
2550                          Name.startswith("avx.blend.p") ||
2551                          Name == "avx2.pblendw" ||
2552                          Name.startswith("avx2.pblendd."))) {
2553       Value *Op0 = CI->getArgOperand(0);
2554       Value *Op1 = CI->getArgOperand(1);
2555       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2556       auto *VecTy = cast<FixedVectorType>(CI->getType());
2557       unsigned NumElts = VecTy->getNumElements();
2558 
2559       SmallVector<int, 16> Idxs(NumElts);
2560       for (unsigned i = 0; i != NumElts; ++i)
2561         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
2562 
2563       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2564     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
2565                          Name == "avx2.vinserti128" ||
2566                          Name.startswith("avx512.mask.insert"))) {
2567       Value *Op0 = CI->getArgOperand(0);
2568       Value *Op1 = CI->getArgOperand(1);
2569       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2570       unsigned DstNumElts =
2571           cast<FixedVectorType>(CI->getType())->getNumElements();
2572       unsigned SrcNumElts =
2573           cast<FixedVectorType>(Op1->getType())->getNumElements();
2574       unsigned Scale = DstNumElts / SrcNumElts;
2575 
2576       // Mask off the high bits of the immediate value; hardware ignores those.
2577       Imm = Imm % Scale;
2578 
2579       // Extend the second operand into a vector the size of the destination.
2580       Value *UndefV = UndefValue::get(Op1->getType());
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, UndefV, 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::experimental_vector_reduce_v2_fmul: {
3645     SmallVector<Value *, 2> Args;
3646     if (CI->isFast())
3647       Args.push_back(ConstantFP::get(CI->getOperand(0)->getType(), 1.0));
3648     else
3649       Args.push_back(CI->getOperand(0));
3650     Args.push_back(CI->getOperand(1));
3651     NewCall = Builder.CreateCall(NewFn, Args);
3652     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3653     break;
3654   }
3655   case Intrinsic::experimental_vector_reduce_v2_fadd: {
3656     SmallVector<Value *, 2> Args;
3657     if (CI->isFast())
3658       Args.push_back(Constant::getNullValue(CI->getOperand(0)->getType()));
3659     else
3660       Args.push_back(CI->getOperand(0));
3661     Args.push_back(CI->getOperand(1));
3662     NewCall = Builder.CreateCall(NewFn, Args);
3663     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3664     break;
3665   }
3666   case Intrinsic::arm_neon_vld1:
3667   case Intrinsic::arm_neon_vld2:
3668   case Intrinsic::arm_neon_vld3:
3669   case Intrinsic::arm_neon_vld4:
3670   case Intrinsic::arm_neon_vld2lane:
3671   case Intrinsic::arm_neon_vld3lane:
3672   case Intrinsic::arm_neon_vld4lane:
3673   case Intrinsic::arm_neon_vst1:
3674   case Intrinsic::arm_neon_vst2:
3675   case Intrinsic::arm_neon_vst3:
3676   case Intrinsic::arm_neon_vst4:
3677   case Intrinsic::arm_neon_vst2lane:
3678   case Intrinsic::arm_neon_vst3lane:
3679   case Intrinsic::arm_neon_vst4lane: {
3680     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3681                                  CI->arg_operands().end());
3682     NewCall = Builder.CreateCall(NewFn, Args);
3683     break;
3684   }
3685 
3686   case Intrinsic::arm_neon_bfdot:
3687   case Intrinsic::arm_neon_bfmmla:
3688   case Intrinsic::arm_neon_bfmlalb:
3689   case Intrinsic::arm_neon_bfmlalt:
3690   case Intrinsic::aarch64_neon_bfdot:
3691   case Intrinsic::aarch64_neon_bfmmla:
3692   case Intrinsic::aarch64_neon_bfmlalb:
3693   case Intrinsic::aarch64_neon_bfmlalt: {
3694     SmallVector<Value *, 3> Args;
3695     assert(CI->getNumArgOperands() == 3 &&
3696            "Mismatch between function args and call args");
3697     size_t OperandWidth =
3698         CI->getArgOperand(1)->getType()->getPrimitiveSizeInBits();
3699     assert((OperandWidth == 64 || OperandWidth == 128) &&
3700            "Unexpected operand width");
3701     Type *NewTy = FixedVectorType::get(Type::getBFloatTy(C), OperandWidth / 16);
3702     auto Iter = CI->arg_operands().begin();
3703     Args.push_back(*Iter++);
3704     Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
3705     Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
3706     NewCall = Builder.CreateCall(NewFn, Args);
3707     break;
3708   }
3709 
3710   case Intrinsic::bitreverse:
3711     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3712     break;
3713 
3714   case Intrinsic::ctlz:
3715   case Intrinsic::cttz:
3716     assert(CI->getNumArgOperands() == 1 &&
3717            "Mismatch between function args and call args");
3718     NewCall =
3719         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
3720     break;
3721 
3722   case Intrinsic::objectsize: {
3723     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
3724                                    ? Builder.getFalse()
3725                                    : CI->getArgOperand(2);
3726     Value *Dynamic =
3727         CI->getNumArgOperands() < 4 ? Builder.getFalse() : CI->getArgOperand(3);
3728     NewCall = Builder.CreateCall(
3729         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize, Dynamic});
3730     break;
3731   }
3732 
3733   case Intrinsic::ctpop:
3734     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3735     break;
3736 
3737   case Intrinsic::convert_from_fp16:
3738     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3739     break;
3740 
3741   case Intrinsic::dbg_value:
3742     // Upgrade from the old version that had an extra offset argument.
3743     assert(CI->getNumArgOperands() == 4);
3744     // Drop nonzero offsets instead of attempting to upgrade them.
3745     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
3746       if (Offset->isZeroValue()) {
3747         NewCall = Builder.CreateCall(
3748             NewFn,
3749             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
3750         break;
3751       }
3752     CI->eraseFromParent();
3753     return;
3754 
3755   case Intrinsic::x86_xop_vfrcz_ss:
3756   case Intrinsic::x86_xop_vfrcz_sd:
3757     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
3758     break;
3759 
3760   case Intrinsic::x86_xop_vpermil2pd:
3761   case Intrinsic::x86_xop_vpermil2ps:
3762   case Intrinsic::x86_xop_vpermil2pd_256:
3763   case Intrinsic::x86_xop_vpermil2ps_256: {
3764     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3765                                  CI->arg_operands().end());
3766     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
3767     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
3768     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
3769     NewCall = Builder.CreateCall(NewFn, Args);
3770     break;
3771   }
3772 
3773   case Intrinsic::x86_sse41_ptestc:
3774   case Intrinsic::x86_sse41_ptestz:
3775   case Intrinsic::x86_sse41_ptestnzc: {
3776     // The arguments for these intrinsics used to be v4f32, and changed
3777     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
3778     // So, the only thing required is a bitcast for both arguments.
3779     // First, check the arguments have the old type.
3780     Value *Arg0 = CI->getArgOperand(0);
3781     if (Arg0->getType() != FixedVectorType::get(Type::getFloatTy(C), 4))
3782       return;
3783 
3784     // Old intrinsic, add bitcasts
3785     Value *Arg1 = CI->getArgOperand(1);
3786 
3787     auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
3788 
3789     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
3790     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
3791 
3792     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
3793     break;
3794   }
3795 
3796   case Intrinsic::x86_rdtscp: {
3797     // This used to take 1 arguments. If we have no arguments, it is already
3798     // upgraded.
3799     if (CI->getNumOperands() == 0)
3800       return;
3801 
3802     NewCall = Builder.CreateCall(NewFn);
3803     // Extract the second result and store it.
3804     Value *Data = Builder.CreateExtractValue(NewCall, 1);
3805     // Cast the pointer to the right type.
3806     Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(0),
3807                                  llvm::PointerType::getUnqual(Data->getType()));
3808     Builder.CreateAlignedStore(Data, Ptr, Align(1));
3809     // Replace the original call result with the first result of the new call.
3810     Value *TSC = Builder.CreateExtractValue(NewCall, 0);
3811 
3812     NewCall->takeName(CI);
3813     CI->replaceAllUsesWith(TSC);
3814     CI->eraseFromParent();
3815     return;
3816   }
3817 
3818   case Intrinsic::x86_sse41_insertps:
3819   case Intrinsic::x86_sse41_dppd:
3820   case Intrinsic::x86_sse41_dpps:
3821   case Intrinsic::x86_sse41_mpsadbw:
3822   case Intrinsic::x86_avx_dp_ps_256:
3823   case Intrinsic::x86_avx2_mpsadbw: {
3824     // Need to truncate the last argument from i32 to i8 -- this argument models
3825     // an inherently 8-bit immediate operand to these x86 instructions.
3826     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3827                                  CI->arg_operands().end());
3828 
3829     // Replace the last argument with a trunc.
3830     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
3831     NewCall = Builder.CreateCall(NewFn, Args);
3832     break;
3833   }
3834 
3835   case Intrinsic::x86_avx512_mask_cmp_pd_128:
3836   case Intrinsic::x86_avx512_mask_cmp_pd_256:
3837   case Intrinsic::x86_avx512_mask_cmp_pd_512:
3838   case Intrinsic::x86_avx512_mask_cmp_ps_128:
3839   case Intrinsic::x86_avx512_mask_cmp_ps_256:
3840   case Intrinsic::x86_avx512_mask_cmp_ps_512: {
3841     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3842                                  CI->arg_operands().end());
3843     unsigned NumElts =
3844         cast<FixedVectorType>(Args[0]->getType())->getNumElements();
3845     Args[3] = getX86MaskVec(Builder, Args[3], NumElts);
3846 
3847     NewCall = Builder.CreateCall(NewFn, Args);
3848     Value *Res = ApplyX86MaskOn1BitsVec(Builder, NewCall, nullptr);
3849 
3850     NewCall->takeName(CI);
3851     CI->replaceAllUsesWith(Res);
3852     CI->eraseFromParent();
3853     return;
3854   }
3855 
3856   case Intrinsic::thread_pointer: {
3857     NewCall = Builder.CreateCall(NewFn, {});
3858     break;
3859   }
3860 
3861   case Intrinsic::invariant_start:
3862   case Intrinsic::invariant_end:
3863   case Intrinsic::masked_load:
3864   case Intrinsic::masked_store:
3865   case Intrinsic::masked_gather:
3866   case Intrinsic::masked_scatter: {
3867     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3868                                  CI->arg_operands().end());
3869     NewCall = Builder.CreateCall(NewFn, Args);
3870     break;
3871   }
3872 
3873   case Intrinsic::memcpy:
3874   case Intrinsic::memmove:
3875   case Intrinsic::memset: {
3876     // We have to make sure that the call signature is what we're expecting.
3877     // We only want to change the old signatures by removing the alignment arg:
3878     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
3879     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
3880     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
3881     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
3882     // Note: i8*'s in the above can be any pointer type
3883     if (CI->getNumArgOperands() != 5) {
3884       DefaultCase();
3885       return;
3886     }
3887     // Remove alignment argument (3), and add alignment attributes to the
3888     // dest/src pointers.
3889     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
3890                       CI->getArgOperand(2), CI->getArgOperand(4)};
3891     NewCall = Builder.CreateCall(NewFn, Args);
3892     auto *MemCI = cast<MemIntrinsic>(NewCall);
3893     // All mem intrinsics support dest alignment.
3894     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
3895     MemCI->setDestAlignment(Align->getMaybeAlignValue());
3896     // Memcpy/Memmove also support source alignment.
3897     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
3898       MTI->setSourceAlignment(Align->getMaybeAlignValue());
3899     break;
3900   }
3901   }
3902   assert(NewCall && "Should have either set this variable or returned through "
3903                     "the default case");
3904   NewCall->takeName(CI);
3905   CI->replaceAllUsesWith(NewCall);
3906   CI->eraseFromParent();
3907 }
3908 
3909 void llvm::UpgradeCallsToIntrinsic(Function *F) {
3910   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
3911 
3912   // Check if this function should be upgraded and get the replacement function
3913   // if there is one.
3914   Function *NewFn;
3915   if (UpgradeIntrinsicFunction(F, NewFn)) {
3916     // Replace all users of the old function with the new function or new
3917     // instructions. This is not a range loop because the call is deleted.
3918     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
3919       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
3920         UpgradeIntrinsicCall(CI, NewFn);
3921 
3922     // Remove old function, no longer used, from the module.
3923     F->eraseFromParent();
3924   }
3925 }
3926 
3927 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
3928   // Check if the tag uses struct-path aware TBAA format.
3929   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
3930     return &MD;
3931 
3932   auto &Context = MD.getContext();
3933   if (MD.getNumOperands() == 3) {
3934     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
3935     MDNode *ScalarType = MDNode::get(Context, Elts);
3936     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
3937     Metadata *Elts2[] = {ScalarType, ScalarType,
3938                          ConstantAsMetadata::get(
3939                              Constant::getNullValue(Type::getInt64Ty(Context))),
3940                          MD.getOperand(2)};
3941     return MDNode::get(Context, Elts2);
3942   }
3943   // Create a MDNode <MD, MD, offset 0>
3944   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
3945                                     Type::getInt64Ty(Context)))};
3946   return MDNode::get(Context, Elts);
3947 }
3948 
3949 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
3950                                       Instruction *&Temp) {
3951   if (Opc != Instruction::BitCast)
3952     return nullptr;
3953 
3954   Temp = nullptr;
3955   Type *SrcTy = V->getType();
3956   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3957       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3958     LLVMContext &Context = V->getContext();
3959 
3960     // We have no information about target data layout, so we assume that
3961     // the maximum pointer size is 64bit.
3962     Type *MidTy = Type::getInt64Ty(Context);
3963     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
3964 
3965     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
3966   }
3967 
3968   return nullptr;
3969 }
3970 
3971 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
3972   if (Opc != Instruction::BitCast)
3973     return nullptr;
3974 
3975   Type *SrcTy = C->getType();
3976   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3977       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3978     LLVMContext &Context = C->getContext();
3979 
3980     // We have no information about target data layout, so we assume that
3981     // the maximum pointer size is 64bit.
3982     Type *MidTy = Type::getInt64Ty(Context);
3983 
3984     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
3985                                      DestTy);
3986   }
3987 
3988   return nullptr;
3989 }
3990 
3991 /// Check the debug info version number, if it is out-dated, drop the debug
3992 /// info. Return true if module is modified.
3993 bool llvm::UpgradeDebugInfo(Module &M) {
3994   unsigned Version = getDebugMetadataVersionFromModule(M);
3995   if (Version == DEBUG_METADATA_VERSION) {
3996     bool BrokenDebugInfo = false;
3997     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
3998       report_fatal_error("Broken module found, compilation aborted!");
3999     if (!BrokenDebugInfo)
4000       // Everything is ok.
4001       return false;
4002     else {
4003       // Diagnose malformed debug info.
4004       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
4005       M.getContext().diagnose(Diag);
4006     }
4007   }
4008   bool Modified = StripDebugInfo(M);
4009   if (Modified && Version != DEBUG_METADATA_VERSION) {
4010     // Diagnose a version mismatch.
4011     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
4012     M.getContext().diagnose(DiagVersion);
4013   }
4014   return Modified;
4015 }
4016 
4017 /// This checks for objc retain release marker which should be upgraded. It
4018 /// returns true if module is modified.
4019 static bool UpgradeRetainReleaseMarker(Module &M) {
4020   bool Changed = false;
4021   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
4022   NamedMDNode *ModRetainReleaseMarker = M.getNamedMetadata(MarkerKey);
4023   if (ModRetainReleaseMarker) {
4024     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
4025     if (Op) {
4026       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
4027       if (ID) {
4028         SmallVector<StringRef, 4> ValueComp;
4029         ID->getString().split(ValueComp, "#");
4030         if (ValueComp.size() == 2) {
4031           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
4032           ID = MDString::get(M.getContext(), NewValue);
4033         }
4034         M.addModuleFlag(Module::Error, MarkerKey, ID);
4035         M.eraseNamedMetadata(ModRetainReleaseMarker);
4036         Changed = true;
4037       }
4038     }
4039   }
4040   return Changed;
4041 }
4042 
4043 void llvm::UpgradeARCRuntime(Module &M) {
4044   // This lambda converts normal function calls to ARC runtime functions to
4045   // intrinsic calls.
4046   auto UpgradeToIntrinsic = [&](const char *OldFunc,
4047                                 llvm::Intrinsic::ID IntrinsicFunc) {
4048     Function *Fn = M.getFunction(OldFunc);
4049 
4050     if (!Fn)
4051       return;
4052 
4053     Function *NewFn = llvm::Intrinsic::getDeclaration(&M, IntrinsicFunc);
4054 
4055     for (auto I = Fn->user_begin(), E = Fn->user_end(); I != E;) {
4056       CallInst *CI = dyn_cast<CallInst>(*I++);
4057       if (!CI || CI->getCalledFunction() != Fn)
4058         continue;
4059 
4060       IRBuilder<> Builder(CI->getParent(), CI->getIterator());
4061       FunctionType *NewFuncTy = NewFn->getFunctionType();
4062       SmallVector<Value *, 2> Args;
4063 
4064       // Don't upgrade the intrinsic if it's not valid to bitcast the return
4065       // value to the return type of the old function.
4066       if (NewFuncTy->getReturnType() != CI->getType() &&
4067           !CastInst::castIsValid(Instruction::BitCast, CI,
4068                                  NewFuncTy->getReturnType()))
4069         continue;
4070 
4071       bool InvalidCast = false;
4072 
4073       for (unsigned I = 0, E = CI->getNumArgOperands(); I != E; ++I) {
4074         Value *Arg = CI->getArgOperand(I);
4075 
4076         // Bitcast argument to the parameter type of the new function if it's
4077         // not a variadic argument.
4078         if (I < NewFuncTy->getNumParams()) {
4079           // Don't upgrade the intrinsic if it's not valid to bitcast the argument
4080           // to the parameter type of the new function.
4081           if (!CastInst::castIsValid(Instruction::BitCast, Arg,
4082                                      NewFuncTy->getParamType(I))) {
4083             InvalidCast = true;
4084             break;
4085           }
4086           Arg = Builder.CreateBitCast(Arg, NewFuncTy->getParamType(I));
4087         }
4088         Args.push_back(Arg);
4089       }
4090 
4091       if (InvalidCast)
4092         continue;
4093 
4094       // Create a call instruction that calls the new function.
4095       CallInst *NewCall = Builder.CreateCall(NewFuncTy, NewFn, Args);
4096       NewCall->setTailCallKind(cast<CallInst>(CI)->getTailCallKind());
4097       NewCall->takeName(CI);
4098 
4099       // Bitcast the return value back to the type of the old call.
4100       Value *NewRetVal = Builder.CreateBitCast(NewCall, CI->getType());
4101 
4102       if (!CI->use_empty())
4103         CI->replaceAllUsesWith(NewRetVal);
4104       CI->eraseFromParent();
4105     }
4106 
4107     if (Fn->use_empty())
4108       Fn->eraseFromParent();
4109   };
4110 
4111   // Unconditionally convert a call to "clang.arc.use" to a call to
4112   // "llvm.objc.clang.arc.use".
4113   UpgradeToIntrinsic("clang.arc.use", llvm::Intrinsic::objc_clang_arc_use);
4114 
4115   // Upgrade the retain release marker. If there is no need to upgrade
4116   // the marker, that means either the module is already new enough to contain
4117   // new intrinsics or it is not ARC. There is no need to upgrade runtime call.
4118   if (!UpgradeRetainReleaseMarker(M))
4119     return;
4120 
4121   std::pair<const char *, llvm::Intrinsic::ID> RuntimeFuncs[] = {
4122       {"objc_autorelease", llvm::Intrinsic::objc_autorelease},
4123       {"objc_autoreleasePoolPop", llvm::Intrinsic::objc_autoreleasePoolPop},
4124       {"objc_autoreleasePoolPush", llvm::Intrinsic::objc_autoreleasePoolPush},
4125       {"objc_autoreleaseReturnValue",
4126        llvm::Intrinsic::objc_autoreleaseReturnValue},
4127       {"objc_copyWeak", llvm::Intrinsic::objc_copyWeak},
4128       {"objc_destroyWeak", llvm::Intrinsic::objc_destroyWeak},
4129       {"objc_initWeak", llvm::Intrinsic::objc_initWeak},
4130       {"objc_loadWeak", llvm::Intrinsic::objc_loadWeak},
4131       {"objc_loadWeakRetained", llvm::Intrinsic::objc_loadWeakRetained},
4132       {"objc_moveWeak", llvm::Intrinsic::objc_moveWeak},
4133       {"objc_release", llvm::Intrinsic::objc_release},
4134       {"objc_retain", llvm::Intrinsic::objc_retain},
4135       {"objc_retainAutorelease", llvm::Intrinsic::objc_retainAutorelease},
4136       {"objc_retainAutoreleaseReturnValue",
4137        llvm::Intrinsic::objc_retainAutoreleaseReturnValue},
4138       {"objc_retainAutoreleasedReturnValue",
4139        llvm::Intrinsic::objc_retainAutoreleasedReturnValue},
4140       {"objc_retainBlock", llvm::Intrinsic::objc_retainBlock},
4141       {"objc_storeStrong", llvm::Intrinsic::objc_storeStrong},
4142       {"objc_storeWeak", llvm::Intrinsic::objc_storeWeak},
4143       {"objc_unsafeClaimAutoreleasedReturnValue",
4144        llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue},
4145       {"objc_retainedObject", llvm::Intrinsic::objc_retainedObject},
4146       {"objc_unretainedObject", llvm::Intrinsic::objc_unretainedObject},
4147       {"objc_unretainedPointer", llvm::Intrinsic::objc_unretainedPointer},
4148       {"objc_retain_autorelease", llvm::Intrinsic::objc_retain_autorelease},
4149       {"objc_sync_enter", llvm::Intrinsic::objc_sync_enter},
4150       {"objc_sync_exit", llvm::Intrinsic::objc_sync_exit},
4151       {"objc_arc_annotation_topdown_bbstart",
4152        llvm::Intrinsic::objc_arc_annotation_topdown_bbstart},
4153       {"objc_arc_annotation_topdown_bbend",
4154        llvm::Intrinsic::objc_arc_annotation_topdown_bbend},
4155       {"objc_arc_annotation_bottomup_bbstart",
4156        llvm::Intrinsic::objc_arc_annotation_bottomup_bbstart},
4157       {"objc_arc_annotation_bottomup_bbend",
4158        llvm::Intrinsic::objc_arc_annotation_bottomup_bbend}};
4159 
4160   for (auto &I : RuntimeFuncs)
4161     UpgradeToIntrinsic(I.first, I.second);
4162 }
4163 
4164 bool llvm::UpgradeModuleFlags(Module &M) {
4165   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
4166   if (!ModFlags)
4167     return false;
4168 
4169   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
4170   bool HasSwiftVersionFlag = false;
4171   uint8_t SwiftMajorVersion, SwiftMinorVersion;
4172   uint32_t SwiftABIVersion;
4173   auto Int8Ty = Type::getInt8Ty(M.getContext());
4174   auto Int32Ty = Type::getInt32Ty(M.getContext());
4175 
4176   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
4177     MDNode *Op = ModFlags->getOperand(I);
4178     if (Op->getNumOperands() != 3)
4179       continue;
4180     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
4181     if (!ID)
4182       continue;
4183     if (ID->getString() == "Objective-C Image Info Version")
4184       HasObjCFlag = true;
4185     if (ID->getString() == "Objective-C Class Properties")
4186       HasClassProperties = true;
4187     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
4188     // field was Error and now they are Max.
4189     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
4190       if (auto *Behavior =
4191               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
4192         if (Behavior->getLimitedValue() == Module::Error) {
4193           Type *Int32Ty = Type::getInt32Ty(M.getContext());
4194           Metadata *Ops[3] = {
4195               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
4196               MDString::get(M.getContext(), ID->getString()),
4197               Op->getOperand(2)};
4198           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4199           Changed = true;
4200         }
4201       }
4202     }
4203     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
4204     // section name so that llvm-lto will not complain about mismatching
4205     // module flags that is functionally the same.
4206     if (ID->getString() == "Objective-C Image Info Section") {
4207       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
4208         SmallVector<StringRef, 4> ValueComp;
4209         Value->getString().split(ValueComp, " ");
4210         if (ValueComp.size() != 1) {
4211           std::string NewValue;
4212           for (auto &S : ValueComp)
4213             NewValue += S.str();
4214           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
4215                               MDString::get(M.getContext(), NewValue)};
4216           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4217           Changed = true;
4218         }
4219       }
4220     }
4221 
4222     // IRUpgrader turns a i32 type "Objective-C Garbage Collection" into i8 value.
4223     // If the higher bits are set, it adds new module flag for swift info.
4224     if (ID->getString() == "Objective-C Garbage Collection") {
4225       auto Md = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
4226       if (Md) {
4227         assert(Md->getValue() && "Expected non-empty metadata");
4228         auto Type = Md->getValue()->getType();
4229         if (Type == Int8Ty)
4230           continue;
4231         unsigned Val = Md->getValue()->getUniqueInteger().getZExtValue();
4232         if ((Val & 0xff) != Val) {
4233           HasSwiftVersionFlag = true;
4234           SwiftABIVersion = (Val & 0xff00) >> 8;
4235           SwiftMajorVersion = (Val & 0xff000000) >> 24;
4236           SwiftMinorVersion = (Val & 0xff0000) >> 16;
4237         }
4238         Metadata *Ops[3] = {
4239           ConstantAsMetadata::get(ConstantInt::get(Int32Ty,Module::Error)),
4240           Op->getOperand(1),
4241           ConstantAsMetadata::get(ConstantInt::get(Int8Ty,Val & 0xff))};
4242         ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4243         Changed = true;
4244       }
4245     }
4246   }
4247 
4248   // "Objective-C Class Properties" is recently added for Objective-C. We
4249   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
4250   // flag of value 0, so we can correclty downgrade this flag when trying to
4251   // link an ObjC bitcode without this module flag with an ObjC bitcode with
4252   // this module flag.
4253   if (HasObjCFlag && !HasClassProperties) {
4254     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
4255                     (uint32_t)0);
4256     Changed = true;
4257   }
4258 
4259   if (HasSwiftVersionFlag) {
4260     M.addModuleFlag(Module::Error, "Swift ABI Version",
4261                     SwiftABIVersion);
4262     M.addModuleFlag(Module::Error, "Swift Major Version",
4263                     ConstantInt::get(Int8Ty, SwiftMajorVersion));
4264     M.addModuleFlag(Module::Error, "Swift Minor Version",
4265                     ConstantInt::get(Int8Ty, SwiftMinorVersion));
4266     Changed = true;
4267   }
4268 
4269   return Changed;
4270 }
4271 
4272 void llvm::UpgradeSectionAttributes(Module &M) {
4273   auto TrimSpaces = [](StringRef Section) -> std::string {
4274     SmallVector<StringRef, 5> Components;
4275     Section.split(Components, ',');
4276 
4277     SmallString<32> Buffer;
4278     raw_svector_ostream OS(Buffer);
4279 
4280     for (auto Component : Components)
4281       OS << ',' << Component.trim();
4282 
4283     return std::string(OS.str().substr(1));
4284   };
4285 
4286   for (auto &GV : M.globals()) {
4287     if (!GV.hasSection())
4288       continue;
4289 
4290     StringRef Section = GV.getSection();
4291 
4292     if (!Section.startswith("__DATA, __objc_catlist"))
4293       continue;
4294 
4295     // __DATA, __objc_catlist, regular, no_dead_strip
4296     // __DATA,__objc_catlist,regular,no_dead_strip
4297     GV.setSection(TrimSpaces(Section));
4298   }
4299 }
4300 
4301 namespace {
4302 // Prior to LLVM 10.0, the strictfp attribute could be used on individual
4303 // callsites within a function that did not also have the strictfp attribute.
4304 // Since 10.0, if strict FP semantics are needed within a function, the
4305 // function must have the strictfp attribute and all calls within the function
4306 // must also have the strictfp attribute. This latter restriction is
4307 // necessary to prevent unwanted libcall simplification when a function is
4308 // being cloned (such as for inlining).
4309 //
4310 // The "dangling" strictfp attribute usage was only used to prevent constant
4311 // folding and other libcall simplification. The nobuiltin attribute on the
4312 // callsite has the same effect.
4313 struct StrictFPUpgradeVisitor : public InstVisitor<StrictFPUpgradeVisitor> {
4314   StrictFPUpgradeVisitor() {}
4315 
4316   void visitCallBase(CallBase &Call) {
4317     if (!Call.isStrictFP())
4318       return;
4319     if (isa<ConstrainedFPIntrinsic>(&Call))
4320       return;
4321     // If we get here, the caller doesn't have the strictfp attribute
4322     // but this callsite does. Replace the strictfp attribute with nobuiltin.
4323     Call.removeAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
4324     Call.addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
4325   }
4326 };
4327 } // namespace
4328 
4329 void llvm::UpgradeFunctionAttributes(Function &F) {
4330   // If a function definition doesn't have the strictfp attribute,
4331   // convert any callsite strictfp attributes to nobuiltin.
4332   if (!F.isDeclaration() && !F.hasFnAttribute(Attribute::StrictFP)) {
4333     StrictFPUpgradeVisitor SFPV;
4334     SFPV.visit(F);
4335   }
4336 }
4337 
4338 static bool isOldLoopArgument(Metadata *MD) {
4339   auto *T = dyn_cast_or_null<MDTuple>(MD);
4340   if (!T)
4341     return false;
4342   if (T->getNumOperands() < 1)
4343     return false;
4344   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
4345   if (!S)
4346     return false;
4347   return S->getString().startswith("llvm.vectorizer.");
4348 }
4349 
4350 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
4351   StringRef OldPrefix = "llvm.vectorizer.";
4352   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
4353 
4354   if (OldTag == "llvm.vectorizer.unroll")
4355     return MDString::get(C, "llvm.loop.interleave.count");
4356 
4357   return MDString::get(
4358       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
4359              .str());
4360 }
4361 
4362 static Metadata *upgradeLoopArgument(Metadata *MD) {
4363   auto *T = dyn_cast_or_null<MDTuple>(MD);
4364   if (!T)
4365     return MD;
4366   if (T->getNumOperands() < 1)
4367     return MD;
4368   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
4369   if (!OldTag)
4370     return MD;
4371   if (!OldTag->getString().startswith("llvm.vectorizer."))
4372     return MD;
4373 
4374   // This has an old tag.  Upgrade it.
4375   SmallVector<Metadata *, 8> Ops;
4376   Ops.reserve(T->getNumOperands());
4377   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
4378   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
4379     Ops.push_back(T->getOperand(I));
4380 
4381   return MDTuple::get(T->getContext(), Ops);
4382 }
4383 
4384 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
4385   auto *T = dyn_cast<MDTuple>(&N);
4386   if (!T)
4387     return &N;
4388 
4389   if (none_of(T->operands(), isOldLoopArgument))
4390     return &N;
4391 
4392   SmallVector<Metadata *, 8> Ops;
4393   Ops.reserve(T->getNumOperands());
4394   for (Metadata *MD : T->operands())
4395     Ops.push_back(upgradeLoopArgument(MD));
4396 
4397   return MDTuple::get(T->getContext(), Ops);
4398 }
4399 
4400 std::string llvm::UpgradeDataLayoutString(StringRef DL, StringRef TT) {
4401   StringRef AddrSpaces = "-p270:32:32-p271:32:32-p272:64:64";
4402 
4403   // If X86, and the datalayout matches the expected format, add pointer size
4404   // address spaces to the datalayout.
4405   if (!Triple(TT).isX86() || DL.contains(AddrSpaces))
4406     return std::string(DL);
4407 
4408   SmallVector<StringRef, 4> Groups;
4409   Regex R("(e-m:[a-z](-p:32:32)?)(-[if]64:.*$)");
4410   if (!R.match(DL, &Groups))
4411     return std::string(DL);
4412 
4413   return (Groups[1] + AddrSpaces + Groups[3]).str();
4414 }
4415 
4416 void llvm::UpgradeAttributes(AttrBuilder &B) {
4417   StringRef FramePointer;
4418   if (B.contains("no-frame-pointer-elim")) {
4419     // The value can be "true" or "false".
4420     for (const auto &I : B.td_attrs())
4421       if (I.first == "no-frame-pointer-elim")
4422         FramePointer = I.second == "true" ? "all" : "none";
4423     B.removeAttribute("no-frame-pointer-elim");
4424   }
4425   if (B.contains("no-frame-pointer-elim-non-leaf")) {
4426     // The value is ignored. "no-frame-pointer-elim"="true" takes priority.
4427     if (FramePointer != "all")
4428       FramePointer = "non-leaf";
4429     B.removeAttribute("no-frame-pointer-elim-non-leaf");
4430   }
4431   if (!FramePointer.empty())
4432     B.addAttribute("frame-pointer", FramePointer);
4433 
4434   if (B.contains("null-pointer-is-valid")) {
4435     // The value can be "true" or "false".
4436     bool NullPointerIsValid = false;
4437     for (const auto &I : B.td_attrs())
4438       if (I.first == "null-pointer-is-valid")
4439         NullPointerIsValid = I.second == "true";
4440     B.removeAttribute("null-pointer-is-valid");
4441     if (NullPointerIsValid)
4442       B.addAttribute(Attribute::NullPointerIsValid);
4443   }
4444 }
4445