LLVM 23.0.0git
ExpandVariadics.cpp
Go to the documentation of this file.
1//===-- ExpandVariadicsPass.cpp --------------------------------*- 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 is an optimization pass for variadic functions. If called from codegen,
10// it can serve as the implementation of variadic functions for a given target.
11//
12// The strategy is to turn the ... part of a variadic function into a va_list
13// and fix up the call sites. The majority of the pass is target independent.
14// The exceptions are the va_list type itself and the rules for where to store
15// variables in memory such that va_arg can iterate over them given a va_list.
16//
17// The majority of the plumbing is splitting the variadic function into a
18// single basic block that packs the variadic arguments into a va_list and
19// a second function that does the work of the original. That packing is
20// exactly what is done by va_start. Further, the transform from ... to va_list
21// replaced va_start with an operation to copy a va_list from the new argument,
22// which is exactly a va_copy. This is useful for reducing target-dependence.
23//
24// A va_list instance is a forward iterator, where the primary operation va_arg
25// is dereference-then-increment. This interface forces significant convergent
26// evolution between target specific implementations. The variation in runtime
27// data layout is limited to that representable by the iterator, parameterised
28// by the type passed to the va_arg instruction.
29//
30// Therefore the majority of the target specific subtlety is packing arguments
31// into a stack allocated buffer such that a va_list can be initialised with it
32// and the va_arg expansion for the target will find the arguments at runtime.
33//
34// The aggregate effect is to unblock other transforms, most critically the
35// general purpose inliner. Known calls to variadic functions become zero cost.
36//
37// Consistency with clang is primarily tested by emitting va_arg using clang
38// then expanding the variadic functions using this pass, followed by trying
39// to constant fold the functions to no-ops.
40//
41// Target specific behaviour is tested in IR - mainly checking that values are
42// put into positions in call frames that make sense for that particular target.
43//
44// There is one "clever" invariant in use. va_start intrinsics that are not
45// within a varidic functions are an error in the IR verifier. When this
46// transform moves blocks from a variadic function into a fixed arity one, it
47// moves va_start intrinsics along with everything else. That means that the
48// va_start intrinsics that need to be rewritten to use the trailing argument
49// are exactly those that are in non-variadic functions so no further state
50// is needed to distinguish those that need to be rewritten.
51//
52//===----------------------------------------------------------------------===//
53
55#include "llvm/ADT/Sequence.h"
58#include "llvm/IR/IRBuilder.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/PassManager.h"
63#include "llvm/Pass.h"
67
68#define DEBUG_TYPE "expand-variadics"
69
70using namespace llvm;
71
72namespace {
73
74cl::opt<ExpandVariadicsMode> ExpandVariadicsModeOption(
75 DEBUG_TYPE "-override", cl::desc("Override the behaviour of " DEBUG_TYPE),
78 "Use the implementation defaults"),
80 "Disable the pass entirely"),
82 "Optimise without changing ABI"),
84 "Change variadic calling convention")));
85
86bool commandLineOverride() {
87 return ExpandVariadicsModeOption != ExpandVariadicsMode::Unspecified;
88}
89
90// Instances of this class encapsulate the target-dependant behaviour as a
91// function of triple. Implementing a new ABI is adding a case to the switch
92// in create(llvm::Triple) at the end of this file.
93// This class may end up instantiated in TargetMachine instances, keeping it
94// here for now until enough targets are implemented for the API to evolve.
95class VariadicABIInfo {
96protected:
97 VariadicABIInfo() = default;
98
99public:
100 static std::unique_ptr<VariadicABIInfo> create(const Triple &T);
101
102 // Allow overriding whether the pass runs on a per-target basis
103 virtual bool enableForTarget() = 0;
104
105 // Whether a valist instance is passed by value or by address
106 // I.e. does it need to be alloca'ed and stored into, or can
107 // it be passed directly in a SSA register
108 virtual bool vaListPassedInSSARegister() = 0;
109
110 // The type of a va_list iterator object
111 virtual Type *vaListType(LLVMContext &Ctx) = 0;
112
113 // The type of a va_list as a function argument as lowered by C
114 virtual Type *vaListParameterType(Module &M) = 0;
115
116 // Initialize an allocated va_list object to point to an already
117 // initialized contiguous memory region.
118 // Return the value to pass as the va_list argument
119 virtual Value *initializeVaList(Module &M, LLVMContext &Ctx,
120 IRBuilder<> &Builder, AllocaInst *VaList,
121 Value *Buffer) = 0;
122
123 struct VAArgSlotInfo {
124 Align DataAlign; // With respect to the call frame
125 bool Indirect; // Passed via a pointer
126 };
127 virtual VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) = 0;
128
129 // Targets implemented so far all have the same trivial lowering for these
130 bool vaEndIsNop() { return true; }
131 bool vaCopyIsMemcpy() { return true; }
132
133 // Per-target overrides of special symbols.
134 virtual bool ignoreFunction(const Function *F) { return false; }
135
136 // Any additional address spaces used in va intrinsics that should be
137 // expanded.
138 virtual SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const {
139 return {};
140 }
141
142 virtual ~VariadicABIInfo() = default;
143};
144
145class ExpandVariadics : public ModulePass {
146
147 // The pass construction sets the default to optimize when called from middle
148 // end and lowering when called from the backend. The command line variable
149 // overrides that. This is useful for testing and debugging. It also allows
150 // building an applications with variadic functions wholly removed if one
151 // has sufficient control over the dependencies, e.g. a statically linked
152 // clang that has no variadic function calls remaining in the binary.
153
154public:
155 static char ID;
157 std::unique_ptr<VariadicABIInfo> ABI;
158
159 ExpandVariadics(ExpandVariadicsMode Mode)
160 : ModulePass(ID),
161 Mode(commandLineOverride() ? ExpandVariadicsModeOption : Mode) {}
162
163 StringRef getPassName() const override { return "Expand variadic functions"; }
164
165 bool rewriteABI() { return Mode == ExpandVariadicsMode::Lowering; }
166
167 template <typename T> bool isValidCallingConv(T *F) {
168 return F->getCallingConv() == CallingConv::C ||
169 F->getCallingConv() == CallingConv::SPIR_FUNC;
170 }
171
172 bool runOnModule(Module &M) override;
173
174 bool runOnFunction(Module &M, IRBuilder<> &Builder, Function *F);
175
176 Function *replaceAllUsesWithNewDeclaration(Module &M,
177 Function *OriginalFunction);
178
179 Function *deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
180 Function *OriginalFunction);
181
182 Function *defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
183 Function *VariadicWrapper,
184 Function *FixedArityReplacement);
185
186 bool expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB, FunctionType *,
187 Function *NF);
188
189 // The intrinsic functions va_copy and va_end are removed unconditionally.
190 // They correspond to a memcpy and a no-op on all implemented targets.
191 // The va_start intrinsic is removed from basic blocks that were not created
192 // by this pass, some may remain if needed to maintain the external ABI.
193
194 template <Intrinsic::ID ID, typename InstructionType>
195 bool expandIntrinsicUsers(Module &M, IRBuilder<> &Builder,
196 PointerType *IntrinsicArgType) {
197 bool Changed = false;
198 const DataLayout &DL = M.getDataLayout();
199 if (Function *Intrinsic =
200 Intrinsic::getDeclarationIfExists(&M, ID, {IntrinsicArgType})) {
201 for (User *U : make_early_inc_range(Intrinsic->users()))
202 if (auto *I = dyn_cast<InstructionType>(U))
203 Changed |= expandVAIntrinsicCall(Builder, DL, I);
204
205 if (Intrinsic->use_empty())
206 Intrinsic->eraseFromParent();
207 }
208 return Changed;
209 }
210
211 bool expandVAIntrinsicUsersWithAddrspace(Module &M, IRBuilder<> &Builder,
212 unsigned Addrspace) {
213 auto &Ctx = M.getContext();
214 PointerType *IntrinsicArgType = PointerType::get(Ctx, Addrspace);
215 bool Changed = false;
216
217 // expand vastart before vacopy as vastart may introduce a vacopy
218 Changed |= expandIntrinsicUsers<Intrinsic::vastart, VAStartInst>(
219 M, Builder, IntrinsicArgType);
220 Changed |= expandIntrinsicUsers<Intrinsic::vaend, VAEndInst>(
221 M, Builder, IntrinsicArgType);
222 Changed |= expandIntrinsicUsers<Intrinsic::vacopy, VACopyInst>(
223 M, Builder, IntrinsicArgType);
224 return Changed;
225 }
226
227 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
228 VAStartInst *Inst);
229
230 bool expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
231 VAEndInst *Inst);
232
233 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
234 VACopyInst *Inst);
235
236 bool expandVAArgInst(IRBuilder<> &Builder, const DataLayout &DL,
237 VAArgInst *Inst);
238
239 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy,
240 Type *ReturnType) {
241 // The type of "FTy" with the ... removed and a va_list appended
242 SmallVector<Type *> ArgTypes(FTy->params());
243 ArgTypes.push_back(ABI->vaListParameterType(M));
244 return FunctionType::get(ReturnType, ArgTypes, /*IsVarArgs=*/false);
245 }
246
247 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy) {
248 return inlinableVariadicFunctionType(M, FTy, FTy->getReturnType());
249 }
250
251 bool expansionApplicableToFunction(Module &M, Function *F) {
252 if (F->isIntrinsic() || !F->isVarArg() ||
253 F->hasFnAttribute(Attribute::Naked))
254 return false;
255
256 if (ABI->ignoreFunction(F))
257 return false;
258
259 if (!isValidCallingConv(F))
260 return false;
261
262 if (rewriteABI())
263 return true;
264
265 if (!F->hasExactDefinition())
266 return false;
267
268 return true;
269 }
270
271 bool expansionApplicableToFunctionCall(CallBase *CB) {
272 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
273 if (CI->isMustTailCall()) {
274 // Cannot expand musttail calls
275 return false;
276 }
277
278 if (!isValidCallingConv(CI))
279 return false;
280
281 return true;
282 }
283
284 if (isa<InvokeInst>(CB)) {
285 // Invoke not implemented in initial implementation of pass
286 return false;
287 }
288
289 // Other unimplemented derivative of CallBase
290 return false;
291 }
292
293 class ExpandedCallFrame {
294 // Helper for constructing an alloca instance containing the arguments bound
295 // to the variadic ... parameter, rearranged to allow indexing through a
296 // va_list iterator
297 enum { N = 4 };
298 SmallVector<Type *, N> FieldTypes;
299 enum Tag { Store, Memcpy, Padding };
301
302 template <Tag tag> void append(Type *FieldType, Value *V, uint64_t Bytes) {
303 FieldTypes.push_back(FieldType);
304 Source.push_back({V, Bytes, tag});
305 }
306
307 public:
308 void store(LLVMContext &Ctx, Type *T, Value *V) { append<Store>(T, V, 0); }
309
310 void memcpy(LLVMContext &Ctx, Type *T, Value *V, uint64_t Bytes) {
311 append<Memcpy>(T, V, Bytes);
312 }
313
314 void padding(LLVMContext &Ctx, uint64_t By) {
315 append<Padding>(ArrayType::get(Type::getInt8Ty(Ctx), By), nullptr, 0);
316 }
317
318 size_t size() const { return FieldTypes.size(); }
319 bool empty() const { return FieldTypes.empty(); }
320
321 StructType *asStruct(LLVMContext &Ctx, StringRef Name) {
322 const bool IsPacked = true;
323 return StructType::create(Ctx, FieldTypes,
324 (Twine(Name) + ".vararg").str(), IsPacked);
325 }
326
327 void initializeStructAlloca(const DataLayout &DL, IRBuilder<> &Builder,
328 AllocaInst *Alloced, StructType *VarargsTy) {
329
330 for (size_t I = 0; I < size(); I++) {
331
332 auto [V, bytes, tag] = Source[I];
333
334 if (tag == Padding) {
335 assert(V == nullptr);
336 continue;
337 }
338
339 auto Dst = Builder.CreateStructGEP(VarargsTy, Alloced, I);
340
341 assert(V != nullptr);
342
343 if (tag == Store)
344 Builder.CreateStore(V, Dst);
345
346 if (tag == Memcpy)
347 Builder.CreateMemCpy(Dst, {}, V, {}, bytes);
348 }
349 }
350 };
351};
352
353bool ExpandVariadics::runOnModule(Module &M) {
354 bool Changed = false;
356 return Changed;
357
358 Triple TT(M.getTargetTriple());
359 ABI = VariadicABIInfo::create(TT);
360 if (!ABI)
361 return Changed;
362
363 if (!ABI->enableForTarget())
364 return Changed;
365
366 auto &Ctx = M.getContext();
367 const DataLayout &DL = M.getDataLayout();
368 IRBuilder<> Builder(Ctx);
369
370 // Lowering needs to run on all functions exactly once.
371 // Optimize could run on functions containing va_start exactly once.
373 Changed |= runOnFunction(M, Builder, &F);
374
375 // After runOnFunction, all known calls to known variadic functions have been
376 // replaced. va_start intrinsics are presently (and invalidly!) only present
377 // in functions that used to be variadic and have now been replaced to take a
378 // va_list instead. If lowering as opposed to optimising, calls to unknown
379 // variadic functions have also been replaced.
380
381 {
382 unsigned Addrspace = 0;
383 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
384
385 Addrspace = DL.getAllocaAddrSpace();
386 if (Addrspace != 0)
387 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
388
389 // Process any addrspaces targets declare to be important.
390 const SmallVector<unsigned> &TargetASVec =
391 ABI->getTargetSpecificVaIntrinAddrSpaces();
392 for (unsigned TargetAS : TargetASVec) {
393 if (TargetAS == 0 || TargetAS == DL.getAllocaAddrSpace())
394 continue;
395 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, TargetAS);
396 }
397 }
398
400 return Changed;
401
402 for (Function &F : make_early_inc_range(M)) {
403 if (F.isDeclaration())
404 continue;
405
406 // Now need to track down indirect calls and va_arg instructions. Can't find
407 // those by walking uses of variadic functions, need to crawl the
408 // instruction stream. Fortunately this is only necessary for the ABI
409 // rewrite case.
410 for (BasicBlock &BB : F) {
411 for (Instruction &I : make_early_inc_range(BB)) {
412 if (auto *VA = dyn_cast<VAArgInst>(&I)) {
413 Changed |= expandVAArgInst(Builder, DL, VA);
414 } else if (CallBase *CB = dyn_cast<CallBase>(&I)) {
415 if (CB->isIndirectCall()) {
416 FunctionType *FTy = CB->getFunctionType();
417 if (FTy->isVarArg())
418 Changed |= expandCall(M, Builder, CB, FTy, /*NF=*/nullptr);
419 }
420 }
421 }
422 }
423 }
424
425 return Changed;
426}
427
428bool ExpandVariadics::runOnFunction(Module &M, IRBuilder<> &Builder,
429 Function *OriginalFunction) {
430 bool Changed = false;
431
432 if (!expansionApplicableToFunction(M, OriginalFunction))
433 return Changed;
434
435 [[maybe_unused]] const bool OriginalFunctionIsDeclaration =
436 OriginalFunction->isDeclaration();
437 assert(rewriteABI() || !OriginalFunctionIsDeclaration);
438
439 // Declare a new function and redirect every use to that new function
440 Function *VariadicWrapper =
441 replaceAllUsesWithNewDeclaration(M, OriginalFunction);
442 assert(VariadicWrapper->isDeclaration());
443 assert(OriginalFunction->use_empty());
444
445 // Create a new function taking va_list containing the implementation of the
446 // original
447 Function *FixedArityReplacement =
448 deriveFixedArityReplacement(M, Builder, OriginalFunction);
449 assert(OriginalFunction->isDeclaration());
450 assert(FixedArityReplacement->isDeclaration() ==
451 OriginalFunctionIsDeclaration);
452 assert(VariadicWrapper->isDeclaration());
453
454 // Create a single block forwarding wrapper that turns a ... into a va_list
455 [[maybe_unused]] Function *VariadicWrapperDefine =
456 defineVariadicWrapper(M, Builder, VariadicWrapper, FixedArityReplacement);
457 assert(VariadicWrapperDefine == VariadicWrapper);
458 assert(!VariadicWrapper->isDeclaration());
459
460 // Add the prof metadata from the original function to the wrapper. Because
461 // FixedArityReplacement is the owner of original function's prof metadata
462 // after the splice, we need to transfer it to VariadicWrapper.
463 VariadicWrapper->setMetadata(
464 LLVMContext::MD_prof,
465 FixedArityReplacement->getMetadata(LLVMContext::MD_prof));
466
467 // We now have:
468 // 1. the original function, now as a declaration with no uses
469 // 2. a variadic function that unconditionally calls a fixed arity replacement
470 // 3. a fixed arity function equivalent to the original function
471
472 // Replace known calls to the variadic with calls to the va_list equivalent
473 for (User *U : make_early_inc_range(VariadicWrapper->users())) {
474 if (CallBase *CB = dyn_cast<CallBase>(U)) {
475 Value *CalledOperand = CB->getCalledOperand();
476 if (VariadicWrapper == CalledOperand)
477 Changed |=
478 expandCall(M, Builder, CB, VariadicWrapper->getFunctionType(),
479 FixedArityReplacement);
480 }
481 }
482
483 // The original function will be erased.
484 // One of the two new functions will become a replacement for the original.
485 // When preserving the ABI, the other is an internal implementation detail.
486 // When rewriting the ABI, RAUW then the variadic one.
487 Function *const ExternallyAccessible =
488 rewriteABI() ? FixedArityReplacement : VariadicWrapper;
489 Function *const InternalOnly =
490 rewriteABI() ? VariadicWrapper : FixedArityReplacement;
491
492 // The external function is the replacement for the original
493 ExternallyAccessible->setLinkage(OriginalFunction->getLinkage());
494 ExternallyAccessible->setVisibility(OriginalFunction->getVisibility());
495 ExternallyAccessible->setComdat(OriginalFunction->getComdat());
496 ExternallyAccessible->takeName(OriginalFunction);
497
498 // Annotate the internal one as internal
501
502 // The original is unused and obsolete
503 OriginalFunction->eraseFromParent();
504
505 InternalOnly->removeDeadConstantUsers();
506
507 if (rewriteABI()) {
508 // All known calls to the function have been removed by expandCall
509 // Resolve everything else by replaceAllUsesWith
510 VariadicWrapper->replaceAllUsesWith(FixedArityReplacement);
511 VariadicWrapper->eraseFromParent();
512 }
513
514 return Changed;
515}
516
517Function *
518ExpandVariadics::replaceAllUsesWithNewDeclaration(Module &M,
519 Function *OriginalFunction) {
520 auto &Ctx = M.getContext();
521 Function &F = *OriginalFunction;
522 FunctionType *FTy = F.getFunctionType();
523 Function *NF = Function::Create(FTy, F.getLinkage(), F.getAddressSpace());
524
525 NF->setName(F.getName() + ".varargs");
526
527 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
528
529 AttrBuilder ParamAttrs(Ctx);
530 AttributeList Attrs = NF->getAttributes();
531 Attrs = Attrs.addParamAttributes(Ctx, FTy->getNumParams(), ParamAttrs);
532 NF->setAttributes(Attrs);
533
534 OriginalFunction->replaceAllUsesWith(NF);
535 return NF;
536}
537
538Function *
539ExpandVariadics::deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
540 Function *OriginalFunction) {
541 Function &F = *OriginalFunction;
542 // The purpose here is split the variadic function F into two functions
543 // One is a variadic function that bundles the passed argument into a va_list
544 // and passes it to the second function. The second function does whatever
545 // the original F does, except that it takes a va_list instead of the ...
546
547 assert(expansionApplicableToFunction(M, &F));
548
549 auto &Ctx = M.getContext();
550
551 // Returned value isDeclaration() is equal to F.isDeclaration()
552 // but that property is not invariant throughout this function
553 const bool FunctionIsDefinition = !F.isDeclaration();
554
555 FunctionType *FTy = F.getFunctionType();
556 SmallVector<Type *> ArgTypes(FTy->params());
557 ArgTypes.push_back(ABI->vaListParameterType(M));
558
559 FunctionType *NFTy = inlinableVariadicFunctionType(M, FTy);
560 Function *NF = Function::Create(NFTy, F.getLinkage(), F.getAddressSpace());
561
562 // Note - same attribute handling as DeadArgumentElimination
563 NF->copyAttributesFrom(&F);
564 NF->setComdat(F.getComdat());
565 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
566 NF->setName(F.getName() + ".valist");
567
568 AttrBuilder ParamAttrs(Ctx);
569
570 AttributeList Attrs = NF->getAttributes();
571 Attrs = Attrs.addParamAttributes(Ctx, NFTy->getNumParams() - 1, ParamAttrs);
572 NF->setAttributes(Attrs);
573
574 // Splice the implementation into the new function with minimal changes
575 if (FunctionIsDefinition) {
576 NF->splice(NF->begin(), &F);
577
578 auto NewArg = NF->arg_begin();
579 for (Argument &Arg : F.args()) {
580 Arg.replaceAllUsesWith(NewArg);
581 NewArg->setName(Arg.getName()); // takeName without killing the old one
582 ++NewArg;
583 }
584 NewArg->setName("varargs");
585 }
586
588 F.getAllMetadata(MDs);
589 for (auto [KindID, Node] : MDs)
590 NF->addMetadata(KindID, *Node);
591 F.clearMetadata();
592
593 return NF;
594}
595
596Function *
597ExpandVariadics::defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
598 Function *VariadicWrapper,
599 Function *FixedArityReplacement) {
600 auto &Ctx = Builder.getContext();
601 const DataLayout &DL = M.getDataLayout();
602 assert(VariadicWrapper->isDeclaration());
603 Function &F = *VariadicWrapper;
604
605 assert(F.isDeclaration());
606 Type *VaListTy = ABI->vaListType(Ctx);
607
608 auto *BB = BasicBlock::Create(Ctx, "entry", &F);
609 Builder.SetInsertPoint(BB);
610
611 AllocaInst *VaListInstance =
612 Builder.CreateAlloca(VaListTy, nullptr, "va_start");
613
614 Builder.CreateLifetimeStart(VaListInstance);
615
616 Builder.CreateIntrinsic(Intrinsic::vastart, {DL.getAllocaPtrType(Ctx)},
617 {VaListInstance});
618
620
621 Type *ParameterType = ABI->vaListParameterType(M);
622 if (ABI->vaListPassedInSSARegister())
623 Args.push_back(Builder.CreateLoad(ParameterType, VaListInstance));
624 else
625 Args.push_back(Builder.CreateAddrSpaceCast(VaListInstance, ParameterType));
626
627 CallInst *Result = Builder.CreateCall(FixedArityReplacement, Args);
628
629 Builder.CreateIntrinsic(Intrinsic::vaend, {DL.getAllocaPtrType(Ctx)},
630 {VaListInstance});
631 Builder.CreateLifetimeEnd(VaListInstance);
632
633 if (Result->getType()->isVoidTy())
634 Builder.CreateRetVoid();
635 else
636 Builder.CreateRet(Result);
637
638 return VariadicWrapper;
639}
640
641bool ExpandVariadics::expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB,
642 FunctionType *VarargFunctionType,
643 Function *NF) {
644 bool Changed = false;
645 const DataLayout &DL = M.getDataLayout();
646
647 if (ABI->ignoreFunction(CB->getCalledFunction()))
648 return Changed;
649
650 if (!expansionApplicableToFunctionCall(CB)) {
651 if (rewriteABI())
652 report_fatal_error("Cannot lower callbase instruction");
653 return Changed;
654 }
655
656 // This is tricky. The call instruction's function type might not match
657 // the type of the caller. When optimising, can leave it unchanged.
658 // Webassembly detects that inconsistency and repairs it.
659 if (CB->getFunctionType() != VarargFunctionType)
660 if (!rewriteABI())
661 return Changed;
662
663 auto &Ctx = CB->getContext();
664
665 Align MaxFieldAlign(1);
666
667 // The strategy is to allocate a call frame containing the variadic
668 // arguments laid out such that a target specific va_list can be initialized
669 // with it, such that target specific va_arg instructions will correctly
670 // iterate over it. This means getting the alignment right and sometimes
671 // embedding a pointer to the value instead of embedding the value itself.
672
673 Function *CBF = CB->getParent()->getParent();
674
675 ExpandedCallFrame Frame;
676
677 uint64_t CurrentOffset = 0;
678
679 for (unsigned I : seq(VarargFunctionType->getNumParams(), CB->arg_size())) {
680 Value *ArgVal = CB->getArgOperand(I);
681 const bool IsByVal = CB->paramHasAttr(I, Attribute::ByVal);
682 const bool IsByRef = CB->paramHasAttr(I, Attribute::ByRef);
683
684 // The type of the value being passed, decoded from byval/byref metadata if
685 // required
686 Type *const UnderlyingType = IsByVal ? CB->getParamByValType(I)
687 : IsByRef ? CB->getParamByRefType(I)
688 : ArgVal->getType();
689 const uint64_t UnderlyingSize =
690 DL.getTypeAllocSize(UnderlyingType).getFixedValue();
691
692 // The type to be written into the call frame
693 Type *FrameFieldType = UnderlyingType;
694
695 // The value to copy from when initialising the frame alloca
696 Value *SourceValue = ArgVal;
697
698 VariadicABIInfo::VAArgSlotInfo SlotInfo = ABI->slotInfo(DL, UnderlyingType);
699
700 if (SlotInfo.Indirect) {
701 // The va_arg lowering loads through a pointer. Set up an alloca to aim
702 // that pointer at.
703 Builder.SetInsertPointPastAllocas(CBF);
704 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
705 Value *CallerCopy =
706 Builder.CreateAlloca(UnderlyingType, nullptr, "IndirectAlloca");
707
708 Builder.SetInsertPoint(CB);
709 if (IsByVal)
710 Builder.CreateMemCpy(CallerCopy, {}, ArgVal, {}, UnderlyingSize);
711 else
712 Builder.CreateStore(ArgVal, CallerCopy);
713
714 // Indirection now handled, pass the alloca ptr by value
715 FrameFieldType = DL.getAllocaPtrType(Ctx);
716 SourceValue = CallerCopy;
717 }
718
719 // Alignment of the value within the frame
720 // This probably needs to be controllable as a function of type
721 Align DataAlign = SlotInfo.DataAlign;
722
723 MaxFieldAlign = std::max(MaxFieldAlign, DataAlign);
724
725 uint64_t DataAlignV = DataAlign.value();
726 if (uint64_t Rem = CurrentOffset % DataAlignV) {
727 // Inject explicit padding to deal with alignment requirements
728 uint64_t Padding = DataAlignV - Rem;
729 Frame.padding(Ctx, Padding);
730 CurrentOffset += Padding;
731 }
732
733 if (SlotInfo.Indirect) {
734 Frame.store(Ctx, FrameFieldType, SourceValue);
735 } else {
736 if (IsByVal)
737 Frame.memcpy(Ctx, FrameFieldType, SourceValue, UnderlyingSize);
738 else
739 Frame.store(Ctx, FrameFieldType, SourceValue);
740 }
741
742 CurrentOffset += DL.getTypeAllocSize(FrameFieldType).getFixedValue();
743 }
744
745 if (Frame.empty()) {
746 // Not passing any arguments, hopefully va_arg won't try to read any
747 // Creating a single byte frame containing nothing to point the va_list
748 // instance as that is less special-casey in the compiler and probably
749 // easier to interpret in a debugger.
750 Frame.padding(Ctx, 1);
751 }
752
753 StructType *VarargsTy = Frame.asStruct(Ctx, CBF->getName());
754
755 // The struct instance needs to be at least MaxFieldAlign for the alignment of
756 // the fields to be correct at runtime. Use the native stack alignment instead
757 // if that's greater as that tends to give better codegen.
758 // This is an awkward way to guess whether there is a known stack alignment
759 // without hitting an assert in DL.getStackAlignment, 1024 is an arbitrary
760 // number likely to be greater than the natural stack alignment.
761 Align AllocaAlign = MaxFieldAlign;
762 if (MaybeAlign StackAlign = DL.getStackAlignment();
763 StackAlign && *StackAlign > AllocaAlign)
764 AllocaAlign = *StackAlign;
765
766 // Put the alloca to hold the variadic args in the entry basic block.
767 Builder.SetInsertPointPastAllocas(CBF);
768
769 // SetCurrentDebugLocation when the builder SetInsertPoint method does not
770 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
771
772 // The awkward construction here is to set the alignment on the instance
773 AllocaInst *Alloced = Builder.Insert(
774 new AllocaInst(VarargsTy, DL.getAllocaAddrSpace(), nullptr, AllocaAlign),
775 "vararg_buffer");
776 Changed = true;
777 assert(Alloced->getAllocatedType() == VarargsTy);
778
779 // Initialize the fields in the struct
780 Builder.SetInsertPoint(CB);
781 Builder.CreateLifetimeStart(Alloced);
782 Frame.initializeStructAlloca(DL, Builder, Alloced, VarargsTy);
783
784 const unsigned NumArgs = VarargFunctionType->getNumParams();
785 SmallVector<Value *> Args(CB->arg_begin(), CB->arg_begin() + NumArgs);
786
787 // Initialize a va_list pointing to that struct and pass it as the last
788 // argument
789 AllocaInst *VaList = nullptr;
790 {
791 if (!ABI->vaListPassedInSSARegister()) {
792 Type *VaListTy = ABI->vaListType(Ctx);
793 Builder.SetInsertPointPastAllocas(CBF);
794 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
795 VaList = Builder.CreateAlloca(VaListTy, nullptr, "va_argument");
796 Builder.SetInsertPoint(CB);
797 Builder.CreateLifetimeStart(VaList);
798 }
799 Builder.SetInsertPoint(CB);
800 Args.push_back(ABI->initializeVaList(M, Ctx, Builder, VaList, Alloced));
801 }
802
803 // Attributes excluding any on the vararg arguments
804 AttributeList PAL = CB->getAttributes();
805 if (!PAL.isEmpty()) {
807 for (unsigned ArgNo = 0; ArgNo < NumArgs; ArgNo++)
808 ArgAttrs.push_back(PAL.getParamAttrs(ArgNo));
809 PAL =
810 AttributeList::get(Ctx, PAL.getFnAttrs(), PAL.getRetAttrs(), ArgAttrs);
811 }
812
814 CB->getOperandBundlesAsDefs(OpBundles);
815
816 CallBase *NewCB = nullptr;
817
818 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
819 Value *Dst = NF ? NF : CI->getCalledOperand();
820 // Use the type of the call site rather than the function type to ensure
821 // RAUW succeeds in the case of a mismatching return type.
822 FunctionType *NFTy =
823 inlinableVariadicFunctionType(M, VarargFunctionType, CB->getType());
824
825 NewCB = CallInst::Create(NFTy, Dst, Args, OpBundles, "", CI->getIterator());
826
827 CallInst::TailCallKind TCK = CI->getTailCallKind();
829
830 // Can't tail call a function that is being passed a pointer to an alloca
831 if (TCK == CallInst::TCK_Tail)
832 TCK = CallInst::TCK_None;
833 CI->setTailCallKind(TCK);
834
835 } else {
836 llvm_unreachable("Unreachable when !expansionApplicableToFunctionCall()");
837 }
838
839 if (VaList)
840 Builder.CreateLifetimeEnd(VaList);
841
842 Builder.CreateLifetimeEnd(Alloced);
843
844 NewCB->setAttributes(PAL);
845 NewCB->takeName(CB);
846 NewCB->setCallingConv(CB->getCallingConv());
847 NewCB->setDebugLoc(DebugLoc());
848
849 // DeadArgElim and ArgPromotion copy exactly this metadata
850 NewCB->copyMetadata(*CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
851
852 CB->replaceAllUsesWith(NewCB);
853 CB->eraseFromParent();
854 return Changed;
855}
856
857bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
858 const DataLayout &DL,
859 VAStartInst *Inst) {
860 // Only removing va_start instructions that are not in variadic functions.
861 // Those would be rejected by the IR verifier before this pass.
862 // After splicing basic blocks from a variadic function into a fixed arity
863 // one the va_start that used to refer to the ... parameter still exist.
864 // There are also variadic functions that this pass did not change and
865 // va_start instances in the created single block wrapper functions.
866 // Replace exactly the instances in non-variadic functions as those are
867 // the ones to be fixed up to use the va_list passed as the final argument.
868
869 Function *ContainingFunction = Inst->getFunction();
870 if (ContainingFunction->isVarArg()) {
871 return false;
872 }
873
874 // The last argument is a vaListParameterType, either a va_list
875 // or a pointer to one depending on the target.
876 bool PassedByValue = ABI->vaListPassedInSSARegister();
877 Argument *PassedVaList =
878 ContainingFunction->getArg(ContainingFunction->arg_size() - 1);
879
880 // va_start takes a pointer to a va_list, e.g. one on the stack
881 Value *VaStartArg = Inst->getArgList();
882
883 Builder.SetInsertPoint(Inst);
884
885 if (PassedByValue) {
886 // The general thing to do is create an alloca, store the va_list argument
887 // to it, then create a va_copy. When vaCopyIsMemcpy(), this optimises to a
888 // store to the VaStartArg.
889 assert(ABI->vaCopyIsMemcpy());
890 Builder.CreateStore(PassedVaList, VaStartArg);
891 } else {
892
893 // Otherwise emit a vacopy to pick up target-specific handling if any
894 auto &Ctx = Builder.getContext();
895
896 Builder.CreateIntrinsic(Intrinsic::vacopy, {DL.getAllocaPtrType(Ctx)},
897 {VaStartArg, PassedVaList});
898 }
899
900 Inst->eraseFromParent();
901 return true;
902}
903
904bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
905 VAEndInst *Inst) {
906 assert(ABI->vaEndIsNop());
907 Inst->eraseFromParent();
908 return true;
909}
910
911bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
912 const DataLayout &DL,
913 VACopyInst *Inst) {
914 assert(ABI->vaCopyIsMemcpy());
915 Builder.SetInsertPoint(Inst);
916
917 auto &Ctx = Builder.getContext();
918 Type *VaListTy = ABI->vaListType(Ctx);
919 uint64_t Size = DL.getTypeAllocSize(VaListTy).getFixedValue();
920
921 Builder.CreateMemCpy(Inst->getDest(), {}, Inst->getSrc(), {},
922 Builder.getInt32(Size));
923
924 Inst->eraseFromParent();
925 return true;
926}
927
928bool ExpandVariadics::expandVAArgInst(IRBuilder<> &Builder,
929 const DataLayout &DL, VAArgInst *Inst) {
930 Builder.SetInsertPoint(Inst);
931
932 auto &Ctx = Builder.getContext();
933 Type *ValTy = Inst->getType();
934 Value *VaListPtr = Inst->getPointerOperand();
935
936 const VariadicABIInfo::VAArgSlotInfo SlotInfo = ABI->slotInfo(DL, ValTy);
937 Type *FrameFieldType = SlotInfo.Indirect ? DL.getAllocaPtrType(Ctx) : ValTy;
938 const uint64_t SlotSize = DL.getTypeAllocSize(FrameFieldType).getFixedValue();
939 const Align SlotAlign = SlotInfo.DataAlign;
940
941 Type *PtrTy = VaListPtr->getType();
942 Type *IdxTy = DL.getIndexType(PtrTy);
943
944 Value *Cur = Builder.CreateLoad(PtrTy, VaListPtr);
945
946 // Round the cursor up to the slot alignment used by the caller.
947 Value *Aligned = Cur;
948 if (SlotAlign > Align(1)) {
949 Value *RoundUp = Builder.CreateInBoundsPtrAdd(
950 Cur, ConstantInt::get(IdxTy, SlotAlign.value() - 1));
951 Aligned = Builder.CreateIntrinsic(
952 Intrinsic::ptrmask, {PtrTy, IdxTy},
953 {RoundUp, ConstantInt::getSigned(IdxTy, -(int64_t)SlotAlign.value())});
954 }
955
956 // Advance past the slot and write the iterator back.
957 Value *Next =
958 Builder.CreateInBoundsPtrAdd(Aligned, ConstantInt::get(IdxTy, SlotSize));
959 Builder.CreateStore(Next, VaListPtr);
960
961 // Load the slot contents: the value itself for direct arguments, or a
962 // pointer to the value for indirect ones.
963 Value *Result = Builder.CreateAlignedLoad(FrameFieldType, Aligned, SlotAlign);
964
965 if (SlotInfo.Indirect)
966 Result = Builder.CreateLoad(ValTy, Result);
967
968 Result->takeName(Inst);
969 Inst->replaceAllUsesWith(Result);
970 Inst->eraseFromParent();
971 return true;
972}
973
974struct Amdgpu final : public VariadicABIInfo {
975
976 bool enableForTarget() override { return true; }
977
978 bool vaListPassedInSSARegister() override { return true; }
979
980 Type *vaListType(LLVMContext &Ctx) override {
981 return PointerType::getUnqual(Ctx);
982 }
983
984 Type *vaListParameterType(Module &M) override {
985 return PointerType::getUnqual(M.getContext());
986 }
987
988 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
989 AllocaInst * /*va_list*/, Value *Buffer) override {
990 // Given Buffer, which is an AllocInst of vararg_buffer
991 // need to return something usable as parameter type
992 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
993 }
994
995 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
996 return {Align(4), false};
997 }
998};
999
1000struct NVPTX final : public VariadicABIInfo {
1001
1002 bool enableForTarget() override { return true; }
1003
1004 bool vaListPassedInSSARegister() override { return true; }
1005
1006 Type *vaListType(LLVMContext &Ctx) override {
1007 return PointerType::getUnqual(Ctx);
1008 }
1009
1010 Type *vaListParameterType(Module &M) override {
1011 return PointerType::getUnqual(M.getContext());
1012 }
1013
1014 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1015 AllocaInst *, Value *Buffer) override {
1016 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
1017 }
1018
1019 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1020 // NVPTX expects natural alignment in all cases. The variadic call ABI will
1021 // handle promoting types to their appropriate size and alignment.
1022 Align A = DL.getABITypeAlign(Parameter);
1023 return {A, false};
1024 }
1025};
1026
1027struct SPIRV final : public VariadicABIInfo {
1028
1029 bool enableForTarget() override { return true; }
1030
1031 bool vaListPassedInSSARegister() override { return true; }
1032
1033 Type *vaListType(LLVMContext &Ctx) override {
1034 return PointerType::getUnqual(Ctx);
1035 }
1036
1037 Type *vaListParameterType(Module &M) override {
1038 return PointerType::getUnqual(M.getContext());
1039 }
1040
1041 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1042 AllocaInst *, Value *Buffer) override {
1043 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
1044 }
1045
1046 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1047 // Expects natural alignment in all cases. The variadic call ABI will handle
1048 // promoting types to their appropriate size and alignment.
1049 Align A = DL.getABITypeAlign(Parameter);
1050 return {A, false};
1051 }
1052
1053 // The SPIR-V backend has special handling for builtins.
1054 bool ignoreFunction(const Function *F) override {
1055 if (!F->isDeclaration())
1056 return false;
1057
1058 std::string Demangled = llvm::demangle(F->getName());
1059 StringRef DemangledName(Demangled);
1060
1061 // Skip any SPIR-V builtins.
1062 if (DemangledName.starts_with("__spirv_") ||
1063 DemangledName.starts_with("printf("))
1064 return true;
1065
1066 return false;
1067 }
1068
1069 // We will likely see va intrinsics in the generic addrspace (4).
1070 SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const override {
1071 return {4};
1072 }
1073};
1074
1075struct Wasm final : public VariadicABIInfo {
1076
1077 bool enableForTarget() override {
1078 // Currently wasm is only used for testing.
1079 return commandLineOverride();
1080 }
1081
1082 bool vaListPassedInSSARegister() override { return true; }
1083
1084 Type *vaListType(LLVMContext &Ctx) override {
1085 return PointerType::getUnqual(Ctx);
1086 }
1087
1088 Type *vaListParameterType(Module &M) override {
1089 return PointerType::getUnqual(M.getContext());
1090 }
1091
1092 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1093 AllocaInst * /*va_list*/, Value *Buffer) override {
1094 return Buffer;
1095 }
1096
1097 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1098 LLVMContext &Ctx = Parameter->getContext();
1099 const unsigned MinAlign = 4;
1100 Align A = DL.getABITypeAlign(Parameter);
1101 if (A < MinAlign)
1102 A = Align(MinAlign);
1103
1104 if (auto *S = dyn_cast<StructType>(Parameter)) {
1105 if (S->getNumElements() > 1) {
1106 return {DL.getABITypeAlign(PointerType::getUnqual(Ctx)), true};
1107 }
1108 }
1109
1110 return {A, false};
1111 }
1112};
1113
1114std::unique_ptr<VariadicABIInfo> VariadicABIInfo::create(const Triple &T) {
1115 switch (T.getArch()) {
1116 case Triple::r600:
1117 case Triple::amdgcn: {
1118 return std::make_unique<Amdgpu>();
1119 }
1120
1121 case Triple::wasm32: {
1122 return std::make_unique<Wasm>();
1123 }
1124
1125 case Triple::nvptx:
1126 case Triple::nvptx64: {
1127 return std::make_unique<NVPTX>();
1128 }
1129
1130 case Triple::spirv:
1131 case Triple::spirv32:
1132 case Triple::spirv64: {
1133 return std::make_unique<SPIRV>();
1134 }
1135
1136 default:
1137 return {};
1138 }
1139}
1140
1141} // namespace
1142
1143char ExpandVariadics::ID = 0;
1144
1145INITIALIZE_PASS(ExpandVariadics, DEBUG_TYPE, "Expand variadic functions", false,
1146 false)
1147
1149 return new ExpandVariadics(M);
1150}
1151
1153 return ExpandVariadics(Mode).runOnModule(M) ? PreservedAnalyses::none()
1155}
1156
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallVector class.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Type * getParamByRefType(unsigned ArgNo) const
Extract the byref type for a call or parameter.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI ExpandVariadicsPass(ExpandVariadicsMode Mode)
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:761
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:354
iterator begin()
Definition Function.h:853
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
size_t arg_size() const
Definition Function.h:901
Argument * getArg(unsigned i) const
Definition Function.h:886
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:843
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
const Comdat * getComdat() const
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:337
LinkageTypes getLinkage() const
void setLinkage(LinkageTypes LT)
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
void setVisibility(VisibilityTypes V)
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2868
LLVM_ABI const DebugLoc & getStableDebugLoc() const
Fetch the debug location for this node, unless this is a debug intrinsic, in which case fetch the deb...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:685
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getPointerOperand()
This represents the llvm.va_copy intrinsic.
Value * getSrc() const
Value * getDest() const
This represents the llvm.va_end intrinsic.
This represents the llvm.va_start intrinsic.
Value * getArgList() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:552
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:399
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
ExpandVariadicsMode
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:357
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
DEMANGLE_ABI std::string demangle(std::string_view MangledName)
Attempt to demangle a string using different demangling schemes.
Definition Demangle.cpp:21
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106