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