1 //===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements methods that make it really easy to deal with intrinsic
10 // functions.
11 //
12 // All intrinsic function calls are instances of the call instruction, so these
13 // are all subclasses of the CallInst class.  Note that none of these classes
14 // has state or virtual methods, which is an important part of this gross/neat
15 // hack working.
16 //
17 // In some cases, arguments to intrinsics need to be generic and are defined as
18 // type pointer to empty struct { }*.  To access the real item of interest the
19 // cast instruction needs to be stripped away.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/Statepoint.h"
33 
34 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm;
36 
37 //===----------------------------------------------------------------------===//
38 /// DbgVariableIntrinsic - This is the common base class for debug info
39 /// intrinsics for variables.
40 ///
41 
42 iterator_range<DbgVariableIntrinsic::location_op_iterator>
43 DbgVariableIntrinsic::location_ops() const {
44   auto *MD = getRawLocation();
45   assert(MD && "First operand of DbgVariableIntrinsic should be non-null.");
46 
47   // If operand is ValueAsMetadata, return a range over just that operand.
48   if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
49     return {location_op_iterator(VAM), location_op_iterator(VAM + 1)};
50   }
51   // If operand is DIArgList, return a range over its args.
52   if (auto *AL = dyn_cast<DIArgList>(MD))
53     return {location_op_iterator(AL->args_begin()),
54             location_op_iterator(AL->args_end())};
55   // Operand must be an empty metadata tuple, so return empty iterator.
56   return {location_op_iterator(static_cast<ValueAsMetadata *>(nullptr)),
57           location_op_iterator(static_cast<ValueAsMetadata *>(nullptr))};
58 }
59 
60 Value *DbgVariableIntrinsic::getVariableLocationOp(unsigned OpIdx) const {
61   auto *MD = getRawLocation();
62   assert(MD && "First operand of DbgVariableIntrinsic should be non-null.");
63   if (auto *AL = dyn_cast<DIArgList>(MD))
64     return AL->getArgs()[OpIdx]->getValue();
65   if (isa<MDNode>(MD))
66     return nullptr;
67   assert(
68       isa<ValueAsMetadata>(MD) &&
69       "Attempted to get location operand from DbgVariableIntrinsic with none.");
70   auto *V = cast<ValueAsMetadata>(MD);
71   assert(OpIdx == 0 && "Operand Index must be 0 for a debug intrinsic with a "
72                        "single location operand.");
73   return V->getValue();
74 }
75 
76 static ValueAsMetadata *getAsMetadata(Value *V) {
77   return isa<MetadataAsValue>(V) ? dyn_cast<ValueAsMetadata>(
78                                        cast<MetadataAsValue>(V)->getMetadata())
79                                  : ValueAsMetadata::get(V);
80 }
81 
82 void DbgVariableIntrinsic::replaceVariableLocationOp(Value *OldValue,
83                                                      Value *NewValue) {
84   assert(NewValue && "Values must be non-null");
85   auto Locations = location_ops();
86   auto OldIt = find(Locations, OldValue);
87   assert(OldIt != Locations.end() && "OldValue must be a current location");
88   if (!hasArgList()) {
89     Value *NewOperand = isa<MetadataAsValue>(NewValue)
90                             ? NewValue
91                             : MetadataAsValue::get(
92                                   getContext(), ValueAsMetadata::get(NewValue));
93     return setArgOperand(0, NewOperand);
94   }
95   SmallVector<ValueAsMetadata *, 4> MDs;
96   ValueAsMetadata *NewOperand = getAsMetadata(NewValue);
97   for (auto *VMD : Locations)
98     MDs.push_back(VMD == *OldIt ? NewOperand : getAsMetadata(VMD));
99   setArgOperand(
100       0, MetadataAsValue::get(getContext(), DIArgList::get(getContext(), MDs)));
101 }
102 void DbgVariableIntrinsic::replaceVariableLocationOp(unsigned OpIdx,
103                                                      Value *NewValue) {
104   assert(OpIdx < getNumVariableLocationOps() && "Invalid Operand Index");
105   if (!hasArgList()) {
106     Value *NewOperand = isa<MetadataAsValue>(NewValue)
107                             ? NewValue
108                             : MetadataAsValue::get(
109                                   getContext(), ValueAsMetadata::get(NewValue));
110     return setArgOperand(0, NewOperand);
111   }
112   SmallVector<ValueAsMetadata *, 4> MDs;
113   ValueAsMetadata *NewOperand = getAsMetadata(NewValue);
114   for (unsigned Idx = 0; Idx < getNumVariableLocationOps(); ++Idx)
115     MDs.push_back(Idx == OpIdx ? NewOperand
116                                : getAsMetadata(getVariableLocationOp(Idx)));
117   setArgOperand(
118       0, MetadataAsValue::get(getContext(), DIArgList::get(getContext(), MDs)));
119 }
120 
121 Optional<uint64_t> DbgVariableIntrinsic::getFragmentSizeInBits() const {
122   if (auto Fragment = getExpression()->getFragmentInfo())
123     return Fragment->SizeInBits;
124   return getVariable()->getSizeInBits();
125 }
126 
127 int llvm::Intrinsic::lookupLLVMIntrinsicByName(ArrayRef<const char *> NameTable,
128                                                StringRef Name) {
129   assert(Name.startswith("llvm."));
130 
131   // Do successive binary searches of the dotted name components. For
132   // "llvm.gc.experimental.statepoint.p1i8.p1i32", we will find the range of
133   // intrinsics starting with "llvm.gc", then "llvm.gc.experimental", then
134   // "llvm.gc.experimental.statepoint", and then we will stop as the range is
135   // size 1. During the search, we can skip the prefix that we already know is
136   // identical. By using strncmp we consider names with differing suffixes to
137   // be part of the equal range.
138   size_t CmpEnd = 4; // Skip the "llvm" component.
139   const char *const *Low = NameTable.begin();
140   const char *const *High = NameTable.end();
141   const char *const *LastLow = Low;
142   while (CmpEnd < Name.size() && High - Low > 0) {
143     size_t CmpStart = CmpEnd;
144     CmpEnd = Name.find('.', CmpStart + 1);
145     CmpEnd = CmpEnd == StringRef::npos ? Name.size() : CmpEnd;
146     auto Cmp = [CmpStart, CmpEnd](const char *LHS, const char *RHS) {
147       return strncmp(LHS + CmpStart, RHS + CmpStart, CmpEnd - CmpStart) < 0;
148     };
149     LastLow = Low;
150     std::tie(Low, High) = std::equal_range(Low, High, Name.data(), Cmp);
151   }
152   if (High - Low > 0)
153     LastLow = Low;
154 
155   if (LastLow == NameTable.end())
156     return -1;
157   StringRef NameFound = *LastLow;
158   if (Name == NameFound ||
159       (Name.startswith(NameFound) && Name[NameFound.size()] == '.'))
160     return LastLow - NameTable.begin();
161   return -1;
162 }
163 
164 Value *InstrProfIncrementInst::getStep() const {
165   if (InstrProfIncrementInstStep::classof(this)) {
166     return const_cast<Value *>(getArgOperand(4));
167   }
168   const Module *M = getModule();
169   LLVMContext &Context = M->getContext();
170   return ConstantInt::get(Type::getInt64Ty(Context), 1);
171 }
172 
173 Optional<RoundingMode> ConstrainedFPIntrinsic::getRoundingMode() const {
174   unsigned NumOperands = getNumArgOperands();
175   Metadata *MD = nullptr;
176   auto *MAV = dyn_cast<MetadataAsValue>(getArgOperand(NumOperands - 2));
177   if (MAV)
178     MD = MAV->getMetadata();
179   if (!MD || !isa<MDString>(MD))
180     return None;
181   return StrToRoundingMode(cast<MDString>(MD)->getString());
182 }
183 
184 Optional<fp::ExceptionBehavior>
185 ConstrainedFPIntrinsic::getExceptionBehavior() const {
186   unsigned NumOperands = getNumArgOperands();
187   Metadata *MD = nullptr;
188   auto *MAV = dyn_cast<MetadataAsValue>(getArgOperand(NumOperands - 1));
189   if (MAV)
190     MD = MAV->getMetadata();
191   if (!MD || !isa<MDString>(MD))
192     return None;
193   return StrToExceptionBehavior(cast<MDString>(MD)->getString());
194 }
195 
196 bool ConstrainedFPIntrinsic::isDefaultFPEnvironment() const {
197   Optional<fp::ExceptionBehavior> Except = getExceptionBehavior();
198   if (Except) {
199     if (Except.getValue() != fp::ebIgnore)
200       return false;
201   }
202 
203   Optional<RoundingMode> Rounding = getRoundingMode();
204   if (Rounding) {
205     if (Rounding.getValue() != RoundingMode::NearestTiesToEven)
206       return false;
207   }
208 
209   return true;
210 }
211 
212 FCmpInst::Predicate ConstrainedFPCmpIntrinsic::getPredicate() const {
213   Metadata *MD = cast<MetadataAsValue>(getArgOperand(2))->getMetadata();
214   if (!MD || !isa<MDString>(MD))
215     return FCmpInst::BAD_FCMP_PREDICATE;
216   return StringSwitch<FCmpInst::Predicate>(cast<MDString>(MD)->getString())
217       .Case("oeq", FCmpInst::FCMP_OEQ)
218       .Case("ogt", FCmpInst::FCMP_OGT)
219       .Case("oge", FCmpInst::FCMP_OGE)
220       .Case("olt", FCmpInst::FCMP_OLT)
221       .Case("ole", FCmpInst::FCMP_OLE)
222       .Case("one", FCmpInst::FCMP_ONE)
223       .Case("ord", FCmpInst::FCMP_ORD)
224       .Case("uno", FCmpInst::FCMP_UNO)
225       .Case("ueq", FCmpInst::FCMP_UEQ)
226       .Case("ugt", FCmpInst::FCMP_UGT)
227       .Case("uge", FCmpInst::FCMP_UGE)
228       .Case("ult", FCmpInst::FCMP_ULT)
229       .Case("ule", FCmpInst::FCMP_ULE)
230       .Case("une", FCmpInst::FCMP_UNE)
231       .Default(FCmpInst::BAD_FCMP_PREDICATE);
232 }
233 
234 bool ConstrainedFPIntrinsic::isUnaryOp() const {
235   switch (getIntrinsicID()) {
236   default:
237     return false;
238 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
239   case Intrinsic::INTRINSIC:                                                   \
240     return NARG == 1;
241 #include "llvm/IR/ConstrainedOps.def"
242   }
243 }
244 
245 bool ConstrainedFPIntrinsic::isTernaryOp() const {
246   switch (getIntrinsicID()) {
247   default:
248     return false;
249 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
250   case Intrinsic::INTRINSIC:                                                   \
251     return NARG == 3;
252 #include "llvm/IR/ConstrainedOps.def"
253   }
254 }
255 
256 bool ConstrainedFPIntrinsic::classof(const IntrinsicInst *I) {
257   switch (I->getIntrinsicID()) {
258 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
259   case Intrinsic::INTRINSIC:
260 #include "llvm/IR/ConstrainedOps.def"
261     return true;
262   default:
263     return false;
264   }
265 }
266 
267 ElementCount VPIntrinsic::getStaticVectorLength() const {
268   auto GetVectorLengthOfType = [](const Type *T) -> ElementCount {
269     auto VT = cast<VectorType>(T);
270     auto ElemCount = VT->getElementCount();
271     return ElemCount;
272   };
273 
274   Value *VPMask = getMaskParam();
275   assert(VPMask && "No mask param?");
276   return GetVectorLengthOfType(VPMask->getType());
277 }
278 
279 Value *VPIntrinsic::getMaskParam() const {
280   if (auto MaskPos = getMaskParamPos(getIntrinsicID()))
281     return getArgOperand(MaskPos.getValue());
282   return nullptr;
283 }
284 
285 void VPIntrinsic::setMaskParam(Value *NewMask) {
286   auto MaskPos = getMaskParamPos(getIntrinsicID());
287   setArgOperand(*MaskPos, NewMask);
288 }
289 
290 Value *VPIntrinsic::getVectorLengthParam() const {
291   if (auto EVLPos = getVectorLengthParamPos(getIntrinsicID()))
292     return getArgOperand(EVLPos.getValue());
293   return nullptr;
294 }
295 
296 void VPIntrinsic::setVectorLengthParam(Value *NewEVL) {
297   auto EVLPos = getVectorLengthParamPos(getIntrinsicID());
298   setArgOperand(*EVLPos, NewEVL);
299 }
300 
301 Optional<unsigned> VPIntrinsic::getMaskParamPos(Intrinsic::ID IntrinsicID) {
302   switch (IntrinsicID) {
303   default:
304     return None;
305 
306 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS)                    \
307   case Intrinsic::VPID:                                                        \
308     return MASKPOS;
309 #include "llvm/IR/VPIntrinsics.def"
310   }
311 }
312 
313 Optional<unsigned>
314 VPIntrinsic::getVectorLengthParamPos(Intrinsic::ID IntrinsicID) {
315   switch (IntrinsicID) {
316   default:
317     return None;
318 
319 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS)                    \
320   case Intrinsic::VPID:                                                        \
321     return VLENPOS;
322 #include "llvm/IR/VPIntrinsics.def"
323   }
324 }
325 
326 bool VPIntrinsic::isVPIntrinsic(Intrinsic::ID ID) {
327   switch (ID) {
328   default:
329     return false;
330 
331 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, MASKPOS, VLENPOS)                    \
332   case Intrinsic::VPID:                                                        \
333     break;
334 #include "llvm/IR/VPIntrinsics.def"
335   }
336   return true;
337 }
338 
339 // Equivalent non-predicated opcode
340 Optional<unsigned> VPIntrinsic::getFunctionalOpcodeForVP(Intrinsic::ID ID) {
341   Optional<unsigned> FunctionalOC;
342   switch (ID) {
343   default:
344     break;
345 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
346 #define HANDLE_VP_TO_OPC(OPC) FunctionalOC = Instruction::OPC;
347 #define END_REGISTER_VP_INTRINSIC(...) break;
348 #include "llvm/IR/VPIntrinsics.def"
349   }
350 
351   return FunctionalOC;
352 }
353 
354 Intrinsic::ID VPIntrinsic::getForOpcode(unsigned IROPC) {
355   switch (IROPC) {
356   default:
357     return Intrinsic::not_intrinsic;
358 
359 #define HANDLE_VP_TO_OPC(OPC) case Instruction::OPC:
360 #define END_REGISTER_VP_INTRINSIC(VPID) return Intrinsic::VPID;
361 #include "llvm/IR/VPIntrinsics.def"
362   }
363 }
364 
365 bool VPIntrinsic::canIgnoreVectorLengthParam() const {
366   using namespace PatternMatch;
367 
368   ElementCount EC = getStaticVectorLength();
369 
370   // No vlen param - no lanes masked-off by it.
371   auto *VLParam = getVectorLengthParam();
372   if (!VLParam)
373     return true;
374 
375   // Note that the VP intrinsic causes undefined behavior if the Explicit Vector
376   // Length parameter is strictly greater-than the number of vector elements of
377   // the operation. This function returns true when this is detected statically
378   // in the IR.
379 
380   // Check whether "W == vscale * EC.getKnownMinValue()"
381   if (EC.isScalable()) {
382     // Undig the DL
383     auto ParMod = this->getModule();
384     if (!ParMod)
385       return false;
386     const auto &DL = ParMod->getDataLayout();
387 
388     // Compare vscale patterns
389     uint64_t VScaleFactor;
390     if (match(VLParam, m_c_Mul(m_ConstantInt(VScaleFactor), m_VScale(DL))))
391       return VScaleFactor >= EC.getKnownMinValue();
392     return (EC.getKnownMinValue() == 1) && match(VLParam, m_VScale(DL));
393   }
394 
395   // standard SIMD operation
396   auto VLConst = dyn_cast<ConstantInt>(VLParam);
397   if (!VLConst)
398     return false;
399 
400   uint64_t VLNum = VLConst->getZExtValue();
401   if (VLNum >= EC.getKnownMinValue())
402     return true;
403 
404   return false;
405 }
406 
407 Function *VPIntrinsic::getDeclarationForParams(Module *M, Intrinsic::ID VPID,
408                                                ArrayRef<Value *> Params) {
409   assert(isVPIntrinsic(VPID) && "not a VP intrinsic");
410 
411   // TODO: Extend this for other VP intrinsics as they are upstreamed. This
412   // works for binary arithmetic VP intrinsics.
413   auto *VPFunc = Intrinsic::getDeclaration(M, VPID, Params[0]->getType());
414   assert(VPFunc && "Could not declare VP intrinsic");
415   return VPFunc;
416 }
417 
418 Instruction::BinaryOps BinaryOpIntrinsic::getBinaryOp() const {
419   switch (getIntrinsicID()) {
420   case Intrinsic::uadd_with_overflow:
421   case Intrinsic::sadd_with_overflow:
422   case Intrinsic::uadd_sat:
423   case Intrinsic::sadd_sat:
424     return Instruction::Add;
425   case Intrinsic::usub_with_overflow:
426   case Intrinsic::ssub_with_overflow:
427   case Intrinsic::usub_sat:
428   case Intrinsic::ssub_sat:
429     return Instruction::Sub;
430   case Intrinsic::umul_with_overflow:
431   case Intrinsic::smul_with_overflow:
432     return Instruction::Mul;
433   default:
434     llvm_unreachable("Invalid intrinsic");
435   }
436 }
437 
438 bool BinaryOpIntrinsic::isSigned() const {
439   switch (getIntrinsicID()) {
440   case Intrinsic::sadd_with_overflow:
441   case Intrinsic::ssub_with_overflow:
442   case Intrinsic::smul_with_overflow:
443   case Intrinsic::sadd_sat:
444   case Intrinsic::ssub_sat:
445     return true;
446   default:
447     return false;
448   }
449 }
450 
451 unsigned BinaryOpIntrinsic::getNoWrapKind() const {
452   if (isSigned())
453     return OverflowingBinaryOperator::NoSignedWrap;
454   else
455     return OverflowingBinaryOperator::NoUnsignedWrap;
456 }
457 
458 const GCStatepointInst *GCProjectionInst::getStatepoint() const {
459   const Value *Token = getArgOperand(0);
460 
461   // This takes care both of relocates for call statepoints and relocates
462   // on normal path of invoke statepoint.
463   if (!isa<LandingPadInst>(Token))
464     return cast<GCStatepointInst>(Token);
465 
466   // This relocate is on exceptional path of an invoke statepoint
467   const BasicBlock *InvokeBB =
468     cast<Instruction>(Token)->getParent()->getUniquePredecessor();
469 
470   assert(InvokeBB && "safepoints should have unique landingpads");
471   assert(InvokeBB->getTerminator() &&
472          "safepoint block should be well formed");
473 
474   return cast<GCStatepointInst>(InvokeBB->getTerminator());
475 }
476 
477 Value *GCRelocateInst::getBasePtr() const {
478   if (auto Opt = getStatepoint()->getOperandBundle(LLVMContext::OB_gc_live))
479     return *(Opt->Inputs.begin() + getBasePtrIndex());
480   return *(getStatepoint()->arg_begin() + getBasePtrIndex());
481 }
482 
483 Value *GCRelocateInst::getDerivedPtr() const {
484   if (auto Opt = getStatepoint()->getOperandBundle(LLVMContext::OB_gc_live))
485     return *(Opt->Inputs.begin() + getDerivedPtrIndex());
486   return *(getStatepoint()->arg_begin() + getDerivedPtrIndex());
487 }
488