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
56#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/PassManager.h"
61#include "llvm/Pass.h"
65
66#define DEBUG_TYPE "expand-variadics"
67
68using namespace llvm;
69
70namespace {
71
72cl::opt<ExpandVariadicsMode> ExpandVariadicsModeOption(
73 DEBUG_TYPE "-override", cl::desc("Override the behaviour of " DEBUG_TYPE),
76 "Use the implementation defaults"),
78 "Disable the pass entirely"),
80 "Optimise without changing ABI"),
82 "Change variadic calling convention")));
83
84bool commandLineOverride() {
85 return ExpandVariadicsModeOption != ExpandVariadicsMode::Unspecified;
86}
87
88// Instances of this class encapsulate the target-dependant behaviour as a
89// function of triple. Implementing a new ABI is adding a case to the switch
90// in create(llvm::Triple) at the end of this file.
91// This class may end up instantiated in TargetMachine instances, keeping it
92// here for now until enough targets are implemented for the API to evolve.
93class VariadicABIInfo {
94protected:
95 VariadicABIInfo() = default;
96
97public:
98 static std::unique_ptr<VariadicABIInfo> create(const Triple &T);
99
100 // Allow overriding whether the pass runs on a per-target basis
101 virtual bool enableForTarget() = 0;
102
103 // Whether a valist instance is passed by value or by address
104 // I.e. does it need to be alloca'ed and stored into, or can
105 // it be passed directly in a SSA register
106 virtual bool vaListPassedInSSARegister() = 0;
107
108 // The type of a va_list iterator object
109 virtual Type *vaListType(LLVMContext &Ctx) = 0;
110
111 // The type of a va_list as a function argument as lowered by C
112 virtual Type *vaListParameterType(Module &M) = 0;
113
114 // Initialize an allocated va_list object to point to an already
115 // initialized contiguous memory region.
116 // Return the value to pass as the va_list argument
117 virtual Value *initializeVaList(Module &M, LLVMContext &Ctx,
118 IRBuilder<> &Builder, AllocaInst *VaList,
119 Value *Buffer) = 0;
120
121 struct VAArgSlotInfo {
122 Align DataAlign; // With respect to the call frame
123 bool Indirect; // Passed via a pointer
124 };
125 virtual VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) = 0;
126
127 // Per-target overrides of special symbols.
128 virtual bool ignoreFunction(Function *F) { return false; }
129
130 // Targets implemented so far all have the same trivial lowering for these
131 bool vaEndIsNop() { return true; }
132 bool vaCopyIsMemcpy() { return true; }
133
134 virtual ~VariadicABIInfo() = default;
135};
136
137class ExpandVariadics : public ModulePass {
138
139 // The pass construction sets the default to optimize when called from middle
140 // end and lowering when called from the backend. The command line variable
141 // overrides that. This is useful for testing and debugging. It also allows
142 // building an applications with variadic functions wholly removed if one
143 // has sufficient control over the dependencies, e.g. a statically linked
144 // clang that has no variadic function calls remaining in the binary.
145
146public:
147 static char ID;
149 std::unique_ptr<VariadicABIInfo> ABI;
150
151 ExpandVariadics(ExpandVariadicsMode Mode)
152 : ModulePass(ID),
153 Mode(commandLineOverride() ? ExpandVariadicsModeOption : Mode) {}
154
155 StringRef getPassName() const override { return "Expand variadic functions"; }
156
157 bool rewriteABI() { return Mode == ExpandVariadicsMode::Lowering; }
158
159 template <typename T> bool isValidCallingConv(T *F) {
160 return F->getCallingConv() == CallingConv::C ||
161 F->getCallingConv() == CallingConv::SPIR_FUNC;
162 }
163
164 bool runOnModule(Module &M) override;
165
166 bool runOnFunction(Module &M, IRBuilder<> &Builder, Function *F);
167
168 Function *replaceAllUsesWithNewDeclaration(Module &M,
169 Function *OriginalFunction);
170
171 Function *deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
172 Function *OriginalFunction);
173
174 Function *defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
175 Function *VariadicWrapper,
176 Function *FixedArityReplacement);
177
178 bool expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB, FunctionType *,
179 Function *NF);
180
181 // The intrinsic functions va_copy and va_end are removed unconditionally.
182 // They correspond to a memcpy and a no-op on all implemented targets.
183 // The va_start intrinsic is removed from basic blocks that were not created
184 // by this pass, some may remain if needed to maintain the external ABI.
185
186 template <Intrinsic::ID ID, typename InstructionType>
187 bool expandIntrinsicUsers(Module &M, IRBuilder<> &Builder,
188 PointerType *IntrinsicArgType) {
189 bool Changed = false;
190 const DataLayout &DL = M.getDataLayout();
191 if (Function *Intrinsic =
192 Intrinsic::getDeclarationIfExists(&M, ID, {IntrinsicArgType})) {
193 for (User *U : make_early_inc_range(Intrinsic->users()))
194 if (auto *I = dyn_cast<InstructionType>(U))
195 Changed |= expandVAIntrinsicCall(Builder, DL, I);
196
197 if (Intrinsic->use_empty())
198 Intrinsic->eraseFromParent();
199 }
200 return Changed;
201 }
202
203 bool expandVAIntrinsicUsersWithAddrspace(Module &M, IRBuilder<> &Builder,
204 unsigned Addrspace) {
205 auto &Ctx = M.getContext();
206 PointerType *IntrinsicArgType = PointerType::get(Ctx, Addrspace);
207 bool Changed = false;
208
209 // expand vastart before vacopy as vastart may introduce a vacopy
210 Changed |= expandIntrinsicUsers<Intrinsic::vastart, VAStartInst>(
211 M, Builder, IntrinsicArgType);
212 Changed |= expandIntrinsicUsers<Intrinsic::vaend, VAEndInst>(
213 M, Builder, IntrinsicArgType);
214 Changed |= expandIntrinsicUsers<Intrinsic::vacopy, VACopyInst>(
215 M, Builder, IntrinsicArgType);
216 return Changed;
217 }
218
219 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
220 VAStartInst *Inst);
221
222 bool expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
223 VAEndInst *Inst);
224
225 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
226 VACopyInst *Inst);
227
228 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy) {
229 // The type of "FTy" with the ... removed and a va_list appended
230 SmallVector<Type *> ArgTypes(FTy->params());
231 ArgTypes.push_back(ABI->vaListParameterType(M));
232 return FunctionType::get(FTy->getReturnType(), ArgTypes,
233 /*IsVarArgs=*/false);
234 }
235
236 bool expansionApplicableToFunction(Module &M, Function *F) {
237 if (F->isIntrinsic() || !F->isVarArg() ||
238 F->hasFnAttribute(Attribute::Naked))
239 return false;
240
241 if (ABI->ignoreFunction(F))
242 return false;
243
244 if (!isValidCallingConv(F))
245 return false;
246
247 if (rewriteABI())
248 return true;
249
250 if (!F->hasExactDefinition())
251 return false;
252
253 return true;
254 }
255
256 bool expansionApplicableToFunctionCall(CallBase *CB) {
257 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
258 if (CI->isMustTailCall()) {
259 // Cannot expand musttail calls
260 return false;
261 }
262
263 if (!isValidCallingConv(CI))
264 return false;
265
266 return true;
267 }
268
269 if (isa<InvokeInst>(CB)) {
270 // Invoke not implemented in initial implementation of pass
271 return false;
272 }
273
274 // Other unimplemented derivative of CallBase
275 return false;
276 }
277
278 class ExpandedCallFrame {
279 // Helper for constructing an alloca instance containing the arguments bound
280 // to the variadic ... parameter, rearranged to allow indexing through a
281 // va_list iterator
282 enum { N = 4 };
283 SmallVector<Type *, N> FieldTypes;
284 enum Tag { Store, Memcpy, Padding };
286
287 template <Tag tag> void append(Type *FieldType, Value *V, uint64_t Bytes) {
288 FieldTypes.push_back(FieldType);
289 Source.push_back({V, Bytes, tag});
290 }
291
292 public:
293 void store(LLVMContext &Ctx, Type *T, Value *V) { append<Store>(T, V, 0); }
294
295 void memcpy(LLVMContext &Ctx, Type *T, Value *V, uint64_t Bytes) {
296 append<Memcpy>(T, V, Bytes);
297 }
298
299 void padding(LLVMContext &Ctx, uint64_t By) {
300 append<Padding>(ArrayType::get(Type::getInt8Ty(Ctx), By), nullptr, 0);
301 }
302
303 size_t size() const { return FieldTypes.size(); }
304 bool empty() const { return FieldTypes.empty(); }
305
306 StructType *asStruct(LLVMContext &Ctx, StringRef Name) {
307 const bool IsPacked = true;
308 return StructType::create(Ctx, FieldTypes,
309 (Twine(Name) + ".vararg").str(), IsPacked);
310 }
311
312 void initializeStructAlloca(const DataLayout &DL, IRBuilder<> &Builder,
313 AllocaInst *Alloced) {
314
315 StructType *VarargsTy = cast<StructType>(Alloced->getAllocatedType());
316
317 for (size_t I = 0; I < size(); I++) {
318
319 auto [V, bytes, tag] = Source[I];
320
321 if (tag == Padding) {
322 assert(V == nullptr);
323 continue;
324 }
325
326 auto Dst = Builder.CreateStructGEP(VarargsTy, Alloced, I);
327
328 assert(V != nullptr);
329
330 if (tag == Store)
331 Builder.CreateStore(V, Dst);
332
333 if (tag == Memcpy)
334 Builder.CreateMemCpy(Dst, {}, V, {}, bytes);
335 }
336 }
337 };
338};
339
340bool ExpandVariadics::runOnModule(Module &M) {
341 bool Changed = false;
343 return Changed;
344
345 Triple TT(M.getTargetTriple());
346 ABI = VariadicABIInfo::create(TT);
347 if (!ABI)
348 return Changed;
349
350 if (!ABI->enableForTarget())
351 return Changed;
352
353 auto &Ctx = M.getContext();
354 const DataLayout &DL = M.getDataLayout();
355 IRBuilder<> Builder(Ctx);
356
357 // Lowering needs to run on all functions exactly once.
358 // Optimize could run on functions containing va_start exactly once.
360 Changed |= runOnFunction(M, Builder, &F);
361
362 // After runOnFunction, all known calls to known variadic functions have been
363 // replaced. va_start intrinsics are presently (and invalidly!) only present
364 // in functions that used to be variadic and have now been replaced to take a
365 // va_list instead. If lowering as opposed to optimising, calls to unknown
366 // variadic functions have also been replaced.
367
368 {
369 // 0 and AllocaAddrSpace are sufficient for the targets implemented so far
370 unsigned Addrspace = 0;
371 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
372
373 Addrspace = DL.getAllocaAddrSpace();
374 if (Addrspace != 0)
375 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
376 }
377
379 return Changed;
380
381 for (Function &F : make_early_inc_range(M)) {
382 if (F.isDeclaration())
383 continue;
384
385 // Now need to track down indirect calls. Can't find those
386 // by walking uses of variadic functions, need to crawl the instruction
387 // stream. Fortunately this is only necessary for the ABI rewrite case.
388 for (BasicBlock &BB : F) {
389 for (Instruction &I : make_early_inc_range(BB)) {
390 if (CallBase *CB = dyn_cast<CallBase>(&I)) {
391 if (CB->isIndirectCall()) {
392 FunctionType *FTy = CB->getFunctionType();
393 if (FTy->isVarArg())
394 Changed |= expandCall(M, Builder, CB, FTy, /*NF=*/nullptr);
395 }
396 }
397 }
398 }
399 }
400
401 return Changed;
402}
403
404bool ExpandVariadics::runOnFunction(Module &M, IRBuilder<> &Builder,
405 Function *OriginalFunction) {
406 bool Changed = false;
407
408 if (!expansionApplicableToFunction(M, OriginalFunction))
409 return Changed;
410
411 [[maybe_unused]] const bool OriginalFunctionIsDeclaration =
412 OriginalFunction->isDeclaration();
413 assert(rewriteABI() || !OriginalFunctionIsDeclaration);
414
415 // Declare a new function and redirect every use to that new function
416 Function *VariadicWrapper =
417 replaceAllUsesWithNewDeclaration(M, OriginalFunction);
418 assert(VariadicWrapper->isDeclaration());
419 assert(OriginalFunction->use_empty());
420
421 // Create a new function taking va_list containing the implementation of the
422 // original
423 Function *FixedArityReplacement =
424 deriveFixedArityReplacement(M, Builder, OriginalFunction);
425 assert(OriginalFunction->isDeclaration());
426 assert(FixedArityReplacement->isDeclaration() ==
427 OriginalFunctionIsDeclaration);
428 assert(VariadicWrapper->isDeclaration());
429
430 // Create a single block forwarding wrapper that turns a ... into a va_list
431 [[maybe_unused]] Function *VariadicWrapperDefine =
432 defineVariadicWrapper(M, Builder, VariadicWrapper, FixedArityReplacement);
433 assert(VariadicWrapperDefine == VariadicWrapper);
434 assert(!VariadicWrapper->isDeclaration());
435
436 // Add the prof metadata from the original function to the wrapper. Because
437 // FixedArityReplacement is the owner of original function's prof metadata
438 // after the splice, we need to transfer it to VariadicWrapper.
439 VariadicWrapper->setMetadata(
440 LLVMContext::MD_prof,
441 FixedArityReplacement->getMetadata(LLVMContext::MD_prof));
442
443 // We now have:
444 // 1. the original function, now as a declaration with no uses
445 // 2. a variadic function that unconditionally calls a fixed arity replacement
446 // 3. a fixed arity function equivalent to the original function
447
448 // Replace known calls to the variadic with calls to the va_list equivalent
449 for (User *U : make_early_inc_range(VariadicWrapper->users())) {
450 if (CallBase *CB = dyn_cast<CallBase>(U)) {
451 Value *CalledOperand = CB->getCalledOperand();
452 if (VariadicWrapper == CalledOperand)
453 Changed |=
454 expandCall(M, Builder, CB, VariadicWrapper->getFunctionType(),
455 FixedArityReplacement);
456 }
457 }
458
459 // The original function will be erased.
460 // One of the two new functions will become a replacement for the original.
461 // When preserving the ABI, the other is an internal implementation detail.
462 // When rewriting the ABI, RAUW then the variadic one.
463 Function *const ExternallyAccessible =
464 rewriteABI() ? FixedArityReplacement : VariadicWrapper;
465 Function *const InternalOnly =
466 rewriteABI() ? VariadicWrapper : FixedArityReplacement;
467
468 // The external function is the replacement for the original
469 ExternallyAccessible->setLinkage(OriginalFunction->getLinkage());
470 ExternallyAccessible->setVisibility(OriginalFunction->getVisibility());
471 ExternallyAccessible->setComdat(OriginalFunction->getComdat());
472 ExternallyAccessible->takeName(OriginalFunction);
473
474 // Annotate the internal one as internal
477
478 // The original is unused and obsolete
479 OriginalFunction->eraseFromParent();
480
481 InternalOnly->removeDeadConstantUsers();
482
483 if (rewriteABI()) {
484 // All known calls to the function have been removed by expandCall
485 // Resolve everything else by replaceAllUsesWith
486 VariadicWrapper->replaceAllUsesWith(FixedArityReplacement);
487 VariadicWrapper->eraseFromParent();
488 }
489
490 return Changed;
491}
492
493Function *
494ExpandVariadics::replaceAllUsesWithNewDeclaration(Module &M,
495 Function *OriginalFunction) {
496 auto &Ctx = M.getContext();
497 Function &F = *OriginalFunction;
498 FunctionType *FTy = F.getFunctionType();
499 Function *NF = Function::Create(FTy, F.getLinkage(), F.getAddressSpace());
500
501 NF->setName(F.getName() + ".varargs");
502
503 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
504
505 AttrBuilder ParamAttrs(Ctx);
506 AttributeList Attrs = NF->getAttributes();
507 Attrs = Attrs.addParamAttributes(Ctx, FTy->getNumParams(), ParamAttrs);
508 NF->setAttributes(Attrs);
509
510 OriginalFunction->replaceAllUsesWith(NF);
511 return NF;
512}
513
514Function *
515ExpandVariadics::deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
516 Function *OriginalFunction) {
517 Function &F = *OriginalFunction;
518 // The purpose here is split the variadic function F into two functions
519 // One is a variadic function that bundles the passed argument into a va_list
520 // and passes it to the second function. The second function does whatever
521 // the original F does, except that it takes a va_list instead of the ...
522
523 assert(expansionApplicableToFunction(M, &F));
524
525 auto &Ctx = M.getContext();
526
527 // Returned value isDeclaration() is equal to F.isDeclaration()
528 // but that property is not invariant throughout this function
529 const bool FunctionIsDefinition = !F.isDeclaration();
530
531 FunctionType *FTy = F.getFunctionType();
532 SmallVector<Type *> ArgTypes(FTy->params());
533 ArgTypes.push_back(ABI->vaListParameterType(M));
534
535 FunctionType *NFTy = inlinableVariadicFunctionType(M, FTy);
536 Function *NF = Function::Create(NFTy, F.getLinkage(), F.getAddressSpace());
537
538 // Note - same attribute handling as DeadArgumentElimination
539 NF->copyAttributesFrom(&F);
540 NF->setComdat(F.getComdat());
541 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
542 NF->setName(F.getName() + ".valist");
543
544 AttrBuilder ParamAttrs(Ctx);
545
546 AttributeList Attrs = NF->getAttributes();
547 Attrs = Attrs.addParamAttributes(Ctx, NFTy->getNumParams() - 1, ParamAttrs);
548 NF->setAttributes(Attrs);
549
550 // Splice the implementation into the new function with minimal changes
551 if (FunctionIsDefinition) {
552 NF->splice(NF->begin(), &F);
553
554 auto NewArg = NF->arg_begin();
555 for (Argument &Arg : F.args()) {
556 Arg.replaceAllUsesWith(NewArg);
557 NewArg->setName(Arg.getName()); // takeName without killing the old one
558 ++NewArg;
559 }
560 NewArg->setName("varargs");
561 }
562
564 F.getAllMetadata(MDs);
565 for (auto [KindID, Node] : MDs)
566 NF->addMetadata(KindID, *Node);
567 F.clearMetadata();
568
569 return NF;
570}
571
572Function *
573ExpandVariadics::defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
574 Function *VariadicWrapper,
575 Function *FixedArityReplacement) {
576 auto &Ctx = Builder.getContext();
577 const DataLayout &DL = M.getDataLayout();
578 assert(VariadicWrapper->isDeclaration());
579 Function &F = *VariadicWrapper;
580
581 assert(F.isDeclaration());
582 Type *VaListTy = ABI->vaListType(Ctx);
583
584 auto *BB = BasicBlock::Create(Ctx, "entry", &F);
585 Builder.SetInsertPoint(BB);
586
587 AllocaInst *VaListInstance =
588 Builder.CreateAlloca(VaListTy, nullptr, "va_start");
589
590 Builder.CreateLifetimeStart(VaListInstance);
591
592 Builder.CreateIntrinsic(Intrinsic::vastart, {DL.getAllocaPtrType(Ctx)},
593 {VaListInstance});
594
596
597 Type *ParameterType = ABI->vaListParameterType(M);
598 if (ABI->vaListPassedInSSARegister())
599 Args.push_back(Builder.CreateLoad(ParameterType, VaListInstance));
600 else
601 Args.push_back(Builder.CreateAddrSpaceCast(VaListInstance, ParameterType));
602
603 CallInst *Result = Builder.CreateCall(FixedArityReplacement, Args);
604
605 Builder.CreateIntrinsic(Intrinsic::vaend, {DL.getAllocaPtrType(Ctx)},
606 {VaListInstance});
607 Builder.CreateLifetimeEnd(VaListInstance);
608
609 if (Result->getType()->isVoidTy())
610 Builder.CreateRetVoid();
611 else
612 Builder.CreateRet(Result);
613
614 return VariadicWrapper;
615}
616
617bool ExpandVariadics::expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB,
618 FunctionType *VarargFunctionType,
619 Function *NF) {
620 bool Changed = false;
621 const DataLayout &DL = M.getDataLayout();
622
623 if (ABI->ignoreFunction(CB->getCalledFunction()))
624 return Changed;
625
626 if (!expansionApplicableToFunctionCall(CB)) {
627 if (rewriteABI())
628 report_fatal_error("Cannot lower callbase instruction");
629 return Changed;
630 }
631
632 // This is tricky. The call instruction's function type might not match
633 // the type of the caller. When optimising, can leave it unchanged.
634 // Webassembly detects that inconsistency and repairs it.
635 FunctionType *FuncType = CB->getFunctionType();
636 if (FuncType != VarargFunctionType) {
637 if (!rewriteABI())
638 return Changed;
639 FuncType = VarargFunctionType;
640 }
641
642 auto &Ctx = CB->getContext();
643
644 Align MaxFieldAlign(1);
645
646 // The strategy is to allocate a call frame containing the variadic
647 // arguments laid out such that a target specific va_list can be initialized
648 // with it, such that target specific va_arg instructions will correctly
649 // iterate over it. This means getting the alignment right and sometimes
650 // embedding a pointer to the value instead of embedding the value itself.
651
652 Function *CBF = CB->getParent()->getParent();
653
654 ExpandedCallFrame Frame;
655
656 uint64_t CurrentOffset = 0;
657
658 for (unsigned I = FuncType->getNumParams(), E = CB->arg_size(); I < E; ++I) {
659 Value *ArgVal = CB->getArgOperand(I);
660 const bool IsByVal = CB->paramHasAttr(I, Attribute::ByVal);
661 const bool IsByRef = CB->paramHasAttr(I, Attribute::ByRef);
662
663 // The type of the value being passed, decoded from byval/byref metadata if
664 // required
665 Type *const UnderlyingType = IsByVal ? CB->getParamByValType(I)
666 : IsByRef ? CB->getParamByRefType(I)
667 : ArgVal->getType();
668 const uint64_t UnderlyingSize =
669 DL.getTypeAllocSize(UnderlyingType).getFixedValue();
670
671 // The type to be written into the call frame
672 Type *FrameFieldType = UnderlyingType;
673
674 // The value to copy from when initialising the frame alloca
675 Value *SourceValue = ArgVal;
676
677 VariadicABIInfo::VAArgSlotInfo SlotInfo = ABI->slotInfo(DL, UnderlyingType);
678
679 if (SlotInfo.Indirect) {
680 // The va_arg lowering loads through a pointer. Set up an alloca to aim
681 // that pointer at.
682 Builder.SetInsertPointPastAllocas(CBF);
683 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
684 Value *CallerCopy =
685 Builder.CreateAlloca(UnderlyingType, nullptr, "IndirectAlloca");
686
687 Builder.SetInsertPoint(CB);
688 if (IsByVal)
689 Builder.CreateMemCpy(CallerCopy, {}, ArgVal, {}, UnderlyingSize);
690 else
691 Builder.CreateStore(ArgVal, CallerCopy);
692
693 // Indirection now handled, pass the alloca ptr by value
694 FrameFieldType = DL.getAllocaPtrType(Ctx);
695 SourceValue = CallerCopy;
696 }
697
698 // Alignment of the value within the frame
699 // This probably needs to be controllable as a function of type
700 Align DataAlign = SlotInfo.DataAlign;
701
702 MaxFieldAlign = std::max(MaxFieldAlign, DataAlign);
703
704 uint64_t DataAlignV = DataAlign.value();
705 if (uint64_t Rem = CurrentOffset % DataAlignV) {
706 // Inject explicit padding to deal with alignment requirements
707 uint64_t Padding = DataAlignV - Rem;
708 Frame.padding(Ctx, Padding);
709 CurrentOffset += Padding;
710 }
711
712 if (SlotInfo.Indirect) {
713 Frame.store(Ctx, FrameFieldType, SourceValue);
714 } else {
715 if (IsByVal)
716 Frame.memcpy(Ctx, FrameFieldType, SourceValue, UnderlyingSize);
717 else
718 Frame.store(Ctx, FrameFieldType, SourceValue);
719 }
720
721 CurrentOffset += DL.getTypeAllocSize(FrameFieldType).getFixedValue();
722 }
723
724 if (Frame.empty()) {
725 // Not passing any arguments, hopefully va_arg won't try to read any
726 // Creating a single byte frame containing nothing to point the va_list
727 // instance as that is less special-casey in the compiler and probably
728 // easier to interpret in a debugger.
729 Frame.padding(Ctx, 1);
730 }
731
732 StructType *VarargsTy = Frame.asStruct(Ctx, CBF->getName());
733
734 // The struct instance needs to be at least MaxFieldAlign for the alignment of
735 // the fields to be correct at runtime. Use the native stack alignment instead
736 // if that's greater as that tends to give better codegen.
737 // This is an awkward way to guess whether there is a known stack alignment
738 // without hitting an assert in DL.getStackAlignment, 1024 is an arbitrary
739 // number likely to be greater than the natural stack alignment.
740 Align AllocaAlign = MaxFieldAlign;
741 if (MaybeAlign StackAlign = DL.getStackAlignment();
742 StackAlign && *StackAlign > AllocaAlign)
743 AllocaAlign = *StackAlign;
744
745 // Put the alloca to hold the variadic args in the entry basic block.
746 Builder.SetInsertPointPastAllocas(CBF);
747
748 // SetCurrentDebugLocation when the builder SetInsertPoint method does not
749 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
750
751 // The awkward construction here is to set the alignment on the instance
752 AllocaInst *Alloced = Builder.Insert(
753 new AllocaInst(VarargsTy, DL.getAllocaAddrSpace(), nullptr, AllocaAlign),
754 "vararg_buffer");
755 Changed = true;
756 assert(Alloced->getAllocatedType() == VarargsTy);
757
758 // Initialize the fields in the struct
759 Builder.SetInsertPoint(CB);
760 Builder.CreateLifetimeStart(Alloced);
761 Frame.initializeStructAlloca(DL, Builder, Alloced);
762
763 const unsigned NumArgs = FuncType->getNumParams();
764 SmallVector<Value *> Args(CB->arg_begin(), CB->arg_begin() + NumArgs);
765
766 // Initialize a va_list pointing to that struct and pass it as the last
767 // argument
768 AllocaInst *VaList = nullptr;
769 {
770 if (!ABI->vaListPassedInSSARegister()) {
771 Type *VaListTy = ABI->vaListType(Ctx);
772 Builder.SetInsertPointPastAllocas(CBF);
773 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
774 VaList = Builder.CreateAlloca(VaListTy, nullptr, "va_argument");
775 Builder.SetInsertPoint(CB);
776 Builder.CreateLifetimeStart(VaList);
777 }
778 Builder.SetInsertPoint(CB);
779 Args.push_back(ABI->initializeVaList(M, Ctx, Builder, VaList, Alloced));
780 }
781
782 // Attributes excluding any on the vararg arguments
783 AttributeList PAL = CB->getAttributes();
784 if (!PAL.isEmpty()) {
786 for (unsigned ArgNo = 0; ArgNo < NumArgs; ArgNo++)
787 ArgAttrs.push_back(PAL.getParamAttrs(ArgNo));
788 PAL =
789 AttributeList::get(Ctx, PAL.getFnAttrs(), PAL.getRetAttrs(), ArgAttrs);
790 }
791
793 CB->getOperandBundlesAsDefs(OpBundles);
794
795 CallBase *NewCB = nullptr;
796
797 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
798 Value *Dst = NF ? NF : CI->getCalledOperand();
799 FunctionType *NFTy = inlinableVariadicFunctionType(M, VarargFunctionType);
800
801 NewCB = CallInst::Create(NFTy, Dst, Args, OpBundles, "", CI->getIterator());
802
803 CallInst::TailCallKind TCK = CI->getTailCallKind();
805
806 // Can't tail call a function that is being passed a pointer to an alloca
807 if (TCK == CallInst::TCK_Tail)
808 TCK = CallInst::TCK_None;
809 CI->setTailCallKind(TCK);
810
811 } else {
812 llvm_unreachable("Unreachable when !expansionApplicableToFunctionCall()");
813 }
814
815 if (VaList)
816 Builder.CreateLifetimeEnd(VaList);
817
818 Builder.CreateLifetimeEnd(Alloced);
819
820 NewCB->setAttributes(PAL);
821 NewCB->takeName(CB);
822 NewCB->setCallingConv(CB->getCallingConv());
823 NewCB->setDebugLoc(DebugLoc());
824
825 // DeadArgElim and ArgPromotion copy exactly this metadata
826 NewCB->copyMetadata(*CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
827
828 CB->replaceAllUsesWith(NewCB);
829 CB->eraseFromParent();
830 return Changed;
831}
832
833bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
834 const DataLayout &DL,
835 VAStartInst *Inst) {
836 // Only removing va_start instructions that are not in variadic functions.
837 // Those would be rejected by the IR verifier before this pass.
838 // After splicing basic blocks from a variadic function into a fixed arity
839 // one the va_start that used to refer to the ... parameter still exist.
840 // There are also variadic functions that this pass did not change and
841 // va_start instances in the created single block wrapper functions.
842 // Replace exactly the instances in non-variadic functions as those are
843 // the ones to be fixed up to use the va_list passed as the final argument.
844
845 Function *ContainingFunction = Inst->getFunction();
846 if (ContainingFunction->isVarArg()) {
847 return false;
848 }
849
850 // The last argument is a vaListParameterType, either a va_list
851 // or a pointer to one depending on the target.
852 bool PassedByValue = ABI->vaListPassedInSSARegister();
853 Argument *PassedVaList =
854 ContainingFunction->getArg(ContainingFunction->arg_size() - 1);
855
856 // va_start takes a pointer to a va_list, e.g. one on the stack
857 Value *VaStartArg = Inst->getArgList();
858
859 Builder.SetInsertPoint(Inst);
860
861 if (PassedByValue) {
862 // The general thing to do is create an alloca, store the va_list argument
863 // to it, then create a va_copy. When vaCopyIsMemcpy(), this optimises to a
864 // store to the VaStartArg.
865 assert(ABI->vaCopyIsMemcpy());
866 Builder.CreateStore(PassedVaList, VaStartArg);
867 } else {
868
869 // Otherwise emit a vacopy to pick up target-specific handling if any
870 auto &Ctx = Builder.getContext();
871
872 Builder.CreateIntrinsic(Intrinsic::vacopy, {DL.getAllocaPtrType(Ctx)},
873 {VaStartArg, PassedVaList});
874 }
875
876 Inst->eraseFromParent();
877 return true;
878}
879
880bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
881 VAEndInst *Inst) {
882 assert(ABI->vaEndIsNop());
883 Inst->eraseFromParent();
884 return true;
885}
886
887bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
888 const DataLayout &DL,
889 VACopyInst *Inst) {
890 assert(ABI->vaCopyIsMemcpy());
891 Builder.SetInsertPoint(Inst);
892
893 auto &Ctx = Builder.getContext();
894 Type *VaListTy = ABI->vaListType(Ctx);
895 uint64_t Size = DL.getTypeAllocSize(VaListTy).getFixedValue();
896
897 Builder.CreateMemCpy(Inst->getDest(), {}, Inst->getSrc(), {},
898 Builder.getInt32(Size));
899
900 Inst->eraseFromParent();
901 return true;
902}
903
904struct Amdgpu final : public VariadicABIInfo {
905
906 bool enableForTarget() override { return true; }
907
908 bool vaListPassedInSSARegister() override { return true; }
909
910 Type *vaListType(LLVMContext &Ctx) override {
911 return PointerType::getUnqual(Ctx);
912 }
913
914 Type *vaListParameterType(Module &M) override {
915 return PointerType::getUnqual(M.getContext());
916 }
917
918 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
919 AllocaInst * /*va_list*/, Value *Buffer) override {
920 // Given Buffer, which is an AllocInst of vararg_buffer
921 // need to return something usable as parameter type
922 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
923 }
924
925 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
926 return {Align(4), false};
927 }
928};
929
930struct NVPTX final : public VariadicABIInfo {
931
932 bool enableForTarget() override { return true; }
933
934 bool vaListPassedInSSARegister() override { return true; }
935
936 Type *vaListType(LLVMContext &Ctx) override {
937 return PointerType::getUnqual(Ctx);
938 }
939
940 Type *vaListParameterType(Module &M) override {
941 return PointerType::getUnqual(M.getContext());
942 }
943
944 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
945 AllocaInst *, Value *Buffer) override {
946 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
947 }
948
949 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
950 // NVPTX expects natural alignment in all cases. The variadic call ABI will
951 // handle promoting types to their appropriate size and alignment.
952 Align A = DL.getABITypeAlign(Parameter);
953 return {A, false};
954 }
955};
956
957struct SPIRV final : public VariadicABIInfo {
958
959 bool enableForTarget() override { return true; }
960
961 bool vaListPassedInSSARegister() override { return true; }
962
963 Type *vaListType(LLVMContext &Ctx) override {
964 return PointerType::getUnqual(Ctx);
965 }
966
967 Type *vaListParameterType(Module &M) override {
968 return PointerType::getUnqual(M.getContext());
969 }
970
971 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
972 AllocaInst *, Value *Buffer) override {
973 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
974 }
975
976 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
977 // Expects natural alignment in all cases. The variadic call ABI will handle
978 // promoting types to their appropriate size and alignment.
979 Align A = DL.getABITypeAlign(Parameter);
980 return {A, false};
981 }
982
983 // The SPIR-V backend has special handling for SPIR-V mangled printf
984 // functions.
985 bool ignoreFunction(Function *F) override {
986 return F->getName().starts_with('_') && F->getName().contains("printf");
987 }
988};
989
990struct Wasm final : public VariadicABIInfo {
991
992 bool enableForTarget() override {
993 // Currently wasm is only used for testing.
994 return commandLineOverride();
995 }
996
997 bool vaListPassedInSSARegister() override { return true; }
998
999 Type *vaListType(LLVMContext &Ctx) override {
1000 return PointerType::getUnqual(Ctx);
1001 }
1002
1003 Type *vaListParameterType(Module &M) override {
1004 return PointerType::getUnqual(M.getContext());
1005 }
1006
1007 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1008 AllocaInst * /*va_list*/, Value *Buffer) override {
1009 return Buffer;
1010 }
1011
1012 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1013 LLVMContext &Ctx = Parameter->getContext();
1014 const unsigned MinAlign = 4;
1015 Align A = DL.getABITypeAlign(Parameter);
1016 if (A < MinAlign)
1017 A = Align(MinAlign);
1018
1019 if (auto *S = dyn_cast<StructType>(Parameter)) {
1020 if (S->getNumElements() > 1) {
1021 return {DL.getABITypeAlign(PointerType::getUnqual(Ctx)), true};
1022 }
1023 }
1024
1025 return {A, false};
1026 }
1027};
1028
1029std::unique_ptr<VariadicABIInfo> VariadicABIInfo::create(const Triple &T) {
1030 switch (T.getArch()) {
1031 case Triple::r600:
1032 case Triple::amdgcn: {
1033 return std::make_unique<Amdgpu>();
1034 }
1035
1036 case Triple::wasm32: {
1037 return std::make_unique<Wasm>();
1038 }
1039
1040 case Triple::nvptx:
1041 case Triple::nvptx64: {
1042 return std::make_unique<NVPTX>();
1043 }
1044
1045 case Triple::spirv:
1046 case Triple::spirv64: {
1047 return std::make_unique<SPIRV>();
1048 }
1049
1050 default:
1051 return {};
1052 }
1053}
1054
1055} // namespace
1056
1057char ExpandVariadics::ID = 0;
1058
1059INITIALIZE_PASS(ExpandVariadics, DEBUG_TYPE, "Expand variadic functions", false,
1060 false)
1061
1063 return new ExpandVariadics(M);
1064}
1065
1067 return ExpandVariadics(Mode).runOnModule(M) ? PreservedAnalyses::none()
1069}
1070
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#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")))
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)
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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:166
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:759
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:209
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:352
iterator begin()
Definition Function.h:851
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
arg_iterator arg_begin()
Definition Function.h:866
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
size_t arg_size() const
Definition Function.h:899
Argument * getArg(unsigned i) const
Definition Function.h:884
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:227
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:859
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
const Comdat * getComdat() const
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition Value.h:576
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:328
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:2762
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:619
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:45
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
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:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
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:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
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.
Definition Types.h:26
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:1667
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
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:632
ExpandVariadicsMode
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:357
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
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