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