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