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