Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
14 pmbaty 1
//===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===//
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 contains the declaration of the Function class, which represents a
10
// single function/procedure in LLVM.
11
//
12
// A function basically consists of a list of basic blocks, a list of arguments,
13
// and a symbol table.
14
//
15
//===----------------------------------------------------------------------===//
16
 
17
#ifndef LLVM_IR_FUNCTION_H
18
#define LLVM_IR_FUNCTION_H
19
 
20
#include "llvm/ADT/DenseSet.h"
21
#include "llvm/ADT/StringRef.h"
22
#include "llvm/ADT/Twine.h"
23
#include "llvm/ADT/ilist_node.h"
24
#include "llvm/ADT/iterator_range.h"
25
#include "llvm/IR/Argument.h"
26
#include "llvm/IR/Attributes.h"
27
#include "llvm/IR/BasicBlock.h"
28
#include "llvm/IR/CallingConv.h"
29
#include "llvm/IR/DerivedTypes.h"
30
#include "llvm/IR/GlobalObject.h"
31
#include "llvm/IR/GlobalValue.h"
32
#include "llvm/IR/OperandTraits.h"
33
#include "llvm/IR/SymbolTableListTraits.h"
34
#include "llvm/IR/Value.h"
35
#include <cassert>
36
#include <cstddef>
37
#include <cstdint>
38
#include <memory>
39
#include <string>
40
 
41
namespace llvm {
42
 
43
namespace Intrinsic {
44
typedef unsigned ID;
45
}
46
 
47
class AssemblyAnnotationWriter;
48
class Constant;
49
struct DenormalMode;
50
class DISubprogram;
51
class LLVMContext;
52
class Module;
53
class raw_ostream;
54
class Type;
55
class User;
56
class BranchProbabilityInfo;
57
class BlockFrequencyInfo;
58
 
59
class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject,
60
                                          public ilist_node<Function> {
61
public:
62
  using BasicBlockListType = SymbolTableList<BasicBlock>;
63
 
64
  // BasicBlock iterators...
65
  using iterator = BasicBlockListType::iterator;
66
  using const_iterator = BasicBlockListType::const_iterator;
67
 
68
  using arg_iterator = Argument *;
69
  using const_arg_iterator = const Argument *;
70
 
71
private:
72
  // Important things that make up a function!
73
  BasicBlockListType BasicBlocks;         ///< The basic blocks
74
  mutable Argument *Arguments = nullptr;  ///< The formal arguments
75
  size_t NumArgs;
76
  std::unique_ptr<ValueSymbolTable>
77
      SymTab;                             ///< Symbol table of args/instructions
78
  AttributeList AttributeSets;            ///< Parameter attributes
79
 
80
  /*
81
   * Value::SubclassData
82
   *
83
   * bit 0      : HasLazyArguments
84
   * bit 1      : HasPrefixData
85
   * bit 2      : HasPrologueData
86
   * bit 3      : HasPersonalityFn
87
   * bits 4-13  : CallingConvention
88
   * bits 14    : HasGC
89
   * bits 15 : [reserved]
90
   */
91
 
92
  /// Bits from GlobalObject::GlobalObjectSubclassData.
93
  enum {
94
    /// Whether this function is materializable.
95
    IsMaterializableBit = 0,
96
  };
97
 
98
  friend class SymbolTableListTraits<Function>;
99
 
100
  /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
101
  /// built on demand, so that the list isn't allocated until the first client
102
  /// needs it.  The hasLazyArguments predicate returns true if the arg list
103
  /// hasn't been set up yet.
104
public:
105
  bool hasLazyArguments() const {
106
    return getSubclassDataFromValue() & (1<<0);
107
  }
108
 
109
private:
110
  void CheckLazyArguments() const {
111
    if (hasLazyArguments())
112
      BuildLazyArguments();
113
  }
114
 
115
  void BuildLazyArguments() const;
116
 
117
  void clearArguments();
118
 
119
  /// Function ctor - If the (optional) Module argument is specified, the
120
  /// function is automatically inserted into the end of the function list for
121
  /// the module.
122
  ///
123
  Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
124
           const Twine &N = "", Module *M = nullptr);
125
 
126
public:
127
  Function(const Function&) = delete;
128
  void operator=(const Function&) = delete;
129
  ~Function();
130
 
131
  // This is here to help easily convert from FunctionT * (Function * or
132
  // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling
133
  // FunctionT->getFunction().
134
  const Function &getFunction() const { return *this; }
135
 
136
  static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
137
                          unsigned AddrSpace, const Twine &N = "",
138
                          Module *M = nullptr) {
139
    return new Function(Ty, Linkage, AddrSpace, N, M);
140
  }
141
 
142
  // TODO: remove this once all users have been updated to pass an AddrSpace
143
  static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
144
                          const Twine &N = "", Module *M = nullptr) {
145
    return new Function(Ty, Linkage, static_cast<unsigned>(-1), N, M);
146
  }
147
 
148
  /// Creates a new function and attaches it to a module.
149
  ///
150
  /// Places the function in the program address space as specified
151
  /// by the module's data layout.
152
  static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
153
                          const Twine &N, Module &M);
154
 
155
  /// Creates a function with some attributes recorded in llvm.module.flags
156
  /// applied.
157
  ///
158
  /// Use this when synthesizing new functions that need attributes that would
159
  /// have been set by command line options.
160
  static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage,
161
                                         unsigned AddrSpace,
162
                                         const Twine &N = "",
163
                                         Module *M = nullptr);
164
 
165
  // Provide fast operand accessors.
166
  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
167
 
168
  /// Returns the number of non-debug IR instructions in this function.
169
  /// This is equivalent to the sum of the sizes of each basic block contained
170
  /// within this function.
171
  unsigned getInstructionCount() const;
172
 
173
  /// Returns the FunctionType for me.
174
  FunctionType *getFunctionType() const {
175
    return cast<FunctionType>(getValueType());
176
  }
177
 
178
  /// Returns the type of the ret val.
179
  Type *getReturnType() const { return getFunctionType()->getReturnType(); }
180
 
181
  /// getContext - Return a reference to the LLVMContext associated with this
182
  /// function.
183
  LLVMContext &getContext() const;
184
 
185
  /// isVarArg - Return true if this function takes a variable number of
186
  /// arguments.
187
  bool isVarArg() const { return getFunctionType()->isVarArg(); }
188
 
189
  bool isMaterializable() const {
190
    return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
191
  }
192
  void setIsMaterializable(bool V) {
193
    unsigned Mask = 1 << IsMaterializableBit;
194
    setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
195
                                (V ? Mask : 0u));
196
  }
197
 
198
  /// getIntrinsicID - This method returns the ID number of the specified
199
  /// function, or Intrinsic::not_intrinsic if the function is not an
200
  /// intrinsic, or if the pointer is null.  This value is always defined to be
201
  /// zero to allow easy checking for whether a function is intrinsic or not.
202
  /// The particular intrinsic functions which correspond to this value are
203
  /// defined in llvm/Intrinsics.h.
204
  Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
205
 
206
  /// isIntrinsic - Returns true if the function's name starts with "llvm.".
207
  /// It's possible for this function to return true while getIntrinsicID()
208
  /// returns Intrinsic::not_intrinsic!
209
  bool isIntrinsic() const { return HasLLVMReservedName; }
210
 
211
  /// isTargetIntrinsic - Returns true if IID is an intrinsic specific to a
212
  /// certain target. If it is a generic intrinsic false is returned.
213
  static bool isTargetIntrinsic(Intrinsic::ID IID);
214
 
215
  /// isTargetIntrinsic - Returns true if this function is an intrinsic and the
216
  /// intrinsic is specific to a certain target. If this is not an intrinsic
217
  /// or a generic intrinsic, false is returned.
218
  bool isTargetIntrinsic() const;
219
 
220
  /// Returns true if the function is one of the "Constrained Floating-Point
221
  /// Intrinsics". Returns false if not, and returns false when
222
  /// getIntrinsicID() returns Intrinsic::not_intrinsic.
223
  bool isConstrainedFPIntrinsic() const;
224
 
225
  static Intrinsic::ID lookupIntrinsicID(StringRef Name);
226
 
227
  /// Recalculate the ID for this function if it is an Intrinsic defined
228
  /// in llvm/Intrinsics.h.  Sets the intrinsic ID to Intrinsic::not_intrinsic
229
  /// if the name of this function does not match an intrinsic in that header.
230
  /// Note, this method does not need to be called directly, as it is called
231
  /// from Value::setName() whenever the name of this function changes.
232
  void recalculateIntrinsicID();
233
 
234
  /// getCallingConv()/setCallingConv(CC) - These method get and set the
235
  /// calling convention of this function.  The enum values for the known
236
  /// calling conventions are defined in CallingConv.h.
237
  CallingConv::ID getCallingConv() const {
238
    return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
239
                                        CallingConv::MaxID);
240
  }
241
  void setCallingConv(CallingConv::ID CC) {
242
    auto ID = static_cast<unsigned>(CC);
243
    assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
244
    setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
245
  }
246
 
247
  enum ProfileCountType { PCT_Real, PCT_Synthetic };
248
 
249
  /// Class to represent profile counts.
250
  ///
251
  /// This class represents both real and synthetic profile counts.
252
  class ProfileCount {
253
  private:
254
    uint64_t Count = 0;
255
    ProfileCountType PCT = PCT_Real;
256
 
257
  public:
258
    ProfileCount(uint64_t Count, ProfileCountType PCT)
259
        : Count(Count), PCT(PCT) {}
260
    uint64_t getCount() const { return Count; }
261
    ProfileCountType getType() const { return PCT; }
262
    bool isSynthetic() const { return PCT == PCT_Synthetic; }
263
  };
264
 
265
  /// Set the entry count for this function.
266
  ///
267
  /// Entry count is the number of times this function was executed based on
268
  /// pgo data. \p Imports points to a set of GUIDs that needs to
269
  /// be imported by the function for sample PGO, to enable the same inlines as
270
  /// the profiled optimized binary.
271
  void setEntryCount(ProfileCount Count,
272
                     const DenseSet<GlobalValue::GUID> *Imports = nullptr);
273
 
274
  /// A convenience wrapper for setting entry count
275
  void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real,
276
                     const DenseSet<GlobalValue::GUID> *Imports = nullptr);
277
 
278
  /// Get the entry count for this function.
279
  ///
280
  /// Entry count is the number of times the function was executed.
281
  /// When AllowSynthetic is false, only pgo_data will be returned.
282
  std::optional<ProfileCount> getEntryCount(bool AllowSynthetic = false) const;
283
 
284
  /// Return true if the function is annotated with profile data.
285
  ///
286
  /// Presence of entry counts from a profile run implies the function has
287
  /// profile annotations. If IncludeSynthetic is false, only return true
288
  /// when the profile data is real.
289
  bool hasProfileData(bool IncludeSynthetic = false) const {
290
    return getEntryCount(IncludeSynthetic).has_value();
291
  }
292
 
293
  /// Returns the set of GUIDs that needs to be imported to the function for
294
  /// sample PGO, to enable the same inlines as the profiled optimized binary.
295
  DenseSet<GlobalValue::GUID> getImportGUIDs() const;
296
 
297
  /// Set the section prefix for this function.
298
  void setSectionPrefix(StringRef Prefix);
299
 
300
  /// Get the section prefix for this function.
301
  std::optional<StringRef> getSectionPrefix() const;
302
 
303
  /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
304
  ///                             to use during code generation.
305
  bool hasGC() const {
306
    return getSubclassDataFromValue() & (1<<14);
307
  }
308
  const std::string &getGC() const;
309
  void setGC(std::string Str);
310
  void clearGC();
311
 
312
  /// Return the attribute list for this Function.
313
  AttributeList getAttributes() const { return AttributeSets; }
314
 
315
  /// Set the attribute list for this Function.
316
  void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
317
 
318
  // TODO: remove non-AtIndex versions of these methods.
319
  /// adds the attribute to the list of attributes.
320
  void addAttributeAtIndex(unsigned i, Attribute Attr);
321
 
322
  /// Add function attributes to this function.
323
  void addFnAttr(Attribute::AttrKind Kind);
324
 
325
  /// Add function attributes to this function.
326
  void addFnAttr(StringRef Kind, StringRef Val = StringRef());
327
 
328
  /// Add function attributes to this function.
329
  void addFnAttr(Attribute Attr);
330
 
331
  /// Add function attributes to this function.
332
  void addFnAttrs(const AttrBuilder &Attrs);
333
 
334
  /// Add return value attributes to this function.
335
  void addRetAttr(Attribute::AttrKind Kind);
336
 
337
  /// Add return value attributes to this function.
338
  void addRetAttr(Attribute Attr);
339
 
340
  /// Add return value attributes to this function.
341
  void addRetAttrs(const AttrBuilder &Attrs);
342
 
343
  /// adds the attribute to the list of attributes for the given arg.
344
  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
345
 
346
  /// adds the attribute to the list of attributes for the given arg.
347
  void addParamAttr(unsigned ArgNo, Attribute Attr);
348
 
349
  /// adds the attributes to the list of attributes for the given arg.
350
  void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs);
351
 
352
  /// removes the attribute from the list of attributes.
353
  void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind);
354
 
355
  /// removes the attribute from the list of attributes.
356
  void removeAttributeAtIndex(unsigned i, StringRef Kind);
357
 
358
  /// Remove function attributes from this function.
359
  void removeFnAttr(Attribute::AttrKind Kind);
360
 
361
  /// Remove function attribute from this function.
362
  void removeFnAttr(StringRef Kind);
363
 
364
  void removeFnAttrs(const AttributeMask &Attrs);
365
 
366
  /// removes the attribute from the return value list of attributes.
367
  void removeRetAttr(Attribute::AttrKind Kind);
368
 
369
  /// removes the attribute from the return value list of attributes.
370
  void removeRetAttr(StringRef Kind);
371
 
372
  /// removes the attributes from the return value list of attributes.
373
  void removeRetAttrs(const AttributeMask &Attrs);
374
 
375
  /// removes the attribute from the list of attributes.
376
  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
377
 
378
  /// removes the attribute from the list of attributes.
379
  void removeParamAttr(unsigned ArgNo, StringRef Kind);
380
 
381
  /// removes the attribute from the list of attributes.
382
  void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs);
383
 
384
  /// Return true if the function has the attribute.
385
  bool hasFnAttribute(Attribute::AttrKind Kind) const;
386
 
387
  /// Return true if the function has the attribute.
388
  bool hasFnAttribute(StringRef Kind) const;
389
 
390
  /// check if an attribute is in the list of attributes for the return value.
391
  bool hasRetAttribute(Attribute::AttrKind Kind) const;
392
 
393
  /// check if an attributes is in the list of attributes.
394
  bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
395
 
396
  /// gets the attribute from the list of attributes.
397
  Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const;
398
 
399
  /// gets the attribute from the list of attributes.
400
  Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const;
401
 
402
  /// Return the attribute for the given attribute kind.
403
  Attribute getFnAttribute(Attribute::AttrKind Kind) const;
404
 
405
  /// Return the attribute for the given attribute kind.
406
  Attribute getFnAttribute(StringRef Kind) const;
407
 
408
  /// For a string attribute \p Kind, parse attribute as an integer.
409
  ///
410
  /// \returns \p Default if attribute is not present.
411
  ///
412
  /// \returns \p Default if there is an error parsing the attribute integer,
413
  /// and error is emitted to the LLVMContext
414
  uint64_t getFnAttributeAsParsedInteger(StringRef Kind,
415
                                         uint64_t Default = 0) const;
416
 
417
  /// gets the specified attribute from the list of attributes.
418
  Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
419
 
420
  /// removes noundef and other attributes that imply undefined behavior if a
421
  /// `undef` or `poison` value is passed from the list of attributes.
422
  void removeParamUndefImplyingAttrs(unsigned ArgNo);
423
 
424
  /// Return the stack alignment for the function.
425
  MaybeAlign getFnStackAlign() const {
426
    return AttributeSets.getFnStackAlignment();
427
  }
428
 
429
  /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
430
  bool hasStackProtectorFnAttr() const;
431
 
432
  /// adds the dereferenceable attribute to the list of attributes for
433
  /// the given arg.
434
  void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes);
435
 
436
  /// adds the dereferenceable_or_null attribute to the list of
437
  /// attributes for the given arg.
438
  void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes);
439
 
440
  MaybeAlign getParamAlign(unsigned ArgNo) const {
441
    return AttributeSets.getParamAlignment(ArgNo);
442
  }
443
 
444
  MaybeAlign getParamStackAlign(unsigned ArgNo) const {
445
    return AttributeSets.getParamStackAlignment(ArgNo);
446
  }
447
 
448
  /// Extract the byval type for a parameter.
449
  Type *getParamByValType(unsigned ArgNo) const {
450
    return AttributeSets.getParamByValType(ArgNo);
451
  }
452
 
453
  /// Extract the sret type for a parameter.
454
  Type *getParamStructRetType(unsigned ArgNo) const {
455
    return AttributeSets.getParamStructRetType(ArgNo);
456
  }
457
 
458
  /// Extract the inalloca type for a parameter.
459
  Type *getParamInAllocaType(unsigned ArgNo) const {
460
    return AttributeSets.getParamInAllocaType(ArgNo);
461
  }
462
 
463
  /// Extract the byref type for a parameter.
464
  Type *getParamByRefType(unsigned ArgNo) const {
465
    return AttributeSets.getParamByRefType(ArgNo);
466
  }
467
 
468
  /// Extract the preallocated type for a parameter.
469
  Type *getParamPreallocatedType(unsigned ArgNo) const {
470
    return AttributeSets.getParamPreallocatedType(ArgNo);
471
  }
472
 
473
  /// Extract the number of dereferenceable bytes for a parameter.
474
  /// @param ArgNo Index of an argument, with 0 being the first function arg.
475
  uint64_t getParamDereferenceableBytes(unsigned ArgNo) const {
476
    return AttributeSets.getParamDereferenceableBytes(ArgNo);
477
  }
478
 
479
  /// Extract the number of dereferenceable_or_null bytes for a
480
  /// parameter.
481
  /// @param ArgNo AttributeList ArgNo, referring to an argument.
482
  uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const {
483
    return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo);
484
  }
485
 
486
  /// Determine if the function is presplit coroutine.
487
  bool isPresplitCoroutine() const {
488
    return hasFnAttribute(Attribute::PresplitCoroutine);
489
  }
490
  void setPresplitCoroutine() { addFnAttr(Attribute::PresplitCoroutine); }
491
  void setSplittedCoroutine() { removeFnAttr(Attribute::PresplitCoroutine); }
492
 
493
  MemoryEffects getMemoryEffects() const;
494
  void setMemoryEffects(MemoryEffects ME);
495
 
496
  /// Determine if the function does not access memory.
497
  bool doesNotAccessMemory() const;
498
  void setDoesNotAccessMemory();
499
 
500
  /// Determine if the function does not access or only reads memory.
501
  bool onlyReadsMemory() const;
502
  void setOnlyReadsMemory();
503
 
504
  /// Determine if the function does not access or only writes memory.
505
  bool onlyWritesMemory() const;
506
  void setOnlyWritesMemory();
507
 
508
  /// Determine if the call can access memmory only using pointers based
509
  /// on its arguments.
510
  bool onlyAccessesArgMemory() const;
511
  void setOnlyAccessesArgMemory();
512
 
513
  /// Determine if the function may only access memory that is
514
  ///  inaccessible from the IR.
515
  bool onlyAccessesInaccessibleMemory() const;
516
  void setOnlyAccessesInaccessibleMemory();
517
 
518
  /// Determine if the function may only access memory that is
519
  ///  either inaccessible from the IR or pointed to by its arguments.
520
  bool onlyAccessesInaccessibleMemOrArgMem() const;
521
  void setOnlyAccessesInaccessibleMemOrArgMem();
522
 
523
  /// Determine if the function cannot return.
524
  bool doesNotReturn() const {
525
    return hasFnAttribute(Attribute::NoReturn);
526
  }
527
  void setDoesNotReturn() {
528
    addFnAttr(Attribute::NoReturn);
529
  }
530
 
531
  /// Determine if the function should not perform indirect branch tracking.
532
  bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); }
533
 
534
  /// Determine if the function cannot unwind.
535
  bool doesNotThrow() const {
536
    return hasFnAttribute(Attribute::NoUnwind);
537
  }
538
  void setDoesNotThrow() {
539
    addFnAttr(Attribute::NoUnwind);
540
  }
541
 
542
  /// Determine if the call cannot be duplicated.
543
  bool cannotDuplicate() const {
544
    return hasFnAttribute(Attribute::NoDuplicate);
545
  }
546
  void setCannotDuplicate() {
547
    addFnAttr(Attribute::NoDuplicate);
548
  }
549
 
550
  /// Determine if the call is convergent.
551
  bool isConvergent() const {
552
    return hasFnAttribute(Attribute::Convergent);
553
  }
554
  void setConvergent() {
555
    addFnAttr(Attribute::Convergent);
556
  }
557
  void setNotConvergent() {
558
    removeFnAttr(Attribute::Convergent);
559
  }
560
 
561
  /// Determine if the call has sideeffects.
562
  bool isSpeculatable() const {
563
    return hasFnAttribute(Attribute::Speculatable);
564
  }
565
  void setSpeculatable() {
566
    addFnAttr(Attribute::Speculatable);
567
  }
568
 
569
  /// Determine if the call might deallocate memory.
570
  bool doesNotFreeMemory() const {
571
    return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree);
572
  }
573
  void setDoesNotFreeMemory() {
574
    addFnAttr(Attribute::NoFree);
575
  }
576
 
577
  /// Determine if the call can synchroize with other threads
578
  bool hasNoSync() const {
579
    return hasFnAttribute(Attribute::NoSync);
580
  }
581
  void setNoSync() {
582
    addFnAttr(Attribute::NoSync);
583
  }
584
 
585
  /// Determine if the function is known not to recurse, directly or
586
  /// indirectly.
587
  bool doesNotRecurse() const {
588
    return hasFnAttribute(Attribute::NoRecurse);
589
  }
590
  void setDoesNotRecurse() {
591
    addFnAttr(Attribute::NoRecurse);
592
  }
593
 
594
  /// Determine if the function is required to make forward progress.
595
  bool mustProgress() const {
596
    return hasFnAttribute(Attribute::MustProgress) ||
597
           hasFnAttribute(Attribute::WillReturn);
598
  }
599
  void setMustProgress() { addFnAttr(Attribute::MustProgress); }
600
 
601
  /// Determine if the function will return.
602
  bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); }
603
  void setWillReturn() { addFnAttr(Attribute::WillReturn); }
604
 
605
  /// Get what kind of unwind table entry to generate for this function.
606
  UWTableKind getUWTableKind() const {
607
    return AttributeSets.getUWTableKind();
608
  }
609
 
610
  /// True if the ABI mandates (or the user requested) that this
611
  /// function be in a unwind table.
612
  bool hasUWTable() const {
613
    return getUWTableKind() != UWTableKind::None;
614
  }
615
  void setUWTableKind(UWTableKind K) {
616
    addFnAttr(Attribute::getWithUWTableKind(getContext(), K));
617
  }
618
  /// True if this function needs an unwind table.
619
  bool needsUnwindTableEntry() const {
620
    return hasUWTable() || !doesNotThrow() || hasPersonalityFn();
621
  }
622
 
623
  /// Determine if the function returns a structure through first
624
  /// or second pointer argument.
625
  bool hasStructRetAttr() const {
626
    return AttributeSets.hasParamAttr(0, Attribute::StructRet) ||
627
           AttributeSets.hasParamAttr(1, Attribute::StructRet);
628
  }
629
 
630
  /// Determine if the parameter or return value is marked with NoAlias
631
  /// attribute.
632
  bool returnDoesNotAlias() const {
633
    return AttributeSets.hasRetAttr(Attribute::NoAlias);
634
  }
635
  void setReturnDoesNotAlias() { addRetAttr(Attribute::NoAlias); }
636
 
637
  /// Do not optimize this function (-O0).
638
  bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); }
639
 
640
  /// Optimize this function for minimum size (-Oz).
641
  bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); }
642
 
643
  /// Optimize this function for size (-Os) or minimum size (-Oz).
644
  bool hasOptSize() const {
645
    return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize();
646
  }
647
 
648
  /// Returns the denormal handling type for the default rounding mode of the
649
  /// function.
650
  DenormalMode getDenormalMode(const fltSemantics &FPType) const;
651
 
652
  /// copyAttributesFrom - copy all additional attributes (those not needed to
653
  /// create a Function) from the Function Src to this one.
654
  void copyAttributesFrom(const Function *Src);
655
 
656
  /// deleteBody - This method deletes the body of the function, and converts
657
  /// the linkage to external.
658
  ///
659
  void deleteBody() {
660
    dropAllReferences();
661
    setLinkage(ExternalLinkage);
662
  }
663
 
664
  /// removeFromParent - This method unlinks 'this' from the containing module,
665
  /// but does not delete it.
666
  ///
667
  void removeFromParent();
668
 
669
  /// eraseFromParent - This method unlinks 'this' from the containing module
670
  /// and deletes it.
671
  ///
672
  void eraseFromParent();
673
 
674
  /// Steal arguments from another function.
675
  ///
676
  /// Drop this function's arguments and splice in the ones from \c Src.
677
  /// Requires that this has no function body.
678
  void stealArgumentListFrom(Function &Src);
679
 
680
  /// Insert \p BB in the basic block list at \p Position. \Returns an iterator
681
  /// to the newly inserted BB.
682
  Function::iterator insert(Function::iterator Position, BasicBlock *BB) {
683
    return BasicBlocks.insert(Position, BB);
684
  }
685
 
686
  /// Transfer all blocks from \p FromF to this function at \p ToIt.
687
  void splice(Function::iterator ToIt, Function *FromF) {
688
    splice(ToIt, FromF, FromF->begin(), FromF->end());
689
  }
690
 
691
  /// Transfer one BasicBlock from \p FromF at \p FromIt to this function
692
  /// at \p ToIt.
693
  void splice(Function::iterator ToIt, Function *FromF,
694
              Function::iterator FromIt) {
695
    auto FromItNext = std::next(FromIt);
696
    // Single-element splice is a noop if destination == source.
697
    if (ToIt == FromIt || ToIt == FromItNext)
698
      return;
699
    splice(ToIt, FromF, FromIt, FromItNext);
700
  }
701
 
702
  /// Transfer a range of basic blocks that belong to \p FromF from \p
703
  /// FromBeginIt to \p FromEndIt, to this function at \p ToIt.
704
  void splice(Function::iterator ToIt, Function *FromF,
705
              Function::iterator FromBeginIt,
706
              Function::iterator FromEndIt);
707
 
708
  /// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt.
709
  /// \Returns \p ToIt.
710
  Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt);
711
 
712
private:
713
  // These need access to the underlying BB list.
714
  friend void BasicBlock::removeFromParent();
715
  friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent();
716
  template <class BB_t, class BB_i_t, class BI_t, class II_t>
717
  friend class InstIterator;
718
  friend class llvm::SymbolTableListTraits<llvm::BasicBlock>;
719
  friend class llvm::ilist_node_with_parent<llvm::BasicBlock, llvm::Function>;
720
 
721
  /// Get the underlying elements of the Function... the basic block list is
722
  /// empty for external functions.
723
  ///
724
  /// This is deliberately private because we have implemented an adequate set
725
  /// of functions to modify the list, including Function::splice(),
726
  /// Function::erase(), Function::insert() etc.
727
  const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
728
        BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
729
 
730
  static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
731
    return &Function::BasicBlocks;
732
  }
733
 
734
public:
735
  const BasicBlock       &getEntryBlock() const   { return front(); }
736
        BasicBlock       &getEntryBlock()         { return front(); }
737
 
738
  //===--------------------------------------------------------------------===//
739
  // Symbol Table Accessing functions...
740
 
741
  /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
742
  ///
743
  inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
744
  inline const ValueSymbolTable *getValueSymbolTable() const {
745
    return SymTab.get();
746
  }
747
 
748
  //===--------------------------------------------------------------------===//
749
  // BasicBlock iterator forwarding functions
750
  //
751
  iterator                begin()       { return BasicBlocks.begin(); }
752
  const_iterator          begin() const { return BasicBlocks.begin(); }
753
  iterator                end  ()       { return BasicBlocks.end();   }
754
  const_iterator          end  () const { return BasicBlocks.end();   }
755
 
756
  size_t                   size() const { return BasicBlocks.size();  }
757
  bool                    empty() const { return BasicBlocks.empty(); }
758
  const BasicBlock       &front() const { return BasicBlocks.front(); }
759
        BasicBlock       &front()       { return BasicBlocks.front(); }
760
  const BasicBlock        &back() const { return BasicBlocks.back();  }
761
        BasicBlock        &back()       { return BasicBlocks.back();  }
762
 
763
/// @name Function Argument Iteration
764
/// @{
765
 
766
  arg_iterator arg_begin() {
767
    CheckLazyArguments();
768
    return Arguments;
769
  }
770
  const_arg_iterator arg_begin() const {
771
    CheckLazyArguments();
772
    return Arguments;
773
  }
774
 
775
  arg_iterator arg_end() {
776
    CheckLazyArguments();
777
    return Arguments + NumArgs;
778
  }
779
  const_arg_iterator arg_end() const {
780
    CheckLazyArguments();
781
    return Arguments + NumArgs;
782
  }
783
 
784
  Argument* getArg(unsigned i) const {
785
    assert (i < NumArgs && "getArg() out of range!");
786
    CheckLazyArguments();
787
    return Arguments + i;
788
  }
789
 
790
  iterator_range<arg_iterator> args() {
791
    return make_range(arg_begin(), arg_end());
792
  }
793
  iterator_range<const_arg_iterator> args() const {
794
    return make_range(arg_begin(), arg_end());
795
  }
796
 
797
/// @}
798
 
799
  size_t arg_size() const { return NumArgs; }
800
  bool arg_empty() const { return arg_size() == 0; }
801
 
802
  /// Check whether this function has a personality function.
803
  bool hasPersonalityFn() const {
804
    return getSubclassDataFromValue() & (1<<3);
805
  }
806
 
807
  /// Get the personality function associated with this function.
808
  Constant *getPersonalityFn() const;
809
  void setPersonalityFn(Constant *Fn);
810
 
811
  /// Check whether this function has prefix data.
812
  bool hasPrefixData() const {
813
    return getSubclassDataFromValue() & (1<<1);
814
  }
815
 
816
  /// Get the prefix data associated with this function.
817
  Constant *getPrefixData() const;
818
  void setPrefixData(Constant *PrefixData);
819
 
820
  /// Check whether this function has prologue data.
821
  bool hasPrologueData() const {
822
    return getSubclassDataFromValue() & (1<<2);
823
  }
824
 
825
  /// Get the prologue data associated with this function.
826
  Constant *getPrologueData() const;
827
  void setPrologueData(Constant *PrologueData);
828
 
829
  /// Print the function to an output stream with an optional
830
  /// AssemblyAnnotationWriter.
831
  void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
832
             bool ShouldPreserveUseListOrder = false,
833
             bool IsForDebug = false) const;
834
 
835
  /// viewCFG - This function is meant for use from the debugger.  You can just
836
  /// say 'call F->viewCFG()' and a ghostview window should pop up from the
837
  /// program, displaying the CFG of the current function with the code for each
838
  /// basic block inside.  This depends on there being a 'dot' and 'gv' program
839
  /// in your path.
840
  ///
841
  void viewCFG() const;
842
 
843
  /// Extended form to print edge weights.
844
  void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
845
               const BranchProbabilityInfo *BPI) const;
846
 
847
  /// viewCFGOnly - This function is meant for use from the debugger.  It works
848
  /// just like viewCFG, but it does not include the contents of basic blocks
849
  /// into the nodes, just the label.  If you are only interested in the CFG
850
  /// this can make the graph smaller.
851
  ///
852
  void viewCFGOnly() const;
853
 
854
  /// Extended form to print edge weights.
855
  void viewCFGOnly(const BlockFrequencyInfo *BFI,
856
                   const BranchProbabilityInfo *BPI) const;
857
 
858
  /// Methods for support type inquiry through isa, cast, and dyn_cast:
859
  static bool classof(const Value *V) {
860
    return V->getValueID() == Value::FunctionVal;
861
  }
862
 
863
  /// dropAllReferences() - This method causes all the subinstructions to "let
864
  /// go" of all references that they are maintaining.  This allows one to
865
  /// 'delete' a whole module at a time, even though there may be circular
866
  /// references... first all references are dropped, and all use counts go to
867
  /// zero.  Then everything is deleted for real.  Note that no operations are
868
  /// valid on an object that has "dropped all references", except operator
869
  /// delete.
870
  ///
871
  /// Since no other object in the module can have references into the body of a
872
  /// function, dropping all references deletes the entire body of the function,
873
  /// including any contained basic blocks.
874
  ///
875
  void dropAllReferences();
876
 
877
  /// hasAddressTaken - returns true if there are any uses of this function
878
  /// other than direct calls or invokes to it, or blockaddress expressions.
879
  /// Optionally passes back an offending user for diagnostic purposes,
880
  /// ignores callback uses, assume like pointer annotation calls, references in
881
  /// llvm.used and llvm.compiler.used variables, and operand bundle
882
  /// "clang.arc.attachedcall".
883
  bool hasAddressTaken(const User ** = nullptr,
884
                       bool IgnoreCallbackUses = false,
885
                       bool IgnoreAssumeLikeCalls = true,
886
                       bool IngoreLLVMUsed = false,
887
                       bool IgnoreARCAttachedCall = false) const;
888
 
889
  /// isDefTriviallyDead - Return true if it is trivially safe to remove
890
  /// this function definition from the module (because it isn't externally
891
  /// visible, does not have its address taken, and has no callers).  To make
892
  /// this more accurate, call removeDeadConstantUsers first.
893
  bool isDefTriviallyDead() const;
894
 
895
  /// callsFunctionThatReturnsTwice - Return true if the function has a call to
896
  /// setjmp or other function that gcc recognizes as "returning twice".
897
  bool callsFunctionThatReturnsTwice() const;
898
 
899
  /// Set the attached subprogram.
900
  ///
901
  /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
902
  void setSubprogram(DISubprogram *SP);
903
 
904
  /// Get the attached subprogram.
905
  ///
906
  /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
907
  /// to \a DISubprogram.
908
  DISubprogram *getSubprogram() const;
909
 
910
  /// Returns true if we should emit debug info for profiling.
911
  bool shouldEmitDebugInfoForProfiling() const;
912
 
913
  /// Check if null pointer dereferencing is considered undefined behavior for
914
  /// the function.
915
  /// Return value: false => null pointer dereference is undefined.
916
  /// Return value: true =>  null pointer dereference is not undefined.
917
  bool nullPointerIsDefined() const;
918
 
919
private:
920
  void allocHungoffUselist();
921
  template<int Idx> void setHungoffOperand(Constant *C);
922
 
923
  /// Shadow Value::setValueSubclassData with a private forwarding method so
924
  /// that subclasses cannot accidentally use it.
925
  void setValueSubclassData(unsigned short D) {
926
    Value::setValueSubclassData(D);
927
  }
928
  void setValueSubclassDataBit(unsigned Bit, bool On);
929
};
930
 
931
/// Check whether null pointer dereferencing is considered undefined behavior
932
/// for a given function or an address space.
933
/// Null pointer access in non-zero address space is not considered undefined.
934
/// Return value: false => null pointer dereference is undefined.
935
/// Return value: true =>  null pointer dereference is not undefined.
936
bool NullPointerIsDefined(const Function *F, unsigned AS = 0);
937
 
938
template <>
939
struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
940
 
941
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
942
 
943
} // end namespace llvm
944
 
945
#endif // LLVM_IR_FUNCTION_H