1 //===- Function.cpp - Implement the Global object classes -----------------===//
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 the Function class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/IR/Function.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/AbstractCallSite.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constant.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/InstIterator.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/IntrinsicsAArch64.h"
36 #include "llvm/IR/IntrinsicsAMDGPU.h"
37 #include "llvm/IR/IntrinsicsARM.h"
38 #include "llvm/IR/IntrinsicsBPF.h"
39 #include "llvm/IR/IntrinsicsHexagon.h"
40 #include "llvm/IR/IntrinsicsMips.h"
41 #include "llvm/IR/IntrinsicsNVPTX.h"
42 #include "llvm/IR/IntrinsicsPowerPC.h"
43 #include "llvm/IR/IntrinsicsR600.h"
44 #include "llvm/IR/IntrinsicsRISCV.h"
45 #include "llvm/IR/IntrinsicsS390.h"
46 #include "llvm/IR/IntrinsicsVE.h"
47 #include "llvm/IR/IntrinsicsWebAssembly.h"
48 #include "llvm/IR/IntrinsicsX86.h"
49 #include "llvm/IR/IntrinsicsXCore.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/MDBuilder.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/SymbolTableListTraits.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/Use.h"
57 #include "llvm/IR/User.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/IR/ValueSymbolTable.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include <algorithm>
64 #include <cassert>
65 #include <cstddef>
66 #include <cstdint>
67 #include <cstring>
68 #include <string>
69
70 using namespace llvm;
71 using ProfileCount = Function::ProfileCount;
72
73 // Explicit instantiations of SymbolTableListTraits since some of the methods
74 // are not in the public header file...
75 template class llvm::SymbolTableListTraits<BasicBlock>;
76
77 //===----------------------------------------------------------------------===//
78 // Argument Implementation
79 //===----------------------------------------------------------------------===//
80
Argument(Type * Ty,const Twine & Name,Function * Par,unsigned ArgNo)81 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
82 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
83 setName(Name);
84 }
85
setParent(Function * parent)86 void Argument::setParent(Function *parent) {
87 Parent = parent;
88 }
89
hasNonNullAttr() const90 bool Argument::hasNonNullAttr() const {
91 if (!getType()->isPointerTy()) return false;
92 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
93 return true;
94 else if (getDereferenceableBytes() > 0 &&
95 !NullPointerIsDefined(getParent(),
96 getType()->getPointerAddressSpace()))
97 return true;
98 return false;
99 }
100
hasByValAttr() const101 bool Argument::hasByValAttr() const {
102 if (!getType()->isPointerTy()) return false;
103 return hasAttribute(Attribute::ByVal);
104 }
105
hasByRefAttr() const106 bool Argument::hasByRefAttr() const {
107 if (!getType()->isPointerTy())
108 return false;
109 return hasAttribute(Attribute::ByRef);
110 }
111
hasSwiftSelfAttr() const112 bool Argument::hasSwiftSelfAttr() const {
113 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
114 }
115
hasSwiftErrorAttr() const116 bool Argument::hasSwiftErrorAttr() const {
117 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
118 }
119
hasInAllocaAttr() const120 bool Argument::hasInAllocaAttr() const {
121 if (!getType()->isPointerTy()) return false;
122 return hasAttribute(Attribute::InAlloca);
123 }
124
hasPreallocatedAttr() const125 bool Argument::hasPreallocatedAttr() const {
126 if (!getType()->isPointerTy())
127 return false;
128 return hasAttribute(Attribute::Preallocated);
129 }
130
hasPassPointeeByValueCopyAttr() const131 bool Argument::hasPassPointeeByValueCopyAttr() const {
132 if (!getType()->isPointerTy()) return false;
133 AttributeList Attrs = getParent()->getAttributes();
134 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
135 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
136 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated);
137 }
138
hasPointeeInMemoryValueAttr() const139 bool Argument::hasPointeeInMemoryValueAttr() const {
140 if (!getType()->isPointerTy())
141 return false;
142 AttributeList Attrs = getParent()->getAttributes();
143 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
144 Attrs.hasParamAttribute(getArgNo(), Attribute::StructRet) ||
145 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
146 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated) ||
147 Attrs.hasParamAttribute(getArgNo(), Attribute::ByRef);
148 }
149
150 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
151 /// parameter type.
getMemoryParamAllocType(AttributeSet ParamAttrs,Type * ArgTy)152 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) {
153 // FIXME: All the type carrying attributes are mutually exclusive, so there
154 // should be a single query to get the stored type that handles any of them.
155 if (Type *ByValTy = ParamAttrs.getByValType())
156 return ByValTy;
157 if (Type *ByRefTy = ParamAttrs.getByRefType())
158 return ByRefTy;
159 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
160 return PreAllocTy;
161
162 // FIXME: sret and inalloca always depends on pointee element type. It's also
163 // possible for byval to miss it.
164 if (ParamAttrs.hasAttribute(Attribute::InAlloca) ||
165 ParamAttrs.hasAttribute(Attribute::ByVal) ||
166 ParamAttrs.hasAttribute(Attribute::StructRet) ||
167 ParamAttrs.hasAttribute(Attribute::Preallocated))
168 return cast<PointerType>(ArgTy)->getElementType();
169
170 return nullptr;
171 }
172
getPassPointeeByValueCopySize(const DataLayout & DL) const173 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
174 AttributeSet ParamAttrs =
175 getParent()->getAttributes().getParamAttributes(getArgNo());
176 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType()))
177 return DL.getTypeAllocSize(MemTy);
178 return 0;
179 }
180
getPointeeInMemoryValueType() const181 Type *Argument::getPointeeInMemoryValueType() const {
182 AttributeSet ParamAttrs =
183 getParent()->getAttributes().getParamAttributes(getArgNo());
184 return getMemoryParamAllocType(ParamAttrs, getType());
185 }
186
getParamAlignment() const187 unsigned Argument::getParamAlignment() const {
188 assert(getType()->isPointerTy() && "Only pointers have alignments");
189 return getParent()->getParamAlignment(getArgNo());
190 }
191
getParamAlign() const192 MaybeAlign Argument::getParamAlign() const {
193 assert(getType()->isPointerTy() && "Only pointers have alignments");
194 return getParent()->getParamAlign(getArgNo());
195 }
196
getParamByValType() const197 Type *Argument::getParamByValType() const {
198 assert(getType()->isPointerTy() && "Only pointers have byval types");
199 return getParent()->getParamByValType(getArgNo());
200 }
201
getParamStructRetType() const202 Type *Argument::getParamStructRetType() const {
203 assert(getType()->isPointerTy() && "Only pointers have sret types");
204 return getParent()->getParamStructRetType(getArgNo());
205 }
206
getParamByRefType() const207 Type *Argument::getParamByRefType() const {
208 assert(getType()->isPointerTy() && "Only pointers have byval types");
209 return getParent()->getParamByRefType(getArgNo());
210 }
211
getDereferenceableBytes() const212 uint64_t Argument::getDereferenceableBytes() const {
213 assert(getType()->isPointerTy() &&
214 "Only pointers have dereferenceable bytes");
215 return getParent()->getParamDereferenceableBytes(getArgNo());
216 }
217
getDereferenceableOrNullBytes() const218 uint64_t Argument::getDereferenceableOrNullBytes() const {
219 assert(getType()->isPointerTy() &&
220 "Only pointers have dereferenceable bytes");
221 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
222 }
223
hasNestAttr() const224 bool Argument::hasNestAttr() const {
225 if (!getType()->isPointerTy()) return false;
226 return hasAttribute(Attribute::Nest);
227 }
228
hasNoAliasAttr() const229 bool Argument::hasNoAliasAttr() const {
230 if (!getType()->isPointerTy()) return false;
231 return hasAttribute(Attribute::NoAlias);
232 }
233
hasNoCaptureAttr() const234 bool Argument::hasNoCaptureAttr() const {
235 if (!getType()->isPointerTy()) return false;
236 return hasAttribute(Attribute::NoCapture);
237 }
238
hasStructRetAttr() const239 bool Argument::hasStructRetAttr() const {
240 if (!getType()->isPointerTy()) return false;
241 return hasAttribute(Attribute::StructRet);
242 }
243
hasInRegAttr() const244 bool Argument::hasInRegAttr() const {
245 return hasAttribute(Attribute::InReg);
246 }
247
hasReturnedAttr() const248 bool Argument::hasReturnedAttr() const {
249 return hasAttribute(Attribute::Returned);
250 }
251
hasZExtAttr() const252 bool Argument::hasZExtAttr() const {
253 return hasAttribute(Attribute::ZExt);
254 }
255
hasSExtAttr() const256 bool Argument::hasSExtAttr() const {
257 return hasAttribute(Attribute::SExt);
258 }
259
onlyReadsMemory() const260 bool Argument::onlyReadsMemory() const {
261 AttributeList Attrs = getParent()->getAttributes();
262 return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
263 Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
264 }
265
addAttrs(AttrBuilder & B)266 void Argument::addAttrs(AttrBuilder &B) {
267 AttributeList AL = getParent()->getAttributes();
268 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
269 getParent()->setAttributes(AL);
270 }
271
addAttr(Attribute::AttrKind Kind)272 void Argument::addAttr(Attribute::AttrKind Kind) {
273 getParent()->addParamAttr(getArgNo(), Kind);
274 }
275
addAttr(Attribute Attr)276 void Argument::addAttr(Attribute Attr) {
277 getParent()->addParamAttr(getArgNo(), Attr);
278 }
279
removeAttr(Attribute::AttrKind Kind)280 void Argument::removeAttr(Attribute::AttrKind Kind) {
281 getParent()->removeParamAttr(getArgNo(), Kind);
282 }
283
hasAttribute(Attribute::AttrKind Kind) const284 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
285 return getParent()->hasParamAttribute(getArgNo(), Kind);
286 }
287
getAttribute(Attribute::AttrKind Kind) const288 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
289 return getParent()->getParamAttribute(getArgNo(), Kind);
290 }
291
292 //===----------------------------------------------------------------------===//
293 // Helper Methods in Function
294 //===----------------------------------------------------------------------===//
295
getContext() const296 LLVMContext &Function::getContext() const {
297 return getType()->getContext();
298 }
299
getInstructionCount() const300 unsigned Function::getInstructionCount() const {
301 unsigned NumInstrs = 0;
302 for (const BasicBlock &BB : BasicBlocks)
303 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
304 BB.instructionsWithoutDebug().end());
305 return NumInstrs;
306 }
307
Create(FunctionType * Ty,LinkageTypes Linkage,const Twine & N,Module & M)308 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
309 const Twine &N, Module &M) {
310 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
311 }
312
removeFromParent()313 void Function::removeFromParent() {
314 getParent()->getFunctionList().remove(getIterator());
315 }
316
eraseFromParent()317 void Function::eraseFromParent() {
318 getParent()->getFunctionList().erase(getIterator());
319 }
320
321 //===----------------------------------------------------------------------===//
322 // Function Implementation
323 //===----------------------------------------------------------------------===//
324
computeAddrSpace(unsigned AddrSpace,Module * M)325 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
326 // If AS == -1 and we are passed a valid module pointer we place the function
327 // in the program address space. Otherwise we default to AS0.
328 if (AddrSpace == static_cast<unsigned>(-1))
329 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
330 return AddrSpace;
331 }
332
Function(FunctionType * Ty,LinkageTypes Linkage,unsigned AddrSpace,const Twine & name,Module * ParentModule)333 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
334 const Twine &name, Module *ParentModule)
335 : GlobalObject(Ty, Value::FunctionVal,
336 OperandTraits<Function>::op_begin(this), 0, Linkage, name,
337 computeAddrSpace(AddrSpace, ParentModule)),
338 NumArgs(Ty->getNumParams()) {
339 assert(FunctionType::isValidReturnType(getReturnType()) &&
340 "invalid return type");
341 setGlobalObjectSubClassData(0);
342
343 // We only need a symbol table for a function if the context keeps value names
344 if (!getContext().shouldDiscardValueNames())
345 SymTab = std::make_unique<ValueSymbolTable>();
346
347 // If the function has arguments, mark them as lazily built.
348 if (Ty->getNumParams())
349 setValueSubclassData(1); // Set the "has lazy arguments" bit.
350
351 if (ParentModule)
352 ParentModule->getFunctionList().push_back(this);
353
354 HasLLVMReservedName = getName().startswith("llvm.");
355 // Ensure intrinsics have the right parameter attributes.
356 // Note, the IntID field will have been set in Value::setName if this function
357 // name is a valid intrinsic ID.
358 if (IntID)
359 setAttributes(Intrinsic::getAttributes(getContext(), IntID));
360 }
361
~Function()362 Function::~Function() {
363 dropAllReferences(); // After this it is safe to delete instructions.
364
365 // Delete all of the method arguments and unlink from symbol table...
366 if (Arguments)
367 clearArguments();
368
369 // Remove the function from the on-the-side GC table.
370 clearGC();
371 }
372
BuildLazyArguments() const373 void Function::BuildLazyArguments() const {
374 // Create the arguments vector, all arguments start out unnamed.
375 auto *FT = getFunctionType();
376 if (NumArgs > 0) {
377 Arguments = std::allocator<Argument>().allocate(NumArgs);
378 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
379 Type *ArgTy = FT->getParamType(i);
380 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
381 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
382 }
383 }
384
385 // Clear the lazy arguments bit.
386 unsigned SDC = getSubclassDataFromValue();
387 SDC &= ~(1 << 0);
388 const_cast<Function*>(this)->setValueSubclassData(SDC);
389 assert(!hasLazyArguments());
390 }
391
makeArgArray(Argument * Args,size_t Count)392 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
393 return MutableArrayRef<Argument>(Args, Count);
394 }
395
isConstrainedFPIntrinsic() const396 bool Function::isConstrainedFPIntrinsic() const {
397 switch (getIntrinsicID()) {
398 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
399 case Intrinsic::INTRINSIC:
400 #include "llvm/IR/ConstrainedOps.def"
401 return true;
402 #undef INSTRUCTION
403 default:
404 return false;
405 }
406 }
407
clearArguments()408 void Function::clearArguments() {
409 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
410 A.setName("");
411 A.~Argument();
412 }
413 std::allocator<Argument>().deallocate(Arguments, NumArgs);
414 Arguments = nullptr;
415 }
416
stealArgumentListFrom(Function & Src)417 void Function::stealArgumentListFrom(Function &Src) {
418 assert(isDeclaration() && "Expected no references to current arguments");
419
420 // Drop the current arguments, if any, and set the lazy argument bit.
421 if (!hasLazyArguments()) {
422 assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
423 [](const Argument &A) { return A.use_empty(); }) &&
424 "Expected arguments to be unused in declaration");
425 clearArguments();
426 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
427 }
428
429 // Nothing to steal if Src has lazy arguments.
430 if (Src.hasLazyArguments())
431 return;
432
433 // Steal arguments from Src, and fix the lazy argument bits.
434 assert(arg_size() == Src.arg_size());
435 Arguments = Src.Arguments;
436 Src.Arguments = nullptr;
437 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
438 // FIXME: This does the work of transferNodesFromList inefficiently.
439 SmallString<128> Name;
440 if (A.hasName())
441 Name = A.getName();
442 if (!Name.empty())
443 A.setName("");
444 A.setParent(this);
445 if (!Name.empty())
446 A.setName(Name);
447 }
448
449 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
450 assert(!hasLazyArguments());
451 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
452 }
453
454 // dropAllReferences() - This function causes all the subinstructions to "let
455 // go" of all references that they are maintaining. This allows one to
456 // 'delete' a whole class at a time, even though there may be circular
457 // references... first all references are dropped, and all use counts go to
458 // zero. Then everything is deleted for real. Note that no operations are
459 // valid on an object that has "dropped all references", except operator
460 // delete.
461 //
dropAllReferences()462 void Function::dropAllReferences() {
463 setIsMaterializable(false);
464
465 for (BasicBlock &BB : *this)
466 BB.dropAllReferences();
467
468 // Delete all basic blocks. They are now unused, except possibly by
469 // blockaddresses, but BasicBlock's destructor takes care of those.
470 while (!BasicBlocks.empty())
471 BasicBlocks.begin()->eraseFromParent();
472
473 // Drop uses of any optional data (real or placeholder).
474 if (getNumOperands()) {
475 User::dropAllReferences();
476 setNumHungOffUseOperands(0);
477 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
478 }
479
480 // Metadata is stored in a side-table.
481 clearMetadata();
482 }
483
addAttribute(unsigned i,Attribute::AttrKind Kind)484 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
485 AttributeList PAL = getAttributes();
486 PAL = PAL.addAttribute(getContext(), i, Kind);
487 setAttributes(PAL);
488 }
489
addAttribute(unsigned i,Attribute Attr)490 void Function::addAttribute(unsigned i, Attribute Attr) {
491 AttributeList PAL = getAttributes();
492 PAL = PAL.addAttribute(getContext(), i, Attr);
493 setAttributes(PAL);
494 }
495
addAttributes(unsigned i,const AttrBuilder & Attrs)496 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
497 AttributeList PAL = getAttributes();
498 PAL = PAL.addAttributes(getContext(), i, Attrs);
499 setAttributes(PAL);
500 }
501
addParamAttr(unsigned ArgNo,Attribute::AttrKind Kind)502 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
503 AttributeList PAL = getAttributes();
504 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
505 setAttributes(PAL);
506 }
507
addParamAttr(unsigned ArgNo,Attribute Attr)508 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
509 AttributeList PAL = getAttributes();
510 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
511 setAttributes(PAL);
512 }
513
addParamAttrs(unsigned ArgNo,const AttrBuilder & Attrs)514 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
515 AttributeList PAL = getAttributes();
516 PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
517 setAttributes(PAL);
518 }
519
removeAttribute(unsigned i,Attribute::AttrKind Kind)520 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
521 AttributeList PAL = getAttributes();
522 PAL = PAL.removeAttribute(getContext(), i, Kind);
523 setAttributes(PAL);
524 }
525
removeAttribute(unsigned i,StringRef Kind)526 void Function::removeAttribute(unsigned i, StringRef Kind) {
527 AttributeList PAL = getAttributes();
528 PAL = PAL.removeAttribute(getContext(), i, Kind);
529 setAttributes(PAL);
530 }
531
removeAttributes(unsigned i,const AttrBuilder & Attrs)532 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
533 AttributeList PAL = getAttributes();
534 PAL = PAL.removeAttributes(getContext(), i, Attrs);
535 setAttributes(PAL);
536 }
537
removeParamAttr(unsigned ArgNo,Attribute::AttrKind Kind)538 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
539 AttributeList PAL = getAttributes();
540 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
541 setAttributes(PAL);
542 }
543
removeParamAttr(unsigned ArgNo,StringRef Kind)544 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
545 AttributeList PAL = getAttributes();
546 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
547 setAttributes(PAL);
548 }
549
removeParamAttrs(unsigned ArgNo,const AttrBuilder & Attrs)550 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
551 AttributeList PAL = getAttributes();
552 PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
553 setAttributes(PAL);
554 }
555
addDereferenceableAttr(unsigned i,uint64_t Bytes)556 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
557 AttributeList PAL = getAttributes();
558 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
559 setAttributes(PAL);
560 }
561
addDereferenceableParamAttr(unsigned ArgNo,uint64_t Bytes)562 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
563 AttributeList PAL = getAttributes();
564 PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
565 setAttributes(PAL);
566 }
567
addDereferenceableOrNullAttr(unsigned i,uint64_t Bytes)568 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
569 AttributeList PAL = getAttributes();
570 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
571 setAttributes(PAL);
572 }
573
addDereferenceableOrNullParamAttr(unsigned ArgNo,uint64_t Bytes)574 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
575 uint64_t Bytes) {
576 AttributeList PAL = getAttributes();
577 PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
578 setAttributes(PAL);
579 }
580
getDenormalMode(const fltSemantics & FPType) const581 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
582 if (&FPType == &APFloat::IEEEsingle()) {
583 Attribute Attr = getFnAttribute("denormal-fp-math-f32");
584 StringRef Val = Attr.getValueAsString();
585 if (!Val.empty())
586 return parseDenormalFPAttribute(Val);
587
588 // If the f32 variant of the attribute isn't specified, try to use the
589 // generic one.
590 }
591
592 Attribute Attr = getFnAttribute("denormal-fp-math");
593 return parseDenormalFPAttribute(Attr.getValueAsString());
594 }
595
getGC() const596 const std::string &Function::getGC() const {
597 assert(hasGC() && "Function has no collector");
598 return getContext().getGC(*this);
599 }
600
setGC(std::string Str)601 void Function::setGC(std::string Str) {
602 setValueSubclassDataBit(14, !Str.empty());
603 getContext().setGC(*this, std::move(Str));
604 }
605
clearGC()606 void Function::clearGC() {
607 if (!hasGC())
608 return;
609 getContext().deleteGC(*this);
610 setValueSubclassDataBit(14, false);
611 }
612
hasStackProtectorFnAttr() const613 bool Function::hasStackProtectorFnAttr() const {
614 return hasFnAttribute(Attribute::StackProtect) ||
615 hasFnAttribute(Attribute::StackProtectStrong) ||
616 hasFnAttribute(Attribute::StackProtectReq);
617 }
618
619 /// Copy all additional attributes (those not needed to create a Function) from
620 /// the Function Src to this one.
copyAttributesFrom(const Function * Src)621 void Function::copyAttributesFrom(const Function *Src) {
622 GlobalObject::copyAttributesFrom(Src);
623 setCallingConv(Src->getCallingConv());
624 setAttributes(Src->getAttributes());
625 if (Src->hasGC())
626 setGC(Src->getGC());
627 else
628 clearGC();
629 if (Src->hasPersonalityFn())
630 setPersonalityFn(Src->getPersonalityFn());
631 if (Src->hasPrefixData())
632 setPrefixData(Src->getPrefixData());
633 if (Src->hasPrologueData())
634 setPrologueData(Src->getPrologueData());
635 }
636
637 /// Table of string intrinsic names indexed by enum value.
638 static const char * const IntrinsicNameTable[] = {
639 "not_intrinsic",
640 #define GET_INTRINSIC_NAME_TABLE
641 #include "llvm/IR/IntrinsicImpl.inc"
642 #undef GET_INTRINSIC_NAME_TABLE
643 };
644
645 /// Table of per-target intrinsic name tables.
646 #define GET_INTRINSIC_TARGET_DATA
647 #include "llvm/IR/IntrinsicImpl.inc"
648 #undef GET_INTRINSIC_TARGET_DATA
649
isTargetIntrinsic(Intrinsic::ID IID)650 bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
651 return IID > TargetInfos[0].Count;
652 }
653
isTargetIntrinsic() const654 bool Function::isTargetIntrinsic() const {
655 return isTargetIntrinsic(IntID);
656 }
657
658 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
659 /// target as \c Name, or the generic table if \c Name is not target specific.
660 ///
661 /// Returns the relevant slice of \c IntrinsicNameTable
findTargetSubtable(StringRef Name)662 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
663 assert(Name.startswith("llvm."));
664
665 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
666 // Drop "llvm." and take the first dotted component. That will be the target
667 // if this is target specific.
668 StringRef Target = Name.drop_front(5).split('.').first;
669 auto It = partition_point(
670 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
671 // We've either found the target or just fall back to the generic set, which
672 // is always first.
673 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
674 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
675 }
676
677 /// This does the actual lookup of an intrinsic ID which
678 /// matches the given function name.
lookupIntrinsicID(StringRef Name)679 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
680 ArrayRef<const char *> NameTable = findTargetSubtable(Name);
681 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
682 if (Idx == -1)
683 return Intrinsic::not_intrinsic;
684
685 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
686 // an index into a sub-table.
687 int Adjust = NameTable.data() - IntrinsicNameTable;
688 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
689
690 // If the intrinsic is not overloaded, require an exact match. If it is
691 // overloaded, require either exact or prefix match.
692 const auto MatchSize = strlen(NameTable[Idx]);
693 assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
694 bool IsExactMatch = Name.size() == MatchSize;
695 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
696 : Intrinsic::not_intrinsic;
697 }
698
recalculateIntrinsicID()699 void Function::recalculateIntrinsicID() {
700 StringRef Name = getName();
701 if (!Name.startswith("llvm.")) {
702 HasLLVMReservedName = false;
703 IntID = Intrinsic::not_intrinsic;
704 return;
705 }
706 HasLLVMReservedName = true;
707 IntID = lookupIntrinsicID(Name);
708 }
709
710 /// Returns a stable mangling for the type specified for use in the name
711 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
712 /// of named types is simply their name. Manglings for unnamed types consist
713 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
714 /// combined with the mangling of their component types. A vararg function
715 /// type will have a suffix of 'vararg'. Since function types can contain
716 /// other function types, we close a function type mangling with suffix 'f'
717 /// which can't be confused with it's prefix. This ensures we don't have
718 /// collisions between two unrelated function types. Otherwise, you might
719 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
720 ///
getMangledTypeStr(Type * Ty)721 static std::string getMangledTypeStr(Type* Ty) {
722 std::string Result;
723 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
724 Result += "p" + utostr(PTyp->getAddressSpace()) +
725 getMangledTypeStr(PTyp->getElementType());
726 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
727 Result += "a" + utostr(ATyp->getNumElements()) +
728 getMangledTypeStr(ATyp->getElementType());
729 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
730 if (!STyp->isLiteral()) {
731 Result += "s_";
732 Result += STyp->getName();
733 } else {
734 Result += "sl_";
735 for (auto Elem : STyp->elements())
736 Result += getMangledTypeStr(Elem);
737 }
738 // Ensure nested structs are distinguishable.
739 Result += "s";
740 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
741 Result += "f_" + getMangledTypeStr(FT->getReturnType());
742 for (size_t i = 0; i < FT->getNumParams(); i++)
743 Result += getMangledTypeStr(FT->getParamType(i));
744 if (FT->isVarArg())
745 Result += "vararg";
746 // Ensure nested function types are distinguishable.
747 Result += "f";
748 } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
749 ElementCount EC = VTy->getElementCount();
750 if (EC.isScalable())
751 Result += "nx";
752 Result += "v" + utostr(EC.getKnownMinValue()) +
753 getMangledTypeStr(VTy->getElementType());
754 } else if (Ty) {
755 switch (Ty->getTypeID()) {
756 default: llvm_unreachable("Unhandled type");
757 case Type::VoidTyID: Result += "isVoid"; break;
758 case Type::MetadataTyID: Result += "Metadata"; break;
759 case Type::HalfTyID: Result += "f16"; break;
760 case Type::BFloatTyID: Result += "bf16"; break;
761 case Type::FloatTyID: Result += "f32"; break;
762 case Type::DoubleTyID: Result += "f64"; break;
763 case Type::X86_FP80TyID: Result += "f80"; break;
764 case Type::FP128TyID: Result += "f128"; break;
765 case Type::PPC_FP128TyID: Result += "ppcf128"; break;
766 case Type::X86_MMXTyID: Result += "x86mmx"; break;
767 case Type::IntegerTyID:
768 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
769 break;
770 }
771 }
772 return Result;
773 }
774
getName(ID id)775 StringRef Intrinsic::getName(ID id) {
776 assert(id < num_intrinsics && "Invalid intrinsic ID!");
777 assert(!Intrinsic::isOverloaded(id) &&
778 "This version of getName does not support overloading");
779 return IntrinsicNameTable[id];
780 }
781
getName(ID id,ArrayRef<Type * > Tys)782 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
783 assert(id < num_intrinsics && "Invalid intrinsic ID!");
784 assert((Tys.empty() || Intrinsic::isOverloaded(id)) &&
785 "This version of getName is for overloaded intrinsics only");
786 std::string Result(IntrinsicNameTable[id]);
787 for (Type *Ty : Tys) {
788 Result += "." + getMangledTypeStr(Ty);
789 }
790 return Result;
791 }
792
793 /// IIT_Info - These are enumerators that describe the entries returned by the
794 /// getIntrinsicInfoTableEntries function.
795 ///
796 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
797 enum IIT_Info {
798 // Common values should be encoded with 0-15.
799 IIT_Done = 0,
800 IIT_I1 = 1,
801 IIT_I8 = 2,
802 IIT_I16 = 3,
803 IIT_I32 = 4,
804 IIT_I64 = 5,
805 IIT_F16 = 6,
806 IIT_F32 = 7,
807 IIT_F64 = 8,
808 IIT_V2 = 9,
809 IIT_V4 = 10,
810 IIT_V8 = 11,
811 IIT_V16 = 12,
812 IIT_V32 = 13,
813 IIT_PTR = 14,
814 IIT_ARG = 15,
815
816 // Values from 16+ are only encodable with the inefficient encoding.
817 IIT_V64 = 16,
818 IIT_MMX = 17,
819 IIT_TOKEN = 18,
820 IIT_METADATA = 19,
821 IIT_EMPTYSTRUCT = 20,
822 IIT_STRUCT2 = 21,
823 IIT_STRUCT3 = 22,
824 IIT_STRUCT4 = 23,
825 IIT_STRUCT5 = 24,
826 IIT_EXTEND_ARG = 25,
827 IIT_TRUNC_ARG = 26,
828 IIT_ANYPTR = 27,
829 IIT_V1 = 28,
830 IIT_VARARG = 29,
831 IIT_HALF_VEC_ARG = 30,
832 IIT_SAME_VEC_WIDTH_ARG = 31,
833 IIT_PTR_TO_ARG = 32,
834 IIT_PTR_TO_ELT = 33,
835 IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
836 IIT_I128 = 35,
837 IIT_V512 = 36,
838 IIT_V1024 = 37,
839 IIT_STRUCT6 = 38,
840 IIT_STRUCT7 = 39,
841 IIT_STRUCT8 = 40,
842 IIT_F128 = 41,
843 IIT_VEC_ELEMENT = 42,
844 IIT_SCALABLE_VEC = 43,
845 IIT_SUBDIVIDE2_ARG = 44,
846 IIT_SUBDIVIDE4_ARG = 45,
847 IIT_VEC_OF_BITCASTS_TO_INT = 46,
848 IIT_V128 = 47,
849 IIT_BF16 = 48,
850 IIT_STRUCT9 = 49,
851 IIT_V256 = 50
852 };
853
DecodeIITType(unsigned & NextElt,ArrayRef<unsigned char> Infos,IIT_Info LastInfo,SmallVectorImpl<Intrinsic::IITDescriptor> & OutputTable)854 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
855 IIT_Info LastInfo,
856 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
857 using namespace Intrinsic;
858
859 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
860
861 IIT_Info Info = IIT_Info(Infos[NextElt++]);
862 unsigned StructElts = 2;
863
864 switch (Info) {
865 case IIT_Done:
866 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
867 return;
868 case IIT_VARARG:
869 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
870 return;
871 case IIT_MMX:
872 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
873 return;
874 case IIT_TOKEN:
875 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
876 return;
877 case IIT_METADATA:
878 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
879 return;
880 case IIT_F16:
881 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
882 return;
883 case IIT_BF16:
884 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
885 return;
886 case IIT_F32:
887 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
888 return;
889 case IIT_F64:
890 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
891 return;
892 case IIT_F128:
893 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
894 return;
895 case IIT_I1:
896 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
897 return;
898 case IIT_I8:
899 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
900 return;
901 case IIT_I16:
902 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
903 return;
904 case IIT_I32:
905 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
906 return;
907 case IIT_I64:
908 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
909 return;
910 case IIT_I128:
911 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
912 return;
913 case IIT_V1:
914 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
915 DecodeIITType(NextElt, Infos, Info, OutputTable);
916 return;
917 case IIT_V2:
918 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
919 DecodeIITType(NextElt, Infos, Info, OutputTable);
920 return;
921 case IIT_V4:
922 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
923 DecodeIITType(NextElt, Infos, Info, OutputTable);
924 return;
925 case IIT_V8:
926 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
927 DecodeIITType(NextElt, Infos, Info, OutputTable);
928 return;
929 case IIT_V16:
930 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
931 DecodeIITType(NextElt, Infos, Info, OutputTable);
932 return;
933 case IIT_V32:
934 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
935 DecodeIITType(NextElt, Infos, Info, OutputTable);
936 return;
937 case IIT_V64:
938 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
939 DecodeIITType(NextElt, Infos, Info, OutputTable);
940 return;
941 case IIT_V128:
942 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
943 DecodeIITType(NextElt, Infos, Info, OutputTable);
944 return;
945 case IIT_V256:
946 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
947 DecodeIITType(NextElt, Infos, Info, OutputTable);
948 return;
949 case IIT_V512:
950 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
951 DecodeIITType(NextElt, Infos, Info, OutputTable);
952 return;
953 case IIT_V1024:
954 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
955 DecodeIITType(NextElt, Infos, Info, OutputTable);
956 return;
957 case IIT_PTR:
958 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
959 DecodeIITType(NextElt, Infos, Info, OutputTable);
960 return;
961 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
962 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
963 Infos[NextElt++]));
964 DecodeIITType(NextElt, Infos, Info, OutputTable);
965 return;
966 }
967 case IIT_ARG: {
968 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
969 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
970 return;
971 }
972 case IIT_EXTEND_ARG: {
973 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
974 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
975 ArgInfo));
976 return;
977 }
978 case IIT_TRUNC_ARG: {
979 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
980 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
981 ArgInfo));
982 return;
983 }
984 case IIT_HALF_VEC_ARG: {
985 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
986 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
987 ArgInfo));
988 return;
989 }
990 case IIT_SAME_VEC_WIDTH_ARG: {
991 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
992 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
993 ArgInfo));
994 return;
995 }
996 case IIT_PTR_TO_ARG: {
997 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
998 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
999 ArgInfo));
1000 return;
1001 }
1002 case IIT_PTR_TO_ELT: {
1003 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1004 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
1005 return;
1006 }
1007 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
1008 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1009 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1010 OutputTable.push_back(
1011 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
1012 return;
1013 }
1014 case IIT_EMPTYSTRUCT:
1015 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
1016 return;
1017 case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH;
1018 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
1019 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
1020 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
1021 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
1022 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
1023 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
1024 case IIT_STRUCT2: {
1025 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
1026
1027 for (unsigned i = 0; i != StructElts; ++i)
1028 DecodeIITType(NextElt, Infos, Info, OutputTable);
1029 return;
1030 }
1031 case IIT_SUBDIVIDE2_ARG: {
1032 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1033 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
1034 ArgInfo));
1035 return;
1036 }
1037 case IIT_SUBDIVIDE4_ARG: {
1038 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1039 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
1040 ArgInfo));
1041 return;
1042 }
1043 case IIT_VEC_ELEMENT: {
1044 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1045 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
1046 ArgInfo));
1047 return;
1048 }
1049 case IIT_SCALABLE_VEC: {
1050 DecodeIITType(NextElt, Infos, Info, OutputTable);
1051 return;
1052 }
1053 case IIT_VEC_OF_BITCASTS_TO_INT: {
1054 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1055 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
1056 ArgInfo));
1057 return;
1058 }
1059 }
1060 llvm_unreachable("unhandled");
1061 }
1062
1063 #define GET_INTRINSIC_GENERATOR_GLOBAL
1064 #include "llvm/IR/IntrinsicImpl.inc"
1065 #undef GET_INTRINSIC_GENERATOR_GLOBAL
1066
getIntrinsicInfoTableEntries(ID id,SmallVectorImpl<IITDescriptor> & T)1067 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
1068 SmallVectorImpl<IITDescriptor> &T){
1069 // Check to see if the intrinsic's type was expressible by the table.
1070 unsigned TableVal = IIT_Table[id-1];
1071
1072 // Decode the TableVal into an array of IITValues.
1073 SmallVector<unsigned char, 8> IITValues;
1074 ArrayRef<unsigned char> IITEntries;
1075 unsigned NextElt = 0;
1076 if ((TableVal >> 31) != 0) {
1077 // This is an offset into the IIT_LongEncodingTable.
1078 IITEntries = IIT_LongEncodingTable;
1079
1080 // Strip sentinel bit.
1081 NextElt = (TableVal << 1) >> 1;
1082 } else {
1083 // Decode the TableVal into an array of IITValues. If the entry was encoded
1084 // into a single word in the table itself, decode it now.
1085 do {
1086 IITValues.push_back(TableVal & 0xF);
1087 TableVal >>= 4;
1088 } while (TableVal);
1089
1090 IITEntries = IITValues;
1091 NextElt = 0;
1092 }
1093
1094 // Okay, decode the table into the output vector of IITDescriptors.
1095 DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1096 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1097 DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1098 }
1099
DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> & Infos,ArrayRef<Type * > Tys,LLVMContext & Context)1100 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1101 ArrayRef<Type*> Tys, LLVMContext &Context) {
1102 using namespace Intrinsic;
1103
1104 IITDescriptor D = Infos.front();
1105 Infos = Infos.slice(1);
1106
1107 switch (D.Kind) {
1108 case IITDescriptor::Void: return Type::getVoidTy(Context);
1109 case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1110 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1111 case IITDescriptor::Token: return Type::getTokenTy(Context);
1112 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1113 case IITDescriptor::Half: return Type::getHalfTy(Context);
1114 case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1115 case IITDescriptor::Float: return Type::getFloatTy(Context);
1116 case IITDescriptor::Double: return Type::getDoubleTy(Context);
1117 case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1118
1119 case IITDescriptor::Integer:
1120 return IntegerType::get(Context, D.Integer_Width);
1121 case IITDescriptor::Vector:
1122 return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1123 D.Vector_Width);
1124 case IITDescriptor::Pointer:
1125 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1126 D.Pointer_AddressSpace);
1127 case IITDescriptor::Struct: {
1128 SmallVector<Type *, 8> Elts;
1129 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1130 Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1131 return StructType::get(Context, Elts);
1132 }
1133 case IITDescriptor::Argument:
1134 return Tys[D.getArgumentNumber()];
1135 case IITDescriptor::ExtendArgument: {
1136 Type *Ty = Tys[D.getArgumentNumber()];
1137 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1138 return VectorType::getExtendedElementVectorType(VTy);
1139
1140 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1141 }
1142 case IITDescriptor::TruncArgument: {
1143 Type *Ty = Tys[D.getArgumentNumber()];
1144 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1145 return VectorType::getTruncatedElementVectorType(VTy);
1146
1147 IntegerType *ITy = cast<IntegerType>(Ty);
1148 assert(ITy->getBitWidth() % 2 == 0);
1149 return IntegerType::get(Context, ITy->getBitWidth() / 2);
1150 }
1151 case IITDescriptor::Subdivide2Argument:
1152 case IITDescriptor::Subdivide4Argument: {
1153 Type *Ty = Tys[D.getArgumentNumber()];
1154 VectorType *VTy = dyn_cast<VectorType>(Ty);
1155 assert(VTy && "Expected an argument of Vector Type");
1156 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1157 return VectorType::getSubdividedVectorType(VTy, SubDivs);
1158 }
1159 case IITDescriptor::HalfVecArgument:
1160 return VectorType::getHalfElementsVectorType(cast<VectorType>(
1161 Tys[D.getArgumentNumber()]));
1162 case IITDescriptor::SameVecWidthArgument: {
1163 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1164 Type *Ty = Tys[D.getArgumentNumber()];
1165 if (auto *VTy = dyn_cast<VectorType>(Ty))
1166 return VectorType::get(EltTy, VTy->getElementCount());
1167 return EltTy;
1168 }
1169 case IITDescriptor::PtrToArgument: {
1170 Type *Ty = Tys[D.getArgumentNumber()];
1171 return PointerType::getUnqual(Ty);
1172 }
1173 case IITDescriptor::PtrToElt: {
1174 Type *Ty = Tys[D.getArgumentNumber()];
1175 VectorType *VTy = dyn_cast<VectorType>(Ty);
1176 if (!VTy)
1177 llvm_unreachable("Expected an argument of Vector Type");
1178 Type *EltTy = VTy->getElementType();
1179 return PointerType::getUnqual(EltTy);
1180 }
1181 case IITDescriptor::VecElementArgument: {
1182 Type *Ty = Tys[D.getArgumentNumber()];
1183 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1184 return VTy->getElementType();
1185 llvm_unreachable("Expected an argument of Vector Type");
1186 }
1187 case IITDescriptor::VecOfBitcastsToInt: {
1188 Type *Ty = Tys[D.getArgumentNumber()];
1189 VectorType *VTy = dyn_cast<VectorType>(Ty);
1190 assert(VTy && "Expected an argument of Vector Type");
1191 return VectorType::getInteger(VTy);
1192 }
1193 case IITDescriptor::VecOfAnyPtrsToElt:
1194 // Return the overloaded type (which determines the pointers address space)
1195 return Tys[D.getOverloadArgNumber()];
1196 }
1197 llvm_unreachable("unhandled");
1198 }
1199
getType(LLVMContext & Context,ID id,ArrayRef<Type * > Tys)1200 FunctionType *Intrinsic::getType(LLVMContext &Context,
1201 ID id, ArrayRef<Type*> Tys) {
1202 SmallVector<IITDescriptor, 8> Table;
1203 getIntrinsicInfoTableEntries(id, Table);
1204
1205 ArrayRef<IITDescriptor> TableRef = Table;
1206 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
1207
1208 SmallVector<Type*, 8> ArgTys;
1209 while (!TableRef.empty())
1210 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1211
1212 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1213 // If we see void type as the type of the last argument, it is vararg intrinsic
1214 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1215 ArgTys.pop_back();
1216 return FunctionType::get(ResultTy, ArgTys, true);
1217 }
1218 return FunctionType::get(ResultTy, ArgTys, false);
1219 }
1220
isOverloaded(ID id)1221 bool Intrinsic::isOverloaded(ID id) {
1222 #define GET_INTRINSIC_OVERLOAD_TABLE
1223 #include "llvm/IR/IntrinsicImpl.inc"
1224 #undef GET_INTRINSIC_OVERLOAD_TABLE
1225 }
1226
isLeaf(ID id)1227 bool Intrinsic::isLeaf(ID id) {
1228 switch (id) {
1229 default:
1230 return true;
1231
1232 case Intrinsic::experimental_gc_statepoint:
1233 case Intrinsic::experimental_patchpoint_void:
1234 case Intrinsic::experimental_patchpoint_i64:
1235 return false;
1236 }
1237 }
1238
1239 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1240 #define GET_INTRINSIC_ATTRIBUTES
1241 #include "llvm/IR/IntrinsicImpl.inc"
1242 #undef GET_INTRINSIC_ATTRIBUTES
1243
getDeclaration(Module * M,ID id,ArrayRef<Type * > Tys)1244 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1245 // There can never be multiple globals with the same name of different types,
1246 // because intrinsics must be a specific type.
1247 return cast<Function>(
1248 M->getOrInsertFunction(Tys.empty() ? getName(id) : getName(id, Tys),
1249 getType(M->getContext(), id, Tys))
1250 .getCallee());
1251 }
1252
1253 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1254 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1255 #include "llvm/IR/IntrinsicImpl.inc"
1256 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1257
1258 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1259 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1260 #include "llvm/IR/IntrinsicImpl.inc"
1261 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1262
1263 using DeferredIntrinsicMatchPair =
1264 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1265
matchIntrinsicType(Type * Ty,ArrayRef<Intrinsic::IITDescriptor> & Infos,SmallVectorImpl<Type * > & ArgTys,SmallVectorImpl<DeferredIntrinsicMatchPair> & DeferredChecks,bool IsDeferredCheck)1266 static bool matchIntrinsicType(
1267 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1268 SmallVectorImpl<Type *> &ArgTys,
1269 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1270 bool IsDeferredCheck) {
1271 using namespace Intrinsic;
1272
1273 // If we ran out of descriptors, there are too many arguments.
1274 if (Infos.empty()) return true;
1275
1276 // Do this before slicing off the 'front' part
1277 auto InfosRef = Infos;
1278 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1279 DeferredChecks.emplace_back(T, InfosRef);
1280 return false;
1281 };
1282
1283 IITDescriptor D = Infos.front();
1284 Infos = Infos.slice(1);
1285
1286 switch (D.Kind) {
1287 case IITDescriptor::Void: return !Ty->isVoidTy();
1288 case IITDescriptor::VarArg: return true;
1289 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1290 case IITDescriptor::Token: return !Ty->isTokenTy();
1291 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1292 case IITDescriptor::Half: return !Ty->isHalfTy();
1293 case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1294 case IITDescriptor::Float: return !Ty->isFloatTy();
1295 case IITDescriptor::Double: return !Ty->isDoubleTy();
1296 case IITDescriptor::Quad: return !Ty->isFP128Ty();
1297 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1298 case IITDescriptor::Vector: {
1299 VectorType *VT = dyn_cast<VectorType>(Ty);
1300 return !VT || VT->getElementCount() != D.Vector_Width ||
1301 matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1302 DeferredChecks, IsDeferredCheck);
1303 }
1304 case IITDescriptor::Pointer: {
1305 PointerType *PT = dyn_cast<PointerType>(Ty);
1306 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1307 matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1308 DeferredChecks, IsDeferredCheck);
1309 }
1310
1311 case IITDescriptor::Struct: {
1312 StructType *ST = dyn_cast<StructType>(Ty);
1313 if (!ST || ST->getNumElements() != D.Struct_NumElements)
1314 return true;
1315
1316 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1317 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1318 DeferredChecks, IsDeferredCheck))
1319 return true;
1320 return false;
1321 }
1322
1323 case IITDescriptor::Argument:
1324 // If this is the second occurrence of an argument,
1325 // verify that the later instance matches the previous instance.
1326 if (D.getArgumentNumber() < ArgTys.size())
1327 return Ty != ArgTys[D.getArgumentNumber()];
1328
1329 if (D.getArgumentNumber() > ArgTys.size() ||
1330 D.getArgumentKind() == IITDescriptor::AK_MatchType)
1331 return IsDeferredCheck || DeferCheck(Ty);
1332
1333 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1334 "Table consistency error");
1335 ArgTys.push_back(Ty);
1336
1337 switch (D.getArgumentKind()) {
1338 case IITDescriptor::AK_Any: return false; // Success
1339 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1340 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1341 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1342 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1343 default: break;
1344 }
1345 llvm_unreachable("all argument kinds not covered");
1346
1347 case IITDescriptor::ExtendArgument: {
1348 // If this is a forward reference, defer the check for later.
1349 if (D.getArgumentNumber() >= ArgTys.size())
1350 return IsDeferredCheck || DeferCheck(Ty);
1351
1352 Type *NewTy = ArgTys[D.getArgumentNumber()];
1353 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1354 NewTy = VectorType::getExtendedElementVectorType(VTy);
1355 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1356 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1357 else
1358 return true;
1359
1360 return Ty != NewTy;
1361 }
1362 case IITDescriptor::TruncArgument: {
1363 // If this is a forward reference, defer the check for later.
1364 if (D.getArgumentNumber() >= ArgTys.size())
1365 return IsDeferredCheck || DeferCheck(Ty);
1366
1367 Type *NewTy = ArgTys[D.getArgumentNumber()];
1368 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1369 NewTy = VectorType::getTruncatedElementVectorType(VTy);
1370 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1371 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1372 else
1373 return true;
1374
1375 return Ty != NewTy;
1376 }
1377 case IITDescriptor::HalfVecArgument:
1378 // If this is a forward reference, defer the check for later.
1379 if (D.getArgumentNumber() >= ArgTys.size())
1380 return IsDeferredCheck || DeferCheck(Ty);
1381 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1382 VectorType::getHalfElementsVectorType(
1383 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1384 case IITDescriptor::SameVecWidthArgument: {
1385 if (D.getArgumentNumber() >= ArgTys.size()) {
1386 // Defer check and subsequent check for the vector element type.
1387 Infos = Infos.slice(1);
1388 return IsDeferredCheck || DeferCheck(Ty);
1389 }
1390 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1391 auto *ThisArgType = dyn_cast<VectorType>(Ty);
1392 // Both must be vectors of the same number of elements or neither.
1393 if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1394 return true;
1395 Type *EltTy = Ty;
1396 if (ThisArgType) {
1397 if (ReferenceType->getElementCount() !=
1398 ThisArgType->getElementCount())
1399 return true;
1400 EltTy = ThisArgType->getElementType();
1401 }
1402 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1403 IsDeferredCheck);
1404 }
1405 case IITDescriptor::PtrToArgument: {
1406 if (D.getArgumentNumber() >= ArgTys.size())
1407 return IsDeferredCheck || DeferCheck(Ty);
1408 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1409 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1410 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1411 }
1412 case IITDescriptor::PtrToElt: {
1413 if (D.getArgumentNumber() >= ArgTys.size())
1414 return IsDeferredCheck || DeferCheck(Ty);
1415 VectorType * ReferenceType =
1416 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1417 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1418
1419 return (!ThisArgType || !ReferenceType ||
1420 ThisArgType->getElementType() != ReferenceType->getElementType());
1421 }
1422 case IITDescriptor::VecOfAnyPtrsToElt: {
1423 unsigned RefArgNumber = D.getRefArgNumber();
1424 if (RefArgNumber >= ArgTys.size()) {
1425 if (IsDeferredCheck)
1426 return true;
1427 // If forward referencing, already add the pointer-vector type and
1428 // defer the checks for later.
1429 ArgTys.push_back(Ty);
1430 return DeferCheck(Ty);
1431 }
1432
1433 if (!IsDeferredCheck){
1434 assert(D.getOverloadArgNumber() == ArgTys.size() &&
1435 "Table consistency error");
1436 ArgTys.push_back(Ty);
1437 }
1438
1439 // Verify the overloaded type "matches" the Ref type.
1440 // i.e. Ty is a vector with the same width as Ref.
1441 // Composed of pointers to the same element type as Ref.
1442 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1443 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1444 if (!ThisArgVecTy || !ReferenceType ||
1445 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1446 return true;
1447 PointerType *ThisArgEltTy =
1448 dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1449 if (!ThisArgEltTy)
1450 return true;
1451 return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
1452 }
1453 case IITDescriptor::VecElementArgument: {
1454 if (D.getArgumentNumber() >= ArgTys.size())
1455 return IsDeferredCheck ? true : DeferCheck(Ty);
1456 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1457 return !ReferenceType || Ty != ReferenceType->getElementType();
1458 }
1459 case IITDescriptor::Subdivide2Argument:
1460 case IITDescriptor::Subdivide4Argument: {
1461 // If this is a forward reference, defer the check for later.
1462 if (D.getArgumentNumber() >= ArgTys.size())
1463 return IsDeferredCheck || DeferCheck(Ty);
1464
1465 Type *NewTy = ArgTys[D.getArgumentNumber()];
1466 if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1467 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1468 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1469 return Ty != NewTy;
1470 }
1471 return true;
1472 }
1473 case IITDescriptor::VecOfBitcastsToInt: {
1474 if (D.getArgumentNumber() >= ArgTys.size())
1475 return IsDeferredCheck || DeferCheck(Ty);
1476 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1477 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1478 if (!ThisArgVecTy || !ReferenceType)
1479 return true;
1480 return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1481 }
1482 }
1483 llvm_unreachable("unhandled");
1484 }
1485
1486 Intrinsic::MatchIntrinsicTypesResult
matchIntrinsicSignature(FunctionType * FTy,ArrayRef<Intrinsic::IITDescriptor> & Infos,SmallVectorImpl<Type * > & ArgTys)1487 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1488 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1489 SmallVectorImpl<Type *> &ArgTys) {
1490 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1491 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1492 false))
1493 return MatchIntrinsicTypes_NoMatchRet;
1494
1495 unsigned NumDeferredReturnChecks = DeferredChecks.size();
1496
1497 for (auto Ty : FTy->params())
1498 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1499 return MatchIntrinsicTypes_NoMatchArg;
1500
1501 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1502 DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1503 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1504 true))
1505 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1506 : MatchIntrinsicTypes_NoMatchArg;
1507 }
1508
1509 return MatchIntrinsicTypes_Match;
1510 }
1511
1512 bool
matchIntrinsicVarArg(bool isVarArg,ArrayRef<Intrinsic::IITDescriptor> & Infos)1513 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1514 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1515 // If there are no descriptors left, then it can't be a vararg.
1516 if (Infos.empty())
1517 return isVarArg;
1518
1519 // There should be only one descriptor remaining at this point.
1520 if (Infos.size() != 1)
1521 return true;
1522
1523 // Check and verify the descriptor.
1524 IITDescriptor D = Infos.front();
1525 Infos = Infos.slice(1);
1526 if (D.Kind == IITDescriptor::VarArg)
1527 return !isVarArg;
1528
1529 return true;
1530 }
1531
getIntrinsicSignature(Function * F,SmallVectorImpl<Type * > & ArgTys)1532 bool Intrinsic::getIntrinsicSignature(Function *F,
1533 SmallVectorImpl<Type *> &ArgTys) {
1534 Intrinsic::ID ID = F->getIntrinsicID();
1535 if (!ID)
1536 return false;
1537
1538 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1539 getIntrinsicInfoTableEntries(ID, Table);
1540 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1541
1542 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
1543 ArgTys) !=
1544 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1545 return false;
1546 }
1547 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
1548 TableRef))
1549 return false;
1550 return true;
1551 }
1552
remangleIntrinsicFunction(Function * F)1553 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1554 SmallVector<Type *, 4> ArgTys;
1555 if (!getIntrinsicSignature(F, ArgTys))
1556 return None;
1557
1558 Intrinsic::ID ID = F->getIntrinsicID();
1559 StringRef Name = F->getName();
1560 if (Name == Intrinsic::getName(ID, ArgTys))
1561 return None;
1562
1563 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1564 NewDecl->setCallingConv(F->getCallingConv());
1565 assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1566 "Shouldn't change the signature");
1567 return NewDecl;
1568 }
1569
1570 /// hasAddressTaken - returns true if there are any uses of this function
1571 /// other than direct calls or invokes to it. Optionally ignores callback
1572 /// uses.
hasAddressTaken(const User ** PutOffender,bool IgnoreCallbackUses) const1573 bool Function::hasAddressTaken(const User **PutOffender,
1574 bool IgnoreCallbackUses) const {
1575 for (const Use &U : uses()) {
1576 const User *FU = U.getUser();
1577 if (isa<BlockAddress>(FU))
1578 continue;
1579
1580 if (IgnoreCallbackUses) {
1581 AbstractCallSite ACS(&U);
1582 if (ACS && ACS.isCallbackCall())
1583 continue;
1584 }
1585
1586 const auto *Call = dyn_cast<CallBase>(FU);
1587 if (!Call) {
1588 if (PutOffender)
1589 *PutOffender = FU;
1590 return true;
1591 }
1592 if (!Call->isCallee(&U)) {
1593 if (PutOffender)
1594 *PutOffender = FU;
1595 return true;
1596 }
1597 }
1598 return false;
1599 }
1600
isDefTriviallyDead() const1601 bool Function::isDefTriviallyDead() const {
1602 // Check the linkage
1603 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1604 !hasAvailableExternallyLinkage())
1605 return false;
1606
1607 // Check if the function is used by anything other than a blockaddress.
1608 for (const User *U : users())
1609 if (!isa<BlockAddress>(U))
1610 return false;
1611
1612 return true;
1613 }
1614
1615 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1616 /// setjmp or other function that gcc recognizes as "returning twice".
callsFunctionThatReturnsTwice() const1617 bool Function::callsFunctionThatReturnsTwice() const {
1618 for (const Instruction &I : instructions(this))
1619 if (const auto *Call = dyn_cast<CallBase>(&I))
1620 if (Call->hasFnAttr(Attribute::ReturnsTwice))
1621 return true;
1622
1623 return false;
1624 }
1625
getPersonalityFn() const1626 Constant *Function::getPersonalityFn() const {
1627 assert(hasPersonalityFn() && getNumOperands());
1628 return cast<Constant>(Op<0>());
1629 }
1630
setPersonalityFn(Constant * Fn)1631 void Function::setPersonalityFn(Constant *Fn) {
1632 setHungoffOperand<0>(Fn);
1633 setValueSubclassDataBit(3, Fn != nullptr);
1634 }
1635
getPrefixData() const1636 Constant *Function::getPrefixData() const {
1637 assert(hasPrefixData() && getNumOperands());
1638 return cast<Constant>(Op<1>());
1639 }
1640
setPrefixData(Constant * PrefixData)1641 void Function::setPrefixData(Constant *PrefixData) {
1642 setHungoffOperand<1>(PrefixData);
1643 setValueSubclassDataBit(1, PrefixData != nullptr);
1644 }
1645
getPrologueData() const1646 Constant *Function::getPrologueData() const {
1647 assert(hasPrologueData() && getNumOperands());
1648 return cast<Constant>(Op<2>());
1649 }
1650
setPrologueData(Constant * PrologueData)1651 void Function::setPrologueData(Constant *PrologueData) {
1652 setHungoffOperand<2>(PrologueData);
1653 setValueSubclassDataBit(2, PrologueData != nullptr);
1654 }
1655
allocHungoffUselist()1656 void Function::allocHungoffUselist() {
1657 // If we've already allocated a uselist, stop here.
1658 if (getNumOperands())
1659 return;
1660
1661 allocHungoffUses(3, /*IsPhi=*/ false);
1662 setNumHungOffUseOperands(3);
1663
1664 // Initialize the uselist with placeholder operands to allow traversal.
1665 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1666 Op<0>().set(CPN);
1667 Op<1>().set(CPN);
1668 Op<2>().set(CPN);
1669 }
1670
1671 template <int Idx>
setHungoffOperand(Constant * C)1672 void Function::setHungoffOperand(Constant *C) {
1673 if (C) {
1674 allocHungoffUselist();
1675 Op<Idx>().set(C);
1676 } else if (getNumOperands()) {
1677 Op<Idx>().set(
1678 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1679 }
1680 }
1681
setValueSubclassDataBit(unsigned Bit,bool On)1682 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1683 assert(Bit < 16 && "SubclassData contains only 16 bits");
1684 if (On)
1685 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1686 else
1687 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1688 }
1689
setEntryCount(ProfileCount Count,const DenseSet<GlobalValue::GUID> * S)1690 void Function::setEntryCount(ProfileCount Count,
1691 const DenseSet<GlobalValue::GUID> *S) {
1692 assert(Count.hasValue());
1693 #if !defined(NDEBUG)
1694 auto PrevCount = getEntryCount();
1695 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1696 #endif
1697
1698 auto ImportGUIDs = getImportGUIDs();
1699 if (S == nullptr && ImportGUIDs.size())
1700 S = &ImportGUIDs;
1701
1702 MDBuilder MDB(getContext());
1703 setMetadata(
1704 LLVMContext::MD_prof,
1705 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1706 }
1707
setEntryCount(uint64_t Count,Function::ProfileCountType Type,const DenseSet<GlobalValue::GUID> * Imports)1708 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1709 const DenseSet<GlobalValue::GUID> *Imports) {
1710 setEntryCount(ProfileCount(Count, Type), Imports);
1711 }
1712
getEntryCount(bool AllowSynthetic) const1713 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1714 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1715 if (MD && MD->getOperand(0))
1716 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1717 if (MDS->getString().equals("function_entry_count")) {
1718 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1719 uint64_t Count = CI->getValue().getZExtValue();
1720 // A value of -1 is used for SamplePGO when there were no samples.
1721 // Treat this the same as unknown.
1722 if (Count == (uint64_t)-1)
1723 return ProfileCount::getInvalid();
1724 return ProfileCount(Count, PCT_Real);
1725 } else if (AllowSynthetic &&
1726 MDS->getString().equals("synthetic_function_entry_count")) {
1727 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1728 uint64_t Count = CI->getValue().getZExtValue();
1729 return ProfileCount(Count, PCT_Synthetic);
1730 }
1731 }
1732 return ProfileCount::getInvalid();
1733 }
1734
getImportGUIDs() const1735 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1736 DenseSet<GlobalValue::GUID> R;
1737 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1738 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1739 if (MDS->getString().equals("function_entry_count"))
1740 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1741 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1742 ->getValue()
1743 .getZExtValue());
1744 return R;
1745 }
1746
setSectionPrefix(StringRef Prefix)1747 void Function::setSectionPrefix(StringRef Prefix) {
1748 MDBuilder MDB(getContext());
1749 setMetadata(LLVMContext::MD_section_prefix,
1750 MDB.createFunctionSectionPrefix(Prefix));
1751 }
1752
getSectionPrefix() const1753 Optional<StringRef> Function::getSectionPrefix() const {
1754 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1755 assert(cast<MDString>(MD->getOperand(0))
1756 ->getString()
1757 .equals("function_section_prefix") &&
1758 "Metadata not match");
1759 return cast<MDString>(MD->getOperand(1))->getString();
1760 }
1761 return None;
1762 }
1763
nullPointerIsDefined() const1764 bool Function::nullPointerIsDefined() const {
1765 return hasFnAttribute(Attribute::NullPointerIsValid);
1766 }
1767
NullPointerIsDefined(const Function * F,unsigned AS)1768 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1769 if (F && F->nullPointerIsDefined())
1770 return true;
1771
1772 if (AS != 0)
1773 return true;
1774
1775 return false;
1776 }
1777