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