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