LLVM 24.0.0git
RewriteStatepointsForGC.cpp
Go to the documentation of this file.
1//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
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// Rewrite call/invoke instructions so as to make potential relocations
10// performed by the garbage collector explicit in the IR.
11//
12//===----------------------------------------------------------------------===//
13
15#include "ScalarOptions.h"
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Sequence.h"
23#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/Argument.h"
32#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GCStrategy.h"
42#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/MDBuilder.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
53#include "llvm/IR/Statepoint.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/User.h"
56#include "llvm/IR/Value.h"
57#include "llvm/IR/ValueHandle.h"
61#include "llvm/Support/Debug.h"
67#include <cassert>
68#include <cstddef>
69#include <cstdint>
70#include <iterator>
71#include <optional>
72#include <set>
73#include <string>
74#include <utility>
75#include <vector>
76
77#define DEBUG_TYPE "rewrite-statepoints-for-gc"
78
79using namespace llvm;
80
81#ifdef EXPENSIVE_CHECKS
82static bool ClobberNonLive = true;
83#else
84static bool ClobberNonLive = false;
85#endif
86
87static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
90
91/// The IR fed into RewriteStatepointsForGC may have had attributes and
92/// metadata implying dereferenceability that are no longer valid/correct after
93/// RewriteStatepointsForGC has run. This is because semantically, after
94/// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
95/// heap. stripNonValidData (conservatively) restores
96/// correctness by erasing all attributes in the module that externally imply
97/// dereferenceability. Similar reasoning also applies to the noalias
98/// attributes and metadata. gc.statepoint can touch the entire heap including
99/// noalias objects.
100/// Apart from attributes and metadata, we also remove instructions that imply
101/// constant physical memory: llvm.invariant.start.
102static void stripNonValidData(Module &M);
103
104// Find the GC strategy for a function, or null if it doesn't have one.
105static std::unique_ptr<GCStrategy> findGCStrategy(Function &F);
106
108
111 bool Changed = false;
112 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
113 for (Function &F : M) {
114 // Nothing to do for declarations.
115 if (F.isDeclaration() || F.empty())
116 continue;
117
118 // Policy choice says not to rewrite - the most common reason is that we're
119 // compiling code without a GCStrategy.
121 continue;
122
123 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
124 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
125 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
126 Changed |= runOnFunction(F, DT, TTI, TLI);
127 }
128 if (!Changed)
129 return PreservedAnalyses::all();
130
131 // stripNonValidData asserts that shouldRewriteStatepointsIn
132 // returns true for at least one function in the module. Since at least
133 // one function changed, we know that the precondition is satisfied.
135
139 return PA;
140}
141
142namespace {
143
144struct GCPtrLivenessData {
145 /// Values defined in this block.
147
148 /// Values used in this block (and thus live); does not included values
149 /// killed within this block.
151
152 /// Values live into this basic block (i.e. used by any
153 /// instruction in this basic block or ones reachable from here)
155
156 /// Values live out of this basic block (i.e. live into
157 /// any successor block)
159};
160
161// The type of the internal cache used inside the findBasePointers family
162// of functions. From the callers perspective, this is an opaque type and
163// should not be inspected.
164//
165// In the actual implementation this caches two relations:
166// - The base relation itself (i.e. this pointer is based on that one)
167// - The base defining value relation (i.e. before base_phi insertion)
168// Generally, after the execution of a full findBasePointer call, only the
169// base relation will remain. Internally, we add a mixture of the two
170// types, then update all the second type to the first type
171using DefiningValueMapTy = MapVector<Value *, Value *>;
172using IsKnownBaseMapTy = MapVector<Value *, bool>;
173using PointerToBaseTy = MapVector<Value *, Value *>;
174using StatepointLiveSetTy = SetVector<Value *>;
175using RematerializedValueMapTy =
177
178struct PartiallyConstructedSafepointRecord {
179 /// The set of values known to be live across this safepoint
180 StatepointLiveSetTy LiveSet;
181
182 /// The *new* gc.statepoint instruction itself. This produces the token
183 /// that normal path gc.relocates and the gc.result are tied to.
184 GCStatepointInst *StatepointToken;
185
186 /// Instruction to which exceptional gc relocates are attached
187 /// Makes it easier to iterate through them during relocationViaAlloca.
188 Instruction *UnwindToken;
189
190 /// Record live values we are rematerialized instead of relocating.
191 /// They are not included into 'LiveSet' field.
192 /// Maps rematerialized copy to it's original value.
193 RematerializedValueMapTy RematerializedValues;
194};
195
196struct RematerizlizationCandidateRecord {
197 // Chain from derived pointer to base.
199 // Original base.
200 Value *RootOfChain;
201 // Cost of chain.
203};
205
206} // end anonymous namespace
207
208static ArrayRef<Use> getDeoptBundleOperands(const ScalarOptions &Opts,
209 const CallBase *Call) {
210 std::optional<OperandBundleUse> DeoptBundle =
211 Call->getOperandBundle(LLVMContext::OB_deopt);
212
213 if (!DeoptBundle) {
214 assert(Opts.rs4gc_allow_statepoint_with_no_deopt_info &&
215 "Found non-leaf call without deopt info!");
216 return {};
217 }
218
219 return DeoptBundle->Inputs;
220}
221
222/// Compute the live-in set for every basic block in the function
224 GCPtrLivenessData &Data, GCStrategy *GC);
225
226/// Given results from the dataflow liveness computation, find the set of live
227/// Values at a particular instruction.
228static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
229 StatepointLiveSetTy &out, GCStrategy *GC);
230
231static bool isGCPointerType(Type *T, GCStrategy *GC) {
232 assert(GC && "GC Strategy for isGCPointerType cannot be null");
233
234 if (!isa<PointerType>(T))
235 return false;
236
237 // conservative - same as StatepointLowering
238 return GC->isGCManagedPointer(T).value_or(true);
239}
240
241// Return true if this type is one which a) is a gc pointer or contains a GC
242// pointer and b) is of a type this code expects to encounter as a live value.
243// (The insertion code will assert that a type which matches (a) and not (b)
244// is not encountered.)
246 // We fully support gc pointers
247 if (isGCPointerType(T, GC))
248 return true;
249 // We partially support vectors of gc pointers. The code will assert if it
250 // can't handle something.
251 if (auto VT = dyn_cast<VectorType>(T))
252 if (isGCPointerType(VT->getElementType(), GC))
253 return true;
254 return false;
255}
256
257#ifndef NDEBUG
258/// Returns true if this type contains a gc pointer whether we know how to
259/// handle that type or not.
260static bool containsGCPtrType(Type *Ty, GCStrategy *GC) {
261 if (isGCPointerType(Ty, GC))
262 return true;
263 if (VectorType *VT = dyn_cast<VectorType>(Ty))
264 return isGCPointerType(VT->getScalarType(), GC);
265 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
266 return containsGCPtrType(AT->getElementType(), GC);
267 if (StructType *ST = dyn_cast<StructType>(Ty))
268 return llvm::any_of(ST->elements(),
269 [GC](Type *Ty) { return containsGCPtrType(Ty, GC); });
270 return false;
271}
272
273// Returns true if this is a type which a) is a gc pointer or contains a GC
274// pointer and b) is of a type which the code doesn't expect (i.e. first class
275// aggregates). Used to trip assertions.
277 return containsGCPtrType(Ty, GC) && !isHandledGCPointerType(Ty, GC);
278}
279#endif
280
281// Return the name of the value suffixed with the provided value, or if the
282// value didn't have a name, the default value specified.
283static std::string suffixed_name_or(Value *V, StringRef Suffix,
284 StringRef DefaultName) {
285 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
286}
287
288// Conservatively identifies any definitions which might be live at the
289// given instruction. The analysis is performed immediately before the
290// given instruction. Values defined by that instruction are not considered
291// live. Values used by that instruction are considered live.
293 const ScalarOptions &Opts, DominatorTree &DT,
294 GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
295 PartiallyConstructedSafepointRecord &Result, GCStrategy *GC) {
296 StatepointLiveSetTy LiveSet;
297 findLiveSetAtInst(Call, OriginalLivenessData, LiveSet, GC);
298
299 if (Opts.spp_print_liveset) {
300 dbgs() << "Live Variables:\n";
301 for (Value *V : LiveSet)
302 dbgs() << " " << V->getName() << " " << *V << "\n";
303 }
304 if (Opts.spp_print_liveset_size) {
305 dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
306 dbgs() << "Number live values: " << LiveSet.size() << "\n";
307 }
308 Result.LiveSet = LiveSet;
309}
310
311/// Returns true if V is a known base.
312static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
313
314/// Caches the IsKnownBase flag for a value and asserts that it wasn't present
315/// in the cache before.
316static void setKnownBase(Value *V, bool IsKnownBase,
317 IsKnownBaseMapTy &KnownBases);
318
319static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
320 IsKnownBaseMapTy &KnownBases);
321
322/// Return a base defining value for the 'Index' element of the given vector
323/// instruction 'I'. If Index is null, returns a BDV for the entire vector
324/// 'I'. As an optimization, this method will try to determine when the
325/// element is known to already be a base pointer. If this can be established,
326/// the second value in the returned pair will be true. Note that either a
327/// vector or a pointer typed value can be returned. For the former, the
328/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
329/// If the later, the return pointer is a BDV (or possibly a base) for the
330/// particular element in 'I'.
331static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
332 IsKnownBaseMapTy &KnownBases) {
333 // Each case parallels findBaseDefiningValue below, see that code for
334 // detailed motivation.
335
336 auto Cached = Cache.find(I);
337 if (Cached != Cache.end())
338 return Cached->second;
339
340 if (isa<Argument>(I)) {
341 // An incoming argument to the function is a base pointer
342 Cache[I] = I;
343 setKnownBase(I, /* IsKnownBase */true, KnownBases);
344 return I;
345 }
346
347 if (isa<Constant>(I)) {
348 // Base of constant vector consists only of constant null pointers.
349 // For reasoning see similar case inside 'findBaseDefiningValue' function.
350 auto *CAZ = ConstantAggregateZero::get(I->getType());
351 Cache[I] = CAZ;
352 setKnownBase(CAZ, /* IsKnownBase */true, KnownBases);
353 return CAZ;
354 }
355
356 if (isa<LoadInst>(I)) {
357 Cache[I] = I;
358 setKnownBase(I, /* IsKnownBase */true, KnownBases);
359 return I;
360 }
361
363 // We don't know whether this vector contains entirely base pointers or
364 // not. To be conservatively correct, we treat it as a BDV and will
365 // duplicate code as needed to construct a parallel vector of bases.
366 Cache[I] = I;
367 setKnownBase(I, /* IsKnownBase */false, KnownBases);
368 return I;
369 }
370
372 // We don't know whether this vector contains entirely base pointers or
373 // not. To be conservatively correct, we treat it as a BDV and will
374 // duplicate code as needed to construct a parallel vector of bases.
375 // TODO: There a number of local optimizations which could be applied here
376 // for particular sufflevector patterns.
377 Cache[I] = I;
378 setKnownBase(I, /* IsKnownBase */false, KnownBases);
379 return I;
380 }
381
382 // The behavior of getelementptr instructions is the same for vector and
383 // non-vector data types.
384 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
385 auto *BDV =
386 findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
387 Cache[GEP] = BDV;
388 return BDV;
389 }
390
391 // The behavior of freeze instructions is the same for vector and
392 // non-vector data types.
393 if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
394 auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
395 Cache[Freeze] = BDV;
396 return BDV;
397 }
398
399 // If the pointer comes through a bitcast of a vector of pointers to
400 // a vector of another type of pointer, then look through the bitcast
401 if (auto *BC = dyn_cast<BitCastInst>(I)) {
402 auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
403 Cache[BC] = BDV;
404 return BDV;
405 }
406
407 // We assume that functions in the source language only return base
408 // pointers. This should probably be generalized via attributes to support
409 // both source language and internal functions.
410 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
411 Cache[I] = I;
412 setKnownBase(I, /* IsKnownBase */true, KnownBases);
413 return I;
414 }
415
416 // A PHI or Select is a base defining value. The outer findBasePointer
417 // algorithm is responsible for constructing a base value for this BDV.
419 "unknown vector instruction - no base found for vector element");
420 Cache[I] = I;
421 setKnownBase(I, /* IsKnownBase */false, KnownBases);
422 return I;
423}
424
425/// Helper function for findBasePointer - Will return a value which either a)
426/// defines the base pointer for the input, b) blocks the simple search
427/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
428/// from pointer to vector type or back.
429static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
430 IsKnownBaseMapTy &KnownBases) {
431 assert(I->getType()->isPtrOrPtrVectorTy() &&
432 "Illegal to ask for the base pointer of a non-pointer type");
433 auto Cached = Cache.find(I);
434 if (Cached != Cache.end())
435 return Cached->second;
436
437 if (I->getType()->isVectorTy())
438 return findBaseDefiningValueOfVector(I, Cache, KnownBases);
439
440 if (isa<Argument>(I)) {
441 // An incoming argument to the function is a base pointer
442 // We should have never reached here if this argument isn't an gc value
443 Cache[I] = I;
444 setKnownBase(I, /* IsKnownBase */true, KnownBases);
445 return I;
446 }
447
448 if (isa<Constant>(I)) {
449 // We assume that objects with a constant base (e.g. a global) can't move
450 // and don't need to be reported to the collector because they are always
451 // live. Besides global references, all kinds of constants (e.g. undef,
452 // constant expressions, null pointers) can be introduced by the inliner or
453 // the optimizer, especially on dynamically dead paths.
454 // Here we treat all of them as having single null base. By doing this we
455 // trying to avoid problems reporting various conflicts in a form of
456 // "phi (const1, const2)" or "phi (const, regular gc ptr)".
457 // See constant.ll file for relevant test cases.
458
459 auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
460 Cache[I] = CPN;
461 setKnownBase(CPN, /* IsKnownBase */true, KnownBases);
462 return CPN;
463 }
464
465 // inttoptrs in an integral address space are currently ill-defined. We
466 // treat them as defining base pointers here for consistency with the
467 // constant rule above and because we don't really have a better semantic
468 // to give them. Note that the optimizer is always free to insert undefined
469 // behavior on dynamically dead paths as well.
470 if (isa<IntToPtrInst>(I)) {
471 Cache[I] = I;
472 setKnownBase(I, /* IsKnownBase */true, KnownBases);
473 return I;
474 }
475
476 if (CastInst *CI = dyn_cast<CastInst>(I)) {
477 Value *Def = CI->stripPointerCasts();
478 // If stripping pointer casts changes the address space there is an
479 // addrspacecast in between.
480 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
481 cast<PointerType>(CI->getType())->getAddressSpace() &&
482 "unsupported addrspacecast");
483 // If we find a cast instruction here, it means we've found a cast which is
484 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
485 // handle int->ptr conversion.
486 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
487 auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
488 Cache[CI] = BDV;
489 return BDV;
490 }
491
492 if (isa<LoadInst>(I)) {
493 // The value loaded is an gc base itself
494 Cache[I] = I;
495 setKnownBase(I, /* IsKnownBase */true, KnownBases);
496 return I;
497 }
498
500 // The base of this GEP is the base
501 auto *BDV =
502 findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
503 Cache[GEP] = BDV;
504 return BDV;
505 }
506
507 if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
508 auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
509 Cache[Freeze] = BDV;
510 return BDV;
511 }
512
514 switch (II->getIntrinsicID()) {
515 default:
516 // fall through to general call handling
517 break;
518 case Intrinsic::experimental_gc_statepoint:
519 llvm_unreachable("statepoints don't produce pointers");
520 case Intrinsic::experimental_gc_relocate:
521 // Rerunning safepoint insertion after safepoints are already
522 // inserted is not supported. It could probably be made to work,
523 // but why are you doing this? There's no good reason.
524 llvm_unreachable("repeat safepoint insertion is not supported");
525 case Intrinsic::gcroot:
526 // Currently, this mechanism hasn't been extended to work with gcroot.
527 // There's no reason it couldn't be, but I haven't thought about the
528 // implications much.
530 "interaction with the gcroot mechanism is not supported");
531 case Intrinsic::experimental_gc_get_pointer_base:
532 auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
533 Cache[II] = BDV;
534 return BDV;
535 }
536 }
537 // We assume that functions in the source language only return base
538 // pointers. This should probably be generalized via attributes to support
539 // both source language and internal functions.
540 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
541 Cache[I] = I;
542 setKnownBase(I, /* IsKnownBase */true, KnownBases);
543 return I;
544 }
545
546 // TODO: I have absolutely no idea how to implement this part yet. It's not
547 // necessarily hard, I just haven't really looked at it yet.
548 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
549
551 // A CAS is effectively a atomic store and load combined under a
552 // predicate. From the perspective of base pointers, we just treat it
553 // like a load.
554 Cache[I] = I;
555 setKnownBase(I, /* IsKnownBase */true, KnownBases);
556 return I;
557 }
558
559 if (isa<AtomicRMWInst>(I)) {
560 assert(cast<AtomicRMWInst>(I)->getOperation() == AtomicRMWInst::Xchg &&
561 "Only Xchg is allowed for pointer values");
562 // A RMW Xchg is a combined atomic load and store, so we can treat the
563 // loaded value as a base pointer.
564 Cache[I] = I;
565 setKnownBase(I, /* IsKnownBase */ true, KnownBases);
566 return I;
567 }
568
569 // The aggregate ops. Aggregates can either be in the heap or on the
570 // stack, but in either case, this is simply a field load. As a result,
571 // this is a defining definition of the base just like a load is.
573 Cache[I] = I;
574 setKnownBase(I, /* IsKnownBase */true, KnownBases);
575 return I;
576 }
577
578 // We should never see an insert vector since that would require we be
579 // tracing back a struct value not a pointer value.
581 "Base pointer for a struct is meaningless");
582
583 // This value might have been generated by findBasePointer() called when
584 // substituting gc.get.pointer.base() intrinsic.
585 bool IsKnownBase =
586 isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
587 setKnownBase(I, /* IsKnownBase */IsKnownBase, KnownBases);
588 Cache[I] = I;
589
590 // An extractelement produces a base result exactly when it's input does.
591 // We may need to insert a parallel instruction to extract the appropriate
592 // element out of the base vector corresponding to the input. Given this,
593 // it's analogous to the phi and select case even though it's not a merge.
595 // Note: There a lot of obvious peephole cases here. This are deliberately
596 // handled after the main base pointer inference algorithm to make writing
597 // test cases to exercise that code easier.
598 return I;
599
600 // The last two cases here don't return a base pointer. Instead, they
601 // return a value which dynamically selects from among several base
602 // derived pointers (each with it's own base potentially). It's the job of
603 // the caller to resolve these.
605 "missing instruction case in findBaseDefiningValue");
606 return I;
607}
608
609/// Returns the base defining value for this value.
610static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
611 IsKnownBaseMapTy &KnownBases) {
612 if (!Cache.contains(I)) {
613 auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
614 Cache[I] = BDV;
615 LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
616 << Cache[I]->getName() << ", is known base = "
617 << KnownBases[I] << "\n");
618 }
619 assert(Cache[I] != nullptr);
620 assert(KnownBases.contains(Cache[I]) &&
621 "Cached value must be present in known bases map");
622 return Cache[I];
623}
624
625/// Return a base pointer for this value if known. Otherwise, return it's
626/// base defining value.
627static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
628 IsKnownBaseMapTy &KnownBases) {
629 Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
630 auto Found = Cache.find(Def);
631 if (Found != Cache.end()) {
632 // Either a base-of relation, or a self reference. Caller must check.
633 return Found->second;
634 }
635 // Only a BDV available
636 return Def;
637}
638
639#ifndef NDEBUG
640/// This value is a base pointer that is not generated by RS4GC, i.e. it already
641/// exists in the code.
643 // no recursion possible
644 return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
647}
648#endif
649
650static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
651 auto It = KnownBases.find(V);
652 assert(It != KnownBases.end() && "Value not present in the map");
653 return It->second;
654}
655
656static void setKnownBase(Value *V, bool IsKnownBase,
657 IsKnownBaseMapTy &KnownBases) {
658#ifndef NDEBUG
659 auto It = KnownBases.find(V);
660 if (It != KnownBases.end())
661 assert(It->second == IsKnownBase && "Changing already present value");
662#endif
663 KnownBases[V] = IsKnownBase;
664}
665
666// Returns true if First and Second values are both scalar or both vector.
667static bool areBothVectorOrScalar(Value *First, Value *Second) {
668 return isa<VectorType>(First->getType()) ==
669 isa<VectorType>(Second->getType());
670}
671
672namespace {
673
674/// Models the state of a single base defining value in the findBasePointer
675/// algorithm for determining where a new instruction is needed to propagate
676/// the base of this BDV.
677class BDVState {
678public:
679 enum StatusTy {
680 // Starting state of lattice
681 Unknown,
682 // Some specific base value -- does *not* mean that instruction
683 // propagates the base of the object
684 // ex: gep %arg, 16 -> %arg is the base value
685 Base,
686 // Need to insert a node to represent a merge.
687 Conflict
688 };
689
690 BDVState() {
691 llvm_unreachable("missing state in map");
692 }
693
694 explicit BDVState(Value *OriginalValue)
695 : OriginalValue(OriginalValue) {}
696 explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
697 : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
698 assert(Status != Base || BaseValue);
699 }
700
701 StatusTy getStatus() const { return Status; }
702 Value *getOriginalValue() const { return OriginalValue; }
703 Value *getBaseValue() const { return BaseValue; }
704
705 bool isBase() const { return getStatus() == Base; }
706 bool isUnknown() const { return getStatus() == Unknown; }
707 bool isConflict() const { return getStatus() == Conflict; }
708
709 // Values of type BDVState form a lattice, and this function implements the
710 // meet
711 // operation.
712 void meet(const BDVState &Other) {
713 auto markConflict = [&]() {
714 Status = BDVState::Conflict;
715 BaseValue = nullptr;
716 };
717 // Conflict is a final state.
718 if (isConflict())
719 return;
720 // if we are not known - just take other state.
721 if (isUnknown()) {
722 Status = Other.getStatus();
723 BaseValue = Other.getBaseValue();
724 return;
725 }
726 // We are base.
727 assert(isBase() && "Unknown state");
728 // If other is unknown - just keep our state.
729 if (Other.isUnknown())
730 return;
731 // If other is conflict - it is a final state.
732 if (Other.isConflict())
733 return markConflict();
734 // Other is base as well.
735 assert(Other.isBase() && "Unknown state");
736 // If bases are different - Conflict.
737 if (getBaseValue() != Other.getBaseValue())
738 return markConflict();
739 // We are identical, do nothing.
740 }
741
742 bool operator==(const BDVState &Other) const {
743 return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
744 Status == Other.Status;
745 }
746
747 bool operator!=(const BDVState &other) const { return !(*this == other); }
748
750 void dump() const {
751 print(dbgs());
752 dbgs() << '\n';
753 }
754
755 void print(raw_ostream &OS) const {
756 switch (getStatus()) {
757 case Unknown:
758 OS << "U";
759 break;
760 case Base:
761 OS << "B";
762 break;
763 case Conflict:
764 OS << "C";
765 break;
766 }
767 OS << " (base " << getBaseValue() << " - "
768 << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
769 << " for " << OriginalValue->getName() << ":";
770 }
771
772private:
773 AssertingVH<Value> OriginalValue; // instruction this state corresponds to
774 StatusTy Status = Unknown;
775 AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
776};
777
778} // end anonymous namespace
779
780#ifndef NDEBUG
781static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
782 State.print(OS);
783 return OS;
784}
785#endif
786
787/// For a given value or instruction, figure out what base ptr its derived from.
788/// For gc objects, this is simply itself. On success, returns a value which is
789/// the base pointer. (This is reliable and can be used for relocation.) On
790/// failure, returns nullptr.
791static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
792 IsKnownBaseMapTy &KnownBases) {
793 Value *Def = findBaseOrBDV(I, Cache, KnownBases);
794
795 if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
796 return Def;
797
798 // Here's the rough algorithm:
799 // - For every SSA value, construct a mapping to either an actual base
800 // pointer or a PHI which obscures the base pointer.
801 // - Construct a mapping from PHI to unknown TOP state. Use an
802 // optimistic algorithm to propagate base pointer information. Lattice
803 // looks like:
804 // UNKNOWN
805 // b1 b2 b3 b4
806 // CONFLICT
807 // When algorithm terminates, all PHIs will either have a single concrete
808 // base or be in a conflict state.
809 // - For every conflict, insert a dummy PHI node without arguments. Add
810 // these to the base[Instruction] = BasePtr mapping. For every
811 // non-conflict, add the actual base.
812 // - For every conflict, add arguments for the base[a] of each input
813 // arguments.
814 //
815 // Note: A simpler form of this would be to add the conflict form of all
816 // PHIs without running the optimistic algorithm. This would be
817 // analogous to pessimistic data flow and would likely lead to an
818 // overall worse solution.
819
820#ifndef NDEBUG
821 auto isExpectedBDVType = [](Value *BDV) {
822 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
825 };
826#endif
827
828 // Once populated, will contain a mapping from each potentially non-base BDV
829 // to a lattice value (described above) which corresponds to that BDV.
830 // We use the order of insertion (DFS over the def/use graph) to provide a
831 // stable deterministic ordering for visiting DenseMaps (which are unordered)
832 // below. This is important for deterministic compilation.
834
835#ifndef NDEBUG
836 auto VerifyStates = [&]() {
837 for (auto &Entry : States) {
838 assert(Entry.first == Entry.second.getOriginalValue());
839 }
840 };
841#endif
842
843 auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
844 if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
845 for (Value *InVal : PN->incoming_values())
846 F(InVal);
847 } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
848 F(SI->getTrueValue());
849 F(SI->getFalseValue());
850 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
851 F(EE->getVectorOperand());
852 } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
853 F(IE->getOperand(0));
854 F(IE->getOperand(1));
855 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
856 // For a canonical broadcast, ignore the undef argument
857 // (without this, we insert a parallel base shuffle for every broadcast)
858 F(SV->getOperand(0));
859 if (!SV->isZeroEltSplat())
860 F(SV->getOperand(1));
861 } else {
862 llvm_unreachable("unexpected BDV type");
863 }
864 };
865
866
867 // Recursively fill in all base defining values reachable from the initial
868 // one for which we don't already know a definite base value for
869 /* scope */ {
871 Worklist.push_back(Def);
872 States.insert({Def, BDVState(Def)});
873 while (!Worklist.empty()) {
874 Value *Current = Worklist.pop_back_val();
875 assert(!isOriginalBaseResult(Current) && "why did it get added?");
876
877 auto visitIncomingValue = [&](Value *InVal) {
878 Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
879 if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
880 // Known bases won't need new instructions introduced and can be
881 // ignored safely. However, this can only be done when InVal and Base
882 // are both scalar or both vector. Otherwise, we need to find a
883 // correct BDV for InVal, by creating an entry in the lattice
884 // (States).
885 return;
886 assert(isExpectedBDVType(Base) && "the only non-base values "
887 "we see should be base defining values");
888 if (States.insert(std::make_pair(Base, BDVState(Base))).second)
889 Worklist.push_back(Base);
890 };
891
892 visitBDVOperands(Current, visitIncomingValue);
893 }
894 }
895
896#ifndef NDEBUG
897 VerifyStates();
898 LLVM_DEBUG(dbgs() << "States after initialization:\n");
899 for (const auto &Pair : States) {
900 LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
901 }
902#endif
903
904 // Iterate forward through the value graph pruning any node from the state
905 // list where all of the inputs are base pointers. The purpose of this is to
906 // reuse existing values when the derived pointer we were asked to materialize
907 // a base pointer for happens to be a base pointer itself. (Or a sub-graph
908 // feeding it does.)
910 do {
911 ToRemove.clear();
912 for (auto Pair : States) {
913 Value *BDV = Pair.first;
914 auto canPruneInput = [&](Value *V) {
915 // If the input of the BDV is the BDV itself we can prune it. This is
916 // only possible if the BDV is a PHI node.
917 if (V->stripPointerCasts() == BDV)
918 return true;
919 Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
920 if (V->stripPointerCasts() != VBDV)
921 return false;
922 // The assumption is that anything not in the state list is
923 // propagates a base pointer.
924 return States.count(VBDV) == 0;
925 };
926
927 bool CanPrune = true;
928 visitBDVOperands(BDV, [&](Value *Op) {
929 CanPrune = CanPrune && canPruneInput(Op);
930 });
931 if (CanPrune)
932 ToRemove.push_back(BDV);
933 }
934 for (Value *V : ToRemove) {
935 States.erase(V);
936 // Cache the fact V is it's own base for later usage.
937 Cache[V] = V;
938 }
939 } while (!ToRemove.empty());
940
941 // Did we manage to prove that Def itself must be a base pointer?
942 if (!States.count(Def))
943 return Def;
944
945 // Return a phi state for a base defining value. We'll generate a new
946 // base state for known bases and expect to find a cached state otherwise.
947 auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
948 auto I = States.find(BaseValue);
949 if (I != States.end())
950 return I->second;
952 return BDVState(BaseValue, BDVState::Base, BaseValue);
953 };
954
955 // Even though we have identified a concrete base (or a conflict) for all live
956 // pointers at this point, there are cases where the base is of an
957 // incompatible type compared to the original instruction. We conservatively
958 // mark those as conflicts to ensure that corresponding BDVs will be generated
959 // in the next steps.
960
961 // this is a rather explicit check for all cases where we should mark the
962 // state as a conflict to force the latter stages of the algorithm to emit
963 // the BDVs.
964 // TODO: in many cases the instructions emited for the conflicting states
965 // will be identical to the I itself (if the I's operate on their BDVs
966 // themselves). We should exploit this, but can't do it here since it would
967 // break the invariant about the BDVs not being known to be a base.
968 // TODO: the code also does not handle constants at all - the algorithm relies
969 // on all constants having the same BDV and therefore constant-only insns
970 // will never be in conflict, but this check is ignored here. If the
971 // constant conflicts will be to BDVs themselves, they will be identical
972 // instructions and will get optimized away (as in the above TODO)
973 auto MarkConflict = [&](Instruction *I, Value *BaseValue) {
974 // II and EE mixes vector & scalar so is always a conflict
976 return true;
977 // Shuffle vector is always a conflict as it creates new vector from
978 // existing ones.
980 return true;
981 // Any instructions where the computed base type differs from the
982 // instruction type. An example is where an extract instruction is used by a
983 // select. Here the select's BDV is a vector (because of extract's BDV),
984 // while the select itself is a scalar type. Note that the IE and EE
985 // instruction check is not fully subsumed by the vector<->scalar check at
986 // the end, this is due to the BDV algorithm being ignorant of BDV types at
987 // this junction.
988 if (!areBothVectorOrScalar(BaseValue, I))
989 return true;
990 return false;
991 };
992
993 bool Progress = true;
994 while (Progress) {
995#ifndef NDEBUG
996 const size_t OldSize = States.size();
997#endif
998 Progress = false;
999 // We're only changing values in this loop, thus safe to keep iterators.
1000 // Since this is computing a fixed point, the order of visit does not
1001 // effect the result. TODO: We could use a worklist here and make this run
1002 // much faster.
1003 for (auto Pair : States) {
1004 Value *BDV = Pair.first;
1005 // Only values that do not have known bases or those that have differing
1006 // type (scalar versus vector) from a possible known base should be in the
1007 // lattice.
1008 assert((!isKnownBase(BDV, KnownBases) ||
1009 !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
1010 "why did it get added?");
1011
1012 BDVState NewState(BDV);
1013 visitBDVOperands(BDV, [&](Value *Op) {
1014 Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
1015 auto OpState = GetStateForBDV(BDV, Op);
1016 NewState.meet(OpState);
1017 });
1018
1019 // if the instruction has known base, but should in fact be marked as
1020 // conflict because of incompatible in/out types, we mark it as such
1021 // ensuring that it will propagate through the fixpoint iteration
1022 auto I = cast<Instruction>(BDV);
1023 auto BV = NewState.getBaseValue();
1024 if (BV && MarkConflict(I, BV))
1025 NewState = BDVState(I, BDVState::Conflict);
1026
1027 BDVState OldState = Pair.second;
1028 if (OldState != NewState) {
1029 Progress = true;
1030 States[BDV] = NewState;
1031 }
1032 }
1033
1034 assert(OldSize == States.size() &&
1035 "fixed point shouldn't be adding any new nodes to state");
1036 }
1037
1038#ifndef NDEBUG
1039 VerifyStates();
1040 LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
1041 for (const auto &Pair : States) {
1042 LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
1043 }
1044
1045 // since we do the conflict marking as part of the fixpoint iteration this
1046 // loop only asserts that invariants are met
1047 for (auto Pair : States) {
1048 Instruction *I = cast<Instruction>(Pair.first);
1049 BDVState State = Pair.second;
1050 auto *BaseValue = State.getBaseValue();
1051 // Only values that do not have known bases or those that have differing
1052 // type (scalar versus vector) from a possible known base should be in the
1053 // lattice.
1054 assert(
1055 (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
1056 "why did it get added?");
1057 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1058 }
1059#endif
1060
1061 // Insert Phis for all conflicts
1062 // TODO: adjust naming patterns to avoid this order of iteration dependency
1063 for (auto Pair : States) {
1064 Instruction *I = cast<Instruction>(Pair.first);
1065 BDVState State = Pair.second;
1066 // Only values that do not have known bases or those that have differing
1067 // type (scalar versus vector) from a possible known base should be in the
1068 // lattice.
1069 assert((!isKnownBase(I, KnownBases) ||
1070 !areBothVectorOrScalar(I, State.getBaseValue())) &&
1071 "why did it get added?");
1072 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1073
1074 // Since we're joining a vector and scalar base, they can never be the
1075 // same. As a result, we should always see insert element having reached
1076 // the conflict state.
1077 assert(!isa<InsertElementInst>(I) || State.isConflict());
1078
1079 if (!State.isConflict())
1080 continue;
1081
1082 auto getMangledName = [](Instruction *I) -> std::string {
1083 if (isa<PHINode>(I)) {
1084 return suffixed_name_or(I, ".base", "base_phi");
1085 } else if (isa<SelectInst>(I)) {
1086 return suffixed_name_or(I, ".base", "base_select");
1087 } else if (isa<ExtractElementInst>(I)) {
1088 return suffixed_name_or(I, ".base", "base_ee");
1089 } else if (isa<InsertElementInst>(I)) {
1090 return suffixed_name_or(I, ".base", "base_ie");
1091 } else {
1092 return suffixed_name_or(I, ".base", "base_sv");
1093 }
1094 };
1095
1096 Instruction *BaseInst = I->clone();
1097 BaseInst->insertBefore(I->getIterator());
1098 BaseInst->setName(getMangledName(I));
1099 // Add metadata marking this as a base value
1100 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1101 States[I] = BDVState(I, BDVState::Conflict, BaseInst);
1102 setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1103 }
1104
1105#ifndef NDEBUG
1106 VerifyStates();
1107#endif
1108
1109 // Returns a instruction which produces the base pointer for a given
1110 // instruction. The instruction is assumed to be an input to one of the BDVs
1111 // seen in the inference algorithm above. As such, we must either already
1112 // know it's base defining value is a base, or have inserted a new
1113 // instruction to propagate the base of it's BDV and have entered that newly
1114 // introduced instruction into the state table. In either case, we are
1115 // assured to be able to determine an instruction which produces it's base
1116 // pointer.
1117 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
1118 Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
1119 Value *Base = nullptr;
1120 if (auto It = States.find(BDV); It == States.end()) {
1122 Base = BDV;
1123 } else {
1124 // Either conflict or base.
1125 Base = It->second.getBaseValue();
1126 }
1127 assert(Base && "Can't be null");
1128 // The cast is needed since base traversal may strip away bitcasts
1129 if (Base->getType() != Input->getType() && InsertPt)
1130 Base = new BitCastInst(Base, Input->getType(), "cast",
1131 InsertPt->getIterator());
1132 return Base;
1133 };
1134
1135 // Fixup all the inputs of the new PHIs. Visit order needs to be
1136 // deterministic and predictable because we're naming newly created
1137 // instructions.
1138 for (auto Pair : States) {
1139 Instruction *BDV = cast<Instruction>(Pair.first);
1140 BDVState State = Pair.second;
1141
1142 // Only values that do not have known bases or those that have differing
1143 // type (scalar versus vector) from a possible known base should be in the
1144 // lattice.
1145 assert((!isKnownBase(BDV, KnownBases) ||
1146 !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
1147 "why did it get added?");
1148 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1149 if (!State.isConflict())
1150 continue;
1151
1152 if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1153 PHINode *PN = cast<PHINode>(BDV);
1154 const unsigned NumPHIValues = PN->getNumIncomingValues();
1155
1156 // The IR verifier requires phi nodes with multiple entries from the
1157 // same basic block to have the same incoming value for each of those
1158 // entries. Since we're inserting bitcasts in the loop, make sure we
1159 // do so at least once per incoming block.
1160 DenseMap<BasicBlock *, Value*> BlockToValue;
1161 for (unsigned i = 0; i < NumPHIValues; i++) {
1162 Value *InVal = PN->getIncomingValue(i);
1163 BasicBlock *InBB = PN->getIncomingBlock(i);
1164 auto [It, Inserted] = BlockToValue.try_emplace(InBB);
1165 if (Inserted)
1166 It->second = getBaseForInput(InVal, InBB->getTerminator());
1167 else {
1168#ifndef NDEBUG
1169 Value *OldBase = It->second;
1170 Value *Base = getBaseForInput(InVal, nullptr);
1171
1172 // We can't use `stripPointerCasts` instead of this function because
1173 // `stripPointerCasts` doesn't handle vectors of pointers.
1174 auto StripBitCasts = [](Value *V) -> Value * {
1175 while (auto *BC = dyn_cast<BitCastInst>(V))
1176 V = BC->getOperand(0);
1177 return V;
1178 };
1179 // In essence this assert states: the only way two values
1180 // incoming from the same basic block may be different is by
1181 // being different bitcasts of the same value. A cleanup
1182 // that remains TODO is changing findBaseOrBDV to return an
1183 // llvm::Value of the correct type (and still remain pure).
1184 // This will remove the need to add bitcasts.
1185 assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
1186 "findBaseOrBDV should be pure!");
1187#endif
1188 }
1189 Value *Base = It->second;
1190 BasePHI->setIncomingValue(i, Base);
1191 }
1192 } else if (SelectInst *BaseSI =
1193 dyn_cast<SelectInst>(State.getBaseValue())) {
1195
1196 // Find the instruction which produces the base for each input.
1197 // We may need to insert a bitcast.
1198 BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1199 BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
1200 } else if (auto *BaseEE =
1201 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1202 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1203 // Find the instruction which produces the base for each input. We may
1204 // need to insert a bitcast.
1205 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1206 } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1207 auto *BdvIE = cast<InsertElementInst>(BDV);
1208 auto UpdateOperand = [&](int OperandIdx) {
1209 Value *InVal = BdvIE->getOperand(OperandIdx);
1210 Value *Base = getBaseForInput(InVal, BaseIE);
1211 BaseIE->setOperand(OperandIdx, Base);
1212 };
1213 UpdateOperand(0); // vector operand
1214 UpdateOperand(1); // scalar operand
1215 } else {
1216 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1217 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1218 auto UpdateOperand = [&](int OperandIdx) {
1219 Value *InVal = BdvSV->getOperand(OperandIdx);
1220 Value *Base = getBaseForInput(InVal, BaseSV);
1221 BaseSV->setOperand(OperandIdx, Base);
1222 };
1223 UpdateOperand(0); // vector operand
1224 if (!BdvSV->isZeroEltSplat())
1225 UpdateOperand(1); // vector operand
1226 else {
1227 // Never read, so just use poison
1228 Value *InVal = BdvSV->getOperand(1);
1229 BaseSV->setOperand(1, PoisonValue::get(InVal->getType()));
1230 }
1231 }
1232 }
1233
1234#ifndef NDEBUG
1235 VerifyStates();
1236#endif
1237
1238 // get the data layout to compare the sizes of base/derived pointer values
1239 [[maybe_unused]] auto &DL =
1240 cast<llvm::Instruction>(Def)->getDataLayout();
1241 // Cache all of our results so we can cheaply reuse them
1242 // NOTE: This is actually two caches: one of the base defining value
1243 // relation and one of the base pointer relation! FIXME
1244 for (auto Pair : States) {
1245 auto *BDV = Pair.first;
1246 Value *Base = Pair.second.getBaseValue();
1247 assert(BDV && Base);
1248 // Whenever we have a derived ptr(s), their base
1249 // ptr(s) must be of the same size, not necessarily the same type
1250 assert(DL.getTypeAllocSize(BDV->getType()) ==
1251 DL.getTypeAllocSize(Base->getType()) &&
1252 "Derived and base values should have same size");
1253 // Only values that do not have known bases or those that have differing
1254 // type (scalar versus vector) from a possible known base should be in the
1255 // lattice.
1256 assert(
1257 (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
1258 "why did it get added?");
1259
1260 LLVM_DEBUG(
1261 dbgs() << "Updating base value cache"
1262 << " for: " << BDV->getName() << " from: "
1263 << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1264 << " to: " << Base->getName() << "\n");
1265
1266 Cache[BDV] = Base;
1267 }
1268 assert(Cache.count(Def));
1269 return Cache[Def];
1270}
1271
1272// For a set of live pointers (base and/or derived), identify the base
1273// pointer of the object which they are derived from. This routine will
1274// mutate the IR graph as needed to make the 'base' pointer live at the
1275// definition site of 'derived'. This ensures that any use of 'derived' can
1276// also use 'base'. This may involve the insertion of a number of
1277// additional PHI nodes.
1278//
1279// preconditions: live is a set of pointer type Values
1280//
1281// side effects: may insert PHI nodes into the existing CFG, will preserve
1282// CFG, will not remove or mutate any existing nodes
1283//
1284// post condition: PointerToBase contains one (derived, base) pair for every
1285// pointer in live. Note that derived can be equal to base if the original
1286// pointer was a base pointer.
1287static void findBasePointers(const StatepointLiveSetTy &live,
1288 PointerToBaseTy &PointerToBase, DominatorTree *DT,
1289 DefiningValueMapTy &DVCache,
1290 IsKnownBaseMapTy &KnownBases) {
1291 for (Value *ptr : live) {
1292 Value *base = findBasePointer(ptr, DVCache, KnownBases);
1293 assert(base && "failed to find base pointer");
1294 PointerToBase[ptr] = base;
1295 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1296 DT->dominates(cast<Instruction>(base)->getParent(),
1297 cast<Instruction>(ptr)->getParent())) &&
1298 "The base we found better dominate the derived pointer");
1299 }
1300}
1301
1302/// Find the required based pointers (and adjust the live set) for the given
1303/// parse point.
1304static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1305 CallBase *Call,
1306 PartiallyConstructedSafepointRecord &result,
1307 PointerToBaseTy &PointerToBase,
1308 IsKnownBaseMapTy &KnownBases) {
1309 StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
1310 // We assume that all pointers passed to deopt are base pointers; as an
1311 // optimization, we can use this to avoid separately materializing the base
1312 // pointer graph. This is only relevant since we're very conservative about
1313 // generating new conflict nodes during base pointer insertion. If we were
1314 // smarter there, this would be irrelevant.
1315 if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
1316 for (Value *V : Opt->Inputs) {
1317 if (!PotentiallyDerivedPointers.count(V))
1318 continue;
1319 PotentiallyDerivedPointers.remove(V);
1320 PointerToBase[V] = V;
1321 }
1322 findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
1323 KnownBases);
1324}
1325
1326/// Given an updated version of the dataflow liveness results, update the
1327/// liveset and base pointer maps for the call site CS.
1328static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1329 CallBase *Call,
1330 PartiallyConstructedSafepointRecord &result,
1331 PointerToBaseTy &PointerToBase,
1332 GCStrategy *GC);
1333
1337 PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1338 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1339 // again. The old values are still live and will help it stabilize quickly.
1340 GCPtrLivenessData RevisedLivenessData;
1341 computeLiveInValues(DT, F, RevisedLivenessData, GC);
1342 for (size_t i = 0; i < records.size(); i++) {
1343 struct PartiallyConstructedSafepointRecord &info = records[i];
1344 recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info, PointerToBase,
1345 GC);
1346 }
1347}
1348
1349// Utility function which clones all instructions from "ChainToBase"
1350// and inserts them before "InsertBefore". Returns rematerialized value
1351// which should be used after statepoint.
1353 BasicBlock::iterator InsertBefore,
1354 Value *RootOfChain,
1355 Value *AlternateLiveBase) {
1356 Instruction *LastClonedValue = nullptr;
1357 Instruction *LastValue = nullptr;
1358 // Walk backwards to visit top-most instructions first.
1359 for (Instruction *Instr : reverse(ChainToBase)) {
1360 // Only GEP's and casts are supported as we need to be careful to not
1361 // introduce any new uses of pointers not in the liveset.
1362 // Note that it's fine to introduce new uses of pointers which were
1363 // otherwise not used after this statepoint.
1365
1366 Instruction *ClonedValue = Instr->clone();
1367 ClonedValue->insertBefore(InsertBefore);
1368 ClonedValue->setName(Instr->getName() + ".remat");
1369
1370 // If it is not first instruction in the chain then it uses previously
1371 // cloned value. We should update it to use cloned value.
1372 if (LastClonedValue) {
1373 assert(LastValue);
1374 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1375#ifndef NDEBUG
1376 for (auto *OpValue : ClonedValue->operand_values()) {
1377 // Assert that cloned instruction does not use any instructions from
1378 // this chain other than LastClonedValue
1379 assert(!is_contained(ChainToBase, OpValue) &&
1380 "incorrect use in rematerialization chain");
1381 // Assert that the cloned instruction does not use the RootOfChain
1382 // or the AlternateLiveBase.
1383 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
1384 }
1385#endif
1386 } else {
1387 // For the first instruction, replace the use of unrelocated base i.e.
1388 // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
1389 // live set. They have been proved to be the same PHI nodes. Note
1390 // that the *only* use of the RootOfChain in the ChainToBase list is
1391 // the first Value in the list.
1392 if (RootOfChain != AlternateLiveBase)
1393 ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
1394 }
1395
1396 LastClonedValue = ClonedValue;
1397 LastValue = Instr;
1398 }
1399 assert(LastClonedValue);
1400 return LastClonedValue;
1401}
1402
1403// When inserting gc.relocate and gc.result calls, we need to ensure there are
1404// no uses of the original value / return value between the gc.statepoint and
1405// the gc.relocate / gc.result call. One case which can arise is a phi node
1406// starting one of the successor blocks. We also need to be able to insert the
1407// gc.relocates only on the path which goes through the statepoint. We might
1408// need to split an edge to make this possible.
1409static BasicBlock *
1411 DominatorTree &DT) {
1412 BasicBlock *Ret = BB;
1413 if (!BB->getUniquePredecessor())
1414 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1415
1416 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1417 // from it
1419 assert(!isa<PHINode>(Ret->begin()) &&
1420 "All PHI nodes should have been removed!");
1421
1422 // At this point, we can safely insert a gc.relocate or gc.result as the first
1423 // instruction in Ret if needed.
1424 return Ret;
1425}
1426
1427// List of all function attributes which must be stripped when lowering from
1428// abstract machine model to physical machine model. Essentially, these are
1429// all the effects a safepoint might have which we ignored in the abstract
1430// machine model for purposes of optimization. We have to strip these on
1431// both function declarations and call sites.
1433 {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
1434
1435// Create new attribute set containing only attributes which can be transferred
1436// from the original call to the safepoint.
1438 AttributeList StatepointAL) {
1439 AttributeList OrigAL = Call->getAttributes();
1440 if (OrigAL.isEmpty())
1441 return StatepointAL;
1442
1443 // Remove the readonly, readnone, and statepoint function attributes.
1444 LLVMContext &Ctx = Call->getContext();
1445 AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
1446 for (auto Attr : FnAttrsToStrip)
1447 FnAttrs.removeAttribute(Attr);
1448
1449 for (Attribute A : OrigAL.getFnAttrs()) {
1451 FnAttrs.removeAttribute(A);
1452 }
1453
1454 StatepointAL = StatepointAL.addFnAttributes(Ctx, FnAttrs);
1455
1456 // The memory intrinsics do not have a 1:1 correspondence of the original
1457 // call arguments to the produced statepoint. Do not transfer the argument
1458 // attributes to avoid putting them on incorrect arguments.
1459 if (IsMemIntrinsic)
1460 return StatepointAL;
1461
1462 // Attach the argument attributes from the original call at the corresponding
1463 // arguments in the statepoint. Note that any argument attributes that are
1464 // invalid after lowering are stripped in stripNonValidDataFromBody.
1465 for (unsigned I : llvm::seq(Call->arg_size()))
1466 StatepointAL = StatepointAL.addParamAttributes(
1468 AttrBuilder(Ctx, OrigAL.getParamAttrs(I)));
1469
1470 // Return attributes are later attached to the gc.result intrinsic.
1471 return StatepointAL;
1472}
1473
1474/// Helper function to place all gc relocates necessary for the given
1475/// statepoint.
1476/// Inputs:
1477/// liveVariables - list of variables to be relocated.
1478/// basePtrs - base pointers.
1479/// statepointToken - statepoint instruction to which relocates should be
1480/// bound.
1481/// Builder - Llvm IR builder to be used to construct new calls.
1483 ArrayRef<Value *> BasePtrs,
1484 Instruction *StatepointToken,
1485 IRBuilder<> &Builder, GCStrategy *GC) {
1486 if (LiveVariables.empty())
1487 return;
1488
1489 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1490 auto ValIt = llvm::find(LiveVec, Val);
1491 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1492 size_t Index = std::distance(LiveVec.begin(), ValIt);
1493 assert(Index < LiveVec.size() && "Bug in std::find?");
1494 return Index;
1495 };
1496 Module *M = StatepointToken->getModule();
1497
1498 for (unsigned i = 0; i < LiveVariables.size(); i++) {
1499 // Generate the gc.relocate call and save the result
1500 Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
1501 Value *LiveIdx = Builder.getInt32(i);
1502
1503 Type *Ty = LiveVariables[i]->getType();
1506 M, Intrinsic::experimental_gc_relocate, {Ty});
1507
1508 // only specify a debug name if we can give a useful one
1509 CallInst *Reloc = Builder.CreateCall(
1510 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1511 suffixed_name_or(LiveVariables[i], ".relocated", ""));
1512 // Trick CodeGen into thinking there are lots of free registers at this
1513 // fake call.
1514 Reloc->setCallingConv(CallingConv::Cold);
1515 }
1516}
1517
1518namespace {
1519
1520/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1521/// avoids having to worry about keeping around dangling pointers to Values.
1522class DeferredReplacement {
1523 AssertingVH<Instruction> Old;
1524 AssertingVH<Instruction> New;
1525 bool IsDeoptimize = false;
1526
1527 DeferredReplacement() = default;
1528
1529public:
1530 static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1531 assert(Old != New && Old && New &&
1532 "Cannot RAUW equal values or to / from null!");
1533
1534 DeferredReplacement D;
1535 D.Old = Old;
1536 D.New = New;
1537 return D;
1538 }
1539
1540 static DeferredReplacement createDelete(Instruction *ToErase) {
1541 DeferredReplacement D;
1542 D.Old = ToErase;
1543 return D;
1544 }
1545
1546 static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1547#ifndef NDEBUG
1548 auto *F = cast<CallInst>(Old)->getCalledFunction();
1549 assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1550 "Only way to construct a deoptimize deferred replacement");
1551#endif
1552 DeferredReplacement D;
1553 D.Old = Old;
1554 D.IsDeoptimize = true;
1555 return D;
1556 }
1557
1558 /// Does the task represented by this instance.
1559 void doReplacement() {
1560 Instruction *OldI = Old;
1561 Instruction *NewI = New;
1562
1563 assert(OldI != NewI && "Disallowed at construction?!");
1564 assert((!IsDeoptimize || !New) &&
1565 "Deoptimize intrinsics are not replaced!");
1566
1567 Old = nullptr;
1568 New = nullptr;
1569
1570 if (NewI)
1571 OldI->replaceAllUsesWith(NewI);
1572
1573 if (IsDeoptimize) {
1574 // Note: we've inserted instructions, so the call to llvm.deoptimize may
1575 // not necessarily be followed by the matching return.
1576 auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1577 new UnreachableInst(RI->getContext(), RI->getIterator());
1578 RI->eraseFromParent();
1579 }
1580
1581 OldI->eraseFromParent();
1582 }
1583};
1584
1585} // end anonymous namespace
1586
1588 const char *DeoptLowering = "deopt-lowering";
1589 if (Call->hasFnAttr(DeoptLowering)) {
1590 // FIXME: Calls have a *really* confusing interface around attributes
1591 // with values.
1592 const AttributeList &CSAS = Call->getAttributes();
1593 if (CSAS.hasFnAttr(DeoptLowering))
1594 return CSAS.getFnAttr(DeoptLowering).getValueAsString();
1595 Function *F = Call->getCalledFunction();
1596 assert(F && F->hasFnAttribute(DeoptLowering));
1597 return F->getFnAttribute(DeoptLowering).getValueAsString();
1598 }
1599 return "live-through";
1600}
1601
1602static void
1604 const SmallVectorImpl<Value *> &BasePtrs,
1606 PartiallyConstructedSafepointRecord &Result,
1607 std::vector<DeferredReplacement> &Replacements,
1608 const PointerToBaseTy &PointerToBase,
1609 GCStrategy *GC) {
1610 assert(BasePtrs.size() == LiveVariables.size());
1611
1612 // Then go ahead and use the builder do actually do the inserts. We insert
1613 // immediately before the previous instruction under the assumption that all
1614 // arguments will be available here. We can't insert afterwards since we may
1615 // be replacing a terminator.
1616 IRBuilder<> Builder(Call);
1617
1620 uint32_t NumPatchBytes = 0;
1622
1623 SmallVector<Value *, 8> CallArgs(Call->args());
1624 std::optional<ArrayRef<Use>> DeoptArgs;
1625 if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
1626 DeoptArgs = Bundle->Inputs;
1627 std::optional<ArrayRef<Use>> TransitionArgs;
1628 if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1629 TransitionArgs = Bundle->Inputs;
1630 // TODO: This flag no longer serves a purpose and can be removed later
1632 }
1633
1634 // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1635 // with a return value, we lower then as never returning calls to
1636 // __llvm_deoptimize that are followed by unreachable to get better codegen.
1637 bool IsDeoptimize = false;
1638 bool IsMemIntrinsic = false;
1639
1641 parseStatepointDirectivesFromAttrs(Call->getAttributes());
1642 if (SD.NumPatchBytes)
1643 NumPatchBytes = *SD.NumPatchBytes;
1644 if (SD.StatepointID)
1645 StatepointID = *SD.StatepointID;
1646
1647 // Pass through the requested lowering if any. The default is live-through.
1648 StringRef DeoptLowering = getDeoptLowering(Call);
1649 if (DeoptLowering == "live-in")
1651 else {
1652 assert(DeoptLowering == "live-through" && "Unsupported value!");
1653 }
1654
1655 FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
1656 if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
1657 auto IID = F->getIntrinsicID();
1658 if (IID == Intrinsic::experimental_deoptimize) {
1659 // Calls to llvm.experimental.deoptimize are lowered to calls to the
1660 // __llvm_deoptimize symbol. We want to resolve this now, since the
1661 // verifier does not allow taking the address of an intrinsic function.
1662
1663 SmallVector<Type *, 8> DomainTy;
1664 for (Value *Arg : CallArgs)
1665 DomainTy.push_back(Arg->getType());
1666 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1667 /* isVarArg = */ false);
1668
1669 // Note: CallTarget can be a bitcast instruction of a symbol if there are
1670 // calls to @llvm.experimental.deoptimize with different argument types in
1671 // the same module. This is fine -- we assume the frontend knew what it
1672 // was doing when generating this kind of IR.
1673 CallTarget = F->getParent()
1674 ->getOrInsertFunction("__llvm_deoptimize", FTy);
1675
1676 IsDeoptimize = true;
1677 } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
1678 IID == Intrinsic::memmove_element_unordered_atomic) {
1679 IsMemIntrinsic = true;
1680
1681 // Unordered atomic memcpy and memmove intrinsics which are not explicitly
1682 // marked as "gc-leaf-function" should be lowered in a GC parseable way.
1683 // Specifically, these calls should be lowered to the
1684 // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
1685 // Similarly to __llvm_deoptimize we want to resolve this now, since the
1686 // verifier does not allow taking the address of an intrinsic function.
1687 //
1688 // Moreover we need to shuffle the arguments for the call in order to
1689 // accommodate GC. The underlying source and destination objects might be
1690 // relocated during copy operation should the GC occur. To relocate the
1691 // derived source and destination pointers the implementation of the
1692 // intrinsic should know the corresponding base pointers.
1693 //
1694 // To make the base pointers available pass them explicitly as arguments:
1695 // memcpy(dest_derived, source_derived, ...) =>
1696 // memcpy(dest_base, dest_offset, source_base, source_offset, ...)
1697 auto &Context = Call->getContext();
1698 auto &DL = Call->getDataLayout();
1699 auto GetBaseAndOffset = [&](Value *Derived) {
1700 Value *Base = nullptr;
1701 // Optimizations in unreachable code might substitute the real pointer
1702 // with undef, poison or null-derived constant. Return null base for
1703 // them to be consistent with the handling in the main algorithm in
1704 // findBaseDefiningValue.
1705 if (isa<Constant>(Derived))
1706 Base =
1707 ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
1708 else {
1709 assert(PointerToBase.count(Derived));
1710 Base = PointerToBase.find(Derived)->second;
1711 }
1712 unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
1713 unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
1714 Value *Base_int = Builder.CreatePtrToInt(
1715 Base, Type::getIntNTy(Context, IntPtrSize));
1716 Value *Derived_int = Builder.CreatePtrToInt(
1717 Derived, Type::getIntNTy(Context, IntPtrSize));
1718 return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
1719 };
1720
1721 auto *Dest = CallArgs[0];
1722 Value *DestBase, *DestOffset;
1723 std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
1724
1725 auto *Source = CallArgs[1];
1726 Value *SourceBase, *SourceOffset;
1727 std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
1728
1729 auto *LengthInBytes = CallArgs[2];
1730 auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
1731
1732 CallArgs.clear();
1733 CallArgs.push_back(DestBase);
1734 CallArgs.push_back(DestOffset);
1735 CallArgs.push_back(SourceBase);
1736 CallArgs.push_back(SourceOffset);
1737 CallArgs.push_back(LengthInBytes);
1738
1739 SmallVector<Type *, 8> DomainTy;
1740 for (Value *Arg : CallArgs)
1741 DomainTy.push_back(Arg->getType());
1742 auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1743 /* isVarArg = */ false);
1744
1745 auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
1746 uint64_t ElementSize = ElementSizeCI->getZExtValue();
1747 if (IID == Intrinsic::memcpy_element_unordered_atomic) {
1748 switch (ElementSize) {
1749 case 1:
1750 return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
1751 case 2:
1752 return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
1753 case 4:
1754 return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
1755 case 8:
1756 return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
1757 case 16:
1758 return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
1759 default:
1760 llvm_unreachable("unexpected element size!");
1761 }
1762 }
1763 assert(IID == Intrinsic::memmove_element_unordered_atomic);
1764 switch (ElementSize) {
1765 case 1:
1766 return "__llvm_memmove_element_unordered_atomic_safepoint_1";
1767 case 2:
1768 return "__llvm_memmove_element_unordered_atomic_safepoint_2";
1769 case 4:
1770 return "__llvm_memmove_element_unordered_atomic_safepoint_4";
1771 case 8:
1772 return "__llvm_memmove_element_unordered_atomic_safepoint_8";
1773 case 16:
1774 return "__llvm_memmove_element_unordered_atomic_safepoint_16";
1775 default:
1776 llvm_unreachable("unexpected element size!");
1777 }
1778 };
1779
1780 CallTarget =
1781 F->getParent()
1782 ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
1783 }
1784 }
1785
1786 // Create the statepoint given all the arguments
1787 GCStatepointInst *Token = nullptr;
1788 if (auto *CI = dyn_cast<CallInst>(Call)) {
1789 CallInst *SPCall = Builder.CreateGCStatepointCall(
1790 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1791 TransitionArgs, DeoptArgs, GCLive, "safepoint_token");
1792
1793 SPCall->setTailCallKind(CI->getTailCallKind());
1794 SPCall->setCallingConv(CI->getCallingConv());
1795
1796 // Set up function attrs directly on statepoint and return attrs later for
1797 // gc_result intrinsic.
1798 SPCall->setAttributes(
1799 legalizeCallAttributes(CI, IsMemIntrinsic, SPCall->getAttributes()));
1800
1801 Token = cast<GCStatepointInst>(SPCall);
1802
1803 // Put the following gc_result and gc_relocate calls immediately after the
1804 // the old call (which we're about to delete)
1805 assert(CI->getNextNode() && "Not a terminator, must have next!");
1806 Builder.SetInsertPoint(CI->getNextNode());
1807 Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
1808 } else {
1809 auto *II = cast<InvokeInst>(Call);
1810
1811 // Insert the new invoke into the old block. We'll remove the old one in a
1812 // moment at which point this will become the new terminator for the
1813 // original block.
1814 InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1815 StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1816 II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1817 GCLive, "statepoint_token");
1818
1819 SPInvoke->setCallingConv(II->getCallingConv());
1820
1821 // Set up function attrs directly on statepoint and return attrs later for
1822 // gc_result intrinsic.
1823 SPInvoke->setAttributes(
1824 legalizeCallAttributes(II, IsMemIntrinsic, SPInvoke->getAttributes()));
1825
1826 Token = cast<GCStatepointInst>(SPInvoke);
1827
1828 // Generate gc relocates in exceptional path
1829 BasicBlock *UnwindBlock = II->getUnwindDest();
1830 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1831 UnwindBlock->getUniquePredecessor() &&
1832 "can't safely insert in this block!");
1833
1834 Builder.SetInsertPoint(UnwindBlock->getFirstInsertionPt());
1835 Builder.SetCurrentDebugLocation(II->getDebugLoc());
1836
1837 // Attach exceptional gc relocates to the landingpad.
1838 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1839 Result.UnwindToken = ExceptionalToken;
1840
1841 CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder, GC);
1842
1843 // Generate gc relocates and returns for normal block
1844 BasicBlock *NormalDest = II->getNormalDest();
1845 assert(!isa<PHINode>(NormalDest->begin()) &&
1846 NormalDest->getUniquePredecessor() &&
1847 "can't safely insert in this block!");
1848
1849 Builder.SetInsertPoint(NormalDest->getFirstInsertionPt());
1850
1851 // gc relocates will be generated later as if it were regular call
1852 // statepoint
1853 }
1854 assert(Token && "Should be set in one of the above branches!");
1855
1856 if (IsDeoptimize) {
1857 // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1858 // transform the tail-call like structure to a call to a void function
1859 // followed by unreachable to get better codegen.
1860 Replacements.push_back(
1861 DeferredReplacement::createDeoptimizeReplacement(Call));
1862 } else {
1863 Token->setName("statepoint_token");
1864 if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
1865 StringRef Name = Call->hasName() ? Call->getName() : "";
1866 CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1867 GCResult->setAttributes(
1868 AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1869 Call->getAttributes().getRetAttrs()));
1870
1871 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1872 // live set of some other safepoint, in which case that safepoint's
1873 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1874 // llvm::Instruction. Instead, we defer the replacement and deletion to
1875 // after the live sets have been made explicit in the IR, and we no longer
1876 // have raw pointers to worry about.
1877 Replacements.emplace_back(
1878 DeferredReplacement::createRAUW(Call, GCResult));
1879 } else {
1880 Replacements.emplace_back(DeferredReplacement::createDelete(Call));
1881 }
1882 }
1883
1884 Result.StatepointToken = Token;
1885
1886 // Second, create a gc.relocate for every live variable
1887 CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder, GC);
1888}
1889
1890// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1891// which make the relocations happening at this safepoint explicit.
1892//
1893// WARNING: Does not do any fixup to adjust users of the original live
1894// values. That's the callers responsibility.
1895static void
1897 PartiallyConstructedSafepointRecord &Result,
1898 std::vector<DeferredReplacement> &Replacements,
1899 const PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1900 const auto &LiveSet = Result.LiveSet;
1901
1902 // Convert to vector for efficient cross referencing.
1903 SmallVector<Value *, 64> BaseVec, LiveVec;
1904 LiveVec.reserve(LiveSet.size());
1905 BaseVec.reserve(LiveSet.size());
1906 for (Value *L : LiveSet) {
1907 LiveVec.push_back(L);
1908 assert(PointerToBase.count(L));
1909 Value *Base = PointerToBase.find(L)->second;
1910 BaseVec.push_back(Base);
1911 }
1912 assert(LiveVec.size() == BaseVec.size());
1913
1914 // Do the actual rewriting and delete the old statepoint
1915 makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
1916 PointerToBase, GC);
1917}
1918
1919// Helper function for the relocationViaAlloca.
1920//
1921// It receives iterator to the statepoint gc relocates and emits a store to the
1922// assigned location (via allocaMap) for the each one of them. It adds the
1923// visited values into the visitedLiveValues set, which we will later use them
1924// for validation checking.
1925static void
1928 DenseSet<Value *> &VisitedLiveValues) {
1929 for (User *U : GCRelocs) {
1931 if (!Relocate)
1932 continue;
1933
1934 Value *OriginalValue = Relocate->getDerivedPtr();
1935 assert(AllocaMap.count(OriginalValue));
1936 Value *Alloca = AllocaMap[OriginalValue];
1937
1938 // Emit store into the related alloca.
1939 assert(Relocate->getNextNode() &&
1940 "Should always have one since it's not a terminator");
1941 new StoreInst(Relocate, Alloca, std::next(Relocate->getIterator()));
1942
1943#ifndef NDEBUG
1944 VisitedLiveValues.insert(OriginalValue);
1945#endif
1946 }
1947}
1948
1949// Helper function for the "relocationViaAlloca". Similar to the
1950// "insertRelocationStores" but works for rematerialized values.
1952 const RematerializedValueMapTy &RematerializedValues,
1954 DenseSet<Value *> &VisitedLiveValues) {
1955 for (auto RematerializedValuePair: RematerializedValues) {
1956 Instruction *RematerializedValue = RematerializedValuePair.first;
1957 Value *OriginalValue = RematerializedValuePair.second;
1958
1959 assert(AllocaMap.count(OriginalValue) &&
1960 "Can not find alloca for rematerialized value");
1961 Value *Alloca = AllocaMap[OriginalValue];
1962
1963 new StoreInst(RematerializedValue, Alloca,
1964 std::next(RematerializedValue->getIterator()));
1965
1966#ifndef NDEBUG
1967 VisitedLiveValues.insert(OriginalValue);
1968#endif
1969 }
1970}
1971
1972/// Do all the relocation update via allocas and mem2reg
1976#ifndef NDEBUG
1977 // record initial number of (static) allocas; we'll check we have the same
1978 // number when we get done.
1979 int InitialAllocaNum = 0;
1980 for (Instruction &I : F.getEntryBlock())
1981 if (isa<AllocaInst>(I))
1982 InitialAllocaNum++;
1983#endif
1984
1985 // TODO-PERF: change data structures, reserve
1987 SmallVector<AllocaInst *, 200> PromotableAllocas;
1988 // Used later to chack that we have enough allocas to store all values
1989 std::size_t NumRematerializedValues = 0;
1990 PromotableAllocas.reserve(Live.size());
1991
1992 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1993 // "PromotableAllocas"
1994 const DataLayout &DL = F.getDataLayout();
1995 auto emitAllocaFor = [&](Value *LiveValue) {
1996 AllocaInst *Alloca =
1997 new AllocaInst(LiveValue->getType(), DL.getAllocaAddrSpace(), "",
1998 F.getEntryBlock().getFirstNonPHIIt());
1999 AllocaMap[LiveValue] = Alloca;
2000 PromotableAllocas.push_back(Alloca);
2001 };
2002
2003 // Emit alloca for each live gc pointer
2004 for (Value *V : Live)
2005 emitAllocaFor(V);
2006
2007 // Emit allocas for rematerialized values
2008 for (const auto &Info : Records)
2009 for (auto RematerializedValuePair : Info.RematerializedValues) {
2010 Value *OriginalValue = RematerializedValuePair.second;
2011 if (AllocaMap.contains(OriginalValue))
2012 continue;
2013
2014 emitAllocaFor(OriginalValue);
2015 ++NumRematerializedValues;
2016 }
2017
2018 // The next two loops are part of the same conceptual operation. We need to
2019 // insert a store to the alloca after the original def and at each
2020 // redefinition. We need to insert a load before each use. These are split
2021 // into distinct loops for performance reasons.
2022
2023 // Update gc pointer after each statepoint: either store a relocated value or
2024 // null (if no relocated value was found for this gc pointer and it is not a
2025 // gc_result). This must happen before we update the statepoint with load of
2026 // alloca otherwise we lose the link between statepoint and old def.
2027 for (const auto &Info : Records) {
2028 GCStatepointInst *Statepoint = Info.StatepointToken;
2029
2030 // This will be used for consistency check
2031 DenseSet<Value *> VisitedLiveValues;
2032
2033 // Insert stores for normal statepoint gc relocates
2034 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
2035
2036 // In case if it was invoke statepoint
2037 // we will insert stores for exceptional path gc relocates.
2038 if (isa<InvokeInst>(Statepoint)) {
2039 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
2040 VisitedLiveValues);
2041 }
2042
2043 // Do similar thing with rematerialized values
2044 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
2045 VisitedLiveValues);
2046
2047 if (ClobberNonLive) {
2048 // As a debugging aid, pretend that an unrelocated pointer becomes null at
2049 // the gc.statepoint. This will turn some subtle GC problems into
2050 // slightly easier to debug SEGVs. Note that on large IR files with
2051 // lots of gc.statepoints this is extremely costly both memory and time
2052 // wise.
2054 for (auto Pair : AllocaMap) {
2055 Value *Def = Pair.first;
2056 AllocaInst *Alloca = Pair.second;
2057
2058 // This value was relocated
2059 if (VisitedLiveValues.count(Def)) {
2060 continue;
2061 }
2062 // Track Def's type since the alloca was created with that type.
2063 ToClobber.push_back({Def->getType(), Alloca});
2064 }
2065
2066 auto InsertClobbersAt = [&](BasicBlock::iterator IP) {
2067 for (auto &[Ty, AI] : ToClobber) {
2068 Constant *CPN;
2069 if (Ty->isVectorTy())
2071 else
2073 new StoreInst(CPN, AI, IP);
2074 }
2075 };
2076
2077 // Insert the clobbering stores. These may get intermixed with the
2078 // gc.results and gc.relocates, but that's fine.
2079 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
2080 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
2081 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
2082 } else {
2083 InsertClobbersAt(
2084 std::next(cast<Instruction>(Statepoint)->getIterator()));
2085 }
2086 }
2087 }
2088
2089 // Update use with load allocas and add store for gc_relocated.
2090 for (auto Pair : AllocaMap) {
2091 Value *Def = Pair.first;
2092 AllocaInst *Alloca = Pair.second;
2093
2094 // We pre-record the uses of allocas so that we dont have to worry about
2095 // later update that changes the user information..
2096
2098 // PERF: trade a linear scan for repeated reallocation
2099 Uses.reserve(Def->getNumUses());
2100 for (User *U : Def->users()) {
2101 if (!isa<ConstantExpr>(U)) {
2102 // If the def has a ConstantExpr use, then the def is either a
2103 // ConstantExpr use itself or null. In either case
2104 // (recursively in the first, directly in the second), the oop
2105 // it is ultimately dependent on is null and this particular
2106 // use does not need to be fixed up.
2107 Uses.push_back(cast<Instruction>(U));
2108 }
2109 }
2110
2112 auto Last = llvm::unique(Uses);
2113 Uses.erase(Last, Uses.end());
2114
2115 for (Instruction *Use : Uses) {
2116 if (isa<PHINode>(Use)) {
2117 PHINode *Phi = cast<PHINode>(Use);
2118 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
2119 if (Def == Phi->getIncomingValue(i)) {
2120 // Use Def's type since the alloca was created with that type.
2121 LoadInst *Load = new LoadInst(
2122 Def->getType(), Alloca, "",
2123 Phi->getIncomingBlock(i)->getTerminator()->getIterator());
2124 Phi->setIncomingValue(i, Load);
2125 }
2126 }
2127 } else {
2128 // Use Def's type since the alloca was created with that type.
2129 LoadInst *Load =
2130 new LoadInst(Def->getType(), Alloca, "", Use->getIterator());
2131 Use->replaceUsesOfWith(Def, Load);
2132 }
2133 }
2134
2135 // Emit store for the initial gc value. Store must be inserted after load,
2136 // otherwise store will be in alloca's use list and an extra load will be
2137 // inserted before it.
2138 StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
2139 DL.getABITypeAlign(Def->getType()));
2140 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
2141 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
2142 // InvokeInst is a terminator so the store need to be inserted into its
2143 // normal destination block.
2144 BasicBlock *NormalDest = Invoke->getNormalDest();
2145 Store->insertBefore(NormalDest->getFirstNonPHIIt());
2146 } else {
2147 assert(!Inst->isTerminator() &&
2148 "The only terminator that can produce a value is "
2149 "InvokeInst which is handled above.");
2150 Store->insertAfter(Inst->getIterator());
2151 }
2152 } else {
2153 assert(isa<Argument>(Def));
2154 Store->insertAfter(cast<Instruction>(Alloca)->getIterator());
2155 }
2156 }
2157
2158 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
2159 "we must have the same allocas with lives");
2160 (void) NumRematerializedValues;
2161 if (!PromotableAllocas.empty()) {
2162 // Apply mem2reg to promote alloca to SSA
2163 PromoteMemToReg(PromotableAllocas, DT);
2164 }
2165
2166#ifndef NDEBUG
2167 for (auto &I : F.getEntryBlock())
2168 if (isa<AllocaInst>(I))
2169 InitialAllocaNum--;
2170 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
2171#endif
2172}
2173
2174/// Insert holders so that each Value is obviously live through the entire
2175/// lifetime of the call.
2177 SmallVectorImpl<CallInst *> &Holders) {
2178 if (Values.empty())
2179 // No values to hold live, might as well not insert the empty holder
2180 return;
2181
2182 Module *M = Call->getModule();
2183 // Use a dummy vararg function to actually hold the values live
2184 FunctionCallee Func = M->getOrInsertFunction(
2185 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
2186 if (isa<CallInst>(Call)) {
2187 // For call safepoints insert dummy calls right after safepoint
2188 Holders.push_back(
2189 CallInst::Create(Func, Values, "", std::next(Call->getIterator())));
2190 return;
2191 }
2192 // For invoke safepooints insert dummy calls both in normal and
2193 // exceptional destination blocks
2194 auto *II = cast<InvokeInst>(Call);
2196 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
2198 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
2199}
2200
2202 const ScalarOptions &Opts, Function &F, DominatorTree &DT,
2203 ArrayRef<CallBase *> toUpdate,
2205 GCStrategy *GC) {
2206 GCPtrLivenessData OriginalLivenessData;
2207 computeLiveInValues(DT, F, OriginalLivenessData, GC);
2208 for (size_t i = 0; i < records.size(); i++) {
2209 struct PartiallyConstructedSafepointRecord &info = records[i];
2210 analyzeParsePointLiveness(Opts, DT, OriginalLivenessData, toUpdate[i], info,
2211 GC);
2212 }
2213}
2214
2215// Helper function for the "rematerializeLiveValues". It walks use chain
2216// starting from the "CurrentValue" until it reaches the root of the chain, i.e.
2217// the base or a value it cannot process. Only "simple" values are processed
2218// (currently it is GEP's and casts). The returned root is examined by the
2219// callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
2220// with all visited values.
2222 SmallVectorImpl<Instruction*> &ChainToBase,
2223 Value *CurrentValue) {
2224 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2225 ChainToBase.push_back(GEP);
2226 return findRematerializableChainToBasePointer(ChainToBase,
2227 GEP->getPointerOperand());
2228 }
2229
2230 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2231 if (!CI->isNoopCast(CI->getDataLayout()))
2232 return CI;
2233
2234 ChainToBase.push_back(CI);
2235 return findRematerializableChainToBasePointer(ChainToBase,
2236 CI->getOperand(0));
2237 }
2238
2239 // We have reached the root of the chain, which is either equal to the base or
2240 // is the first unsupported value along the use chain.
2241 return CurrentValue;
2242}
2243
2244// Helper function for the "rematerializeLiveValues". Compute cost of the use
2245// chain we are going to rematerialize.
2246static InstructionCost
2249 InstructionCost Cost = 0;
2250
2251 for (Instruction *Instr : Chain) {
2252 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2253 assert(CI->isNoopCast(CI->getDataLayout()) &&
2254 "non noop cast is found during rematerialization");
2255
2256 Type *SrcTy = CI->getOperand(0)->getType();
2257 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
2260
2261 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2262 // Cost of the address calculation
2263 Cost += TTI.getAddressComputationCost(
2264 GEP->getType(), nullptr, nullptr,
2266
2267 // And cost of the GEP itself
2268 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2269 // allowed for the external usage)
2270 if (!GEP->hasAllConstantIndices())
2271 Cost += 2;
2272
2273 } else {
2274 llvm_unreachable("unsupported instruction type during rematerialization");
2275 }
2276 }
2277
2278 return Cost;
2279}
2280
2281static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
2282 unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
2283 if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
2284 OrigRootPhi.getParent() != AlternateRootPhi.getParent())
2285 return false;
2286 // Map of incoming values and their corresponding basic blocks of
2287 // OrigRootPhi.
2288 SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
2289 for (unsigned i = 0; i < PhiNum; i++)
2290 CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
2291 OrigRootPhi.getIncomingBlock(i);
2292
2293 // Both current and base PHIs should have same incoming values and
2294 // the same basic blocks corresponding to the incoming values.
2295 for (unsigned i = 0; i < PhiNum; i++) {
2296 auto CIVI =
2297 CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2298 if (CIVI == CurrentIncomingValues.end())
2299 return false;
2300 BasicBlock *CurrentIncomingBB = CIVI->second;
2301 if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2302 return false;
2303 }
2304 return true;
2305}
2306
2307// Find derived pointers that can be recomputed cheap enough and fill
2308// RematerizationCandidates with such candidates.
2309static void
2310findRematerializationCandidates(PointerToBaseTy PointerToBase,
2311 RematCandTy &RematerizationCandidates,
2313 const unsigned int ChainLengthThreshold = 10;
2314
2315 for (auto P2B : PointerToBase) {
2316 auto *Derived = P2B.first;
2317 auto *Base = P2B.second;
2318 // Consider only derived pointers.
2319 if (Derived == Base)
2320 continue;
2321
2322 // For each live pointer find its defining chain.
2324 Value *RootOfChain =
2325 findRematerializableChainToBasePointer(ChainToBase, Derived);
2326
2327 // Nothing to do, or chain is too long
2328 if ( ChainToBase.size() == 0 ||
2329 ChainToBase.size() > ChainLengthThreshold)
2330 continue;
2331
2332 // Handle the scenario where the RootOfChain is not equal to the
2333 // Base Value, but they are essentially the same phi values.
2334 if (Value *BaseVal = PointerToBase[Derived]; RootOfChain != BaseVal) {
2335 PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2336 PHINode *AlternateRootPhi = dyn_cast<PHINode>(BaseVal);
2337 if (!OrigRootPhi || !AlternateRootPhi)
2338 continue;
2339 // PHI nodes that have the same incoming values, and belonging to the same
2340 // basic blocks are essentially the same SSA value. When the original phi
2341 // has incoming values with different base pointers, the original phi is
2342 // marked as conflict, and an additional `AlternateRootPhi` with the same
2343 // incoming values get generated by the findBasePointer function. We need
2344 // to identify the newly generated AlternateRootPhi (.base version of phi)
2345 // and RootOfChain (the original phi node itself) are the same, so that we
2346 // can rematerialize the gep and casts. This is a workaround for the
2347 // deficiency in the findBasePointer algorithm.
2348 if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2349 continue;
2350 }
2351 // Compute cost of this chain.
2352 InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
2353 // TODO: We can also account for cases when we will be able to remove some
2354 // of the rematerialized values by later optimization passes. I.e if
2355 // we rematerialized several intersecting chains. Or if original values
2356 // don't have any uses besides this statepoint.
2357
2358 // Ok, there is a candidate.
2359 RematerizlizationCandidateRecord Record;
2360 Record.ChainToBase = ChainToBase;
2361 Record.RootOfChain = RootOfChain;
2362 Record.Cost = Cost;
2363 RematerizationCandidates.insert({ Derived, Record });
2364 }
2365}
2366
2367// Try to rematerialize derived pointers immediately before their uses
2368// (instead of rematerializing after every statepoint it is live through).
2369// This can be beneficial when derived pointer is live across many
2370// statepoints, but uses are rare.
2372 const ScalarOptions &Opts, RematCandTy &RematerizationCandidates,
2374 PointerToBaseTy &PointerToBase) {
2375 if (!Opts.rs4gc_remat_derived_at_uses)
2376 return;
2377
2378 SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
2379
2380 LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
2381 << "Num statepoints: " << Records.size() << '\n');
2382
2383 for (auto &It : RematerizationCandidates) {
2384 Instruction *Cand = cast<Instruction>(It.first);
2385 auto &Record = It.second;
2386
2387 if (Record.Cost >= Opts.spp_rematerialization_threshold)
2388 continue;
2389
2390 if (Cand->user_empty())
2391 continue;
2392
2393 if (Cand->hasOneUse())
2394 if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
2395 if (U->getParent() == Cand->getParent())
2396 continue;
2397
2398 // Rematerialization before PHI nodes is not implemented.
2399 if (llvm::any_of(Cand->users(),
2400 [](const auto *U) { return isa<PHINode>(U); }))
2401 continue;
2402
2403 LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
2404
2405 // Count of rematerialization instructions we introduce is equal to number
2406 // of candidate uses.
2407 // Count of rematerialization instructions we eliminate is equal to number
2408 // of statepoints it is live through.
2409 // Consider transformation profitable if latter is greater than former
2410 // (in other words, we create less than eliminate).
2411 unsigned NumLiveStatepoints = llvm::count_if(
2412 Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
2413 unsigned NumUses = Cand->getNumUses();
2414
2415 LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
2416 << NumLiveStatepoints << " ");
2417
2418 if (NumLiveStatepoints < NumUses) {
2419 LLVM_DEBUG(dbgs() << "not profitable\n");
2420 continue;
2421 }
2422
2423 // If rematerialization is 'free', then favor rematerialization at
2424 // uses as it generally shortens live ranges.
2425 // TODO: Short (size ==1) chains only?
2426 if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
2427 LLVM_DEBUG(dbgs() << "not profitable\n");
2428 continue;
2429 }
2430
2431 LLVM_DEBUG(dbgs() << "looks profitable\n");
2432
2433 // ChainToBase may contain another remat candidate (as a sub chain) which
2434 // has been rewritten by now. Need to recollect chain to have up to date
2435 // value.
2436 // TODO: sort records in findRematerializationCandidates() in
2437 // decreasing chain size order?
2438 if (Record.ChainToBase.size() > 1) {
2439 Record.ChainToBase.clear();
2441 }
2442
2443 // Current rematerialization algorithm is very simple: we rematerialize
2444 // immediately before EVERY use, even if there are several uses in same
2445 // block or if use is local to Cand Def. The reason is that this allows
2446 // us to avoid recomputing liveness without complicated analysis:
2447 // - If we did not eliminate all uses of original Candidate, we do not
2448 // know exaclty in what BBs it is still live.
2449 // - If we rematerialize once per BB, we need to find proper insertion
2450 // place (first use in block, but after Def) and analyze if there is
2451 // statepoint between uses in the block.
2452 while (!Cand->user_empty()) {
2453 Instruction *UserI = cast<Instruction>(*Cand->user_begin());
2454 Instruction *RematChain =
2455 rematerializeChain(Record.ChainToBase, UserI->getIterator(),
2456 Record.RootOfChain, PointerToBase[Cand]);
2457 UserI->replaceUsesOfWith(Cand, RematChain);
2458 PointerToBase[RematChain] = PointerToBase[Cand];
2459 }
2460 LiveValuesToBeDeleted.push_back(Cand);
2461 }
2462
2463 LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
2464 << " derived pointers\n");
2465 for (auto *Cand : LiveValuesToBeDeleted) {
2466 assert(Cand->use_empty() && "Unexpected user remain");
2467 RematerizationCandidates.erase(Cand);
2468 for (auto &R : Records) {
2469 assert(!R.LiveSet.contains(Cand) ||
2470 R.LiveSet.contains(PointerToBase[Cand]));
2471 R.LiveSet.remove(Cand);
2472 }
2473 }
2474
2475 // Recollect not rematerialized chains - we might have rewritten
2476 // their sub-chains.
2477 if (!LiveValuesToBeDeleted.empty()) {
2478 for (auto &P : RematerizationCandidates) {
2479 auto &R = P.second;
2480 if (R.ChainToBase.size() > 1) {
2481 R.ChainToBase.clear();
2482 findRematerializableChainToBasePointer(R.ChainToBase, P.first);
2483 }
2484 }
2485 }
2486}
2487
2488// From the statepoint live set pick values that are cheaper to recompute then
2489// to relocate. Remove this values from the live set, rematerialize them after
2490// statepoint and record them in "Info" structure. Note that similar to
2491// relocated values we don't do any user adjustments here.
2492static void rematerializeLiveValues(const ScalarOptions &Opts, CallBase *Call,
2493 PartiallyConstructedSafepointRecord &Info,
2494 PointerToBaseTy &PointerToBase,
2495 RematCandTy &RematerizationCandidates,
2497 // Record values we are going to delete from this statepoint live set.
2498 // We can not di this in following loop due to iterator invalidation.
2499 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2500
2501 for (Value *LiveValue : Info.LiveSet) {
2502 auto It = RematerizationCandidates.find(LiveValue);
2503 if (It == RematerizationCandidates.end())
2504 continue;
2505
2506 RematerizlizationCandidateRecord &Record = It->second;
2507
2508 InstructionCost Cost = Record.Cost;
2509 // For invokes we need to rematerialize each chain twice - for normal and
2510 // for unwind basic blocks. Model this by multiplying cost by two.
2511 if (isa<InvokeInst>(Call))
2512 Cost *= 2;
2513
2514 // If it's too expensive - skip it.
2515 if (Cost >= Opts.spp_rematerialization_threshold)
2516 continue;
2517
2518 // Remove value from the live set
2519 LiveValuesToBeDeleted.push_back(LiveValue);
2520
2521 // Clone instructions and record them inside "Info" structure.
2522
2523 // Different cases for calls and invokes. For invokes we need to clone
2524 // instructions both on normal and unwind path.
2525 if (isa<CallInst>(Call)) {
2526 Instruction *InsertBefore = Call->getNextNode();
2527 assert(InsertBefore);
2528 Instruction *RematerializedValue =
2529 rematerializeChain(Record.ChainToBase, InsertBefore->getIterator(),
2530 Record.RootOfChain, PointerToBase[LiveValue]);
2531 Info.RematerializedValues[RematerializedValue] = LiveValue;
2532 } else {
2533 auto *Invoke = cast<InvokeInst>(Call);
2534
2535 BasicBlock::iterator NormalInsertBefore =
2536 Invoke->getNormalDest()->getFirstInsertionPt();
2537 BasicBlock::iterator UnwindInsertBefore =
2538 Invoke->getUnwindDest()->getFirstInsertionPt();
2539
2540 Instruction *NormalRematerializedValue =
2541 rematerializeChain(Record.ChainToBase, NormalInsertBefore,
2542 Record.RootOfChain, PointerToBase[LiveValue]);
2543 Instruction *UnwindRematerializedValue =
2544 rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
2545 Record.RootOfChain, PointerToBase[LiveValue]);
2546
2547 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2548 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2549 }
2550 }
2551
2552 // Remove rematerialized values from the live set.
2553 for (auto *LiveValue: LiveValuesToBeDeleted) {
2554 Info.LiveSet.remove(LiveValue);
2555 }
2556}
2557
2559 SmallVectorImpl<CallInst *> &Intrinsics,
2560 DefiningValueMapTy &DVCache,
2561 IsKnownBaseMapTy &KnownBases) {
2562 auto &Context = F.getContext();
2563 auto &DL = F.getDataLayout();
2564 bool Changed = false;
2565
2566 for (auto *Callsite : Intrinsics)
2567 switch (Callsite->getIntrinsicID()) {
2568 case Intrinsic::experimental_gc_get_pointer_base: {
2569 Changed = true;
2570 Value *Base =
2571 findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
2572 assert(!DVCache.count(Callsite));
2573 Callsite->replaceAllUsesWith(Base);
2574 if (!Base->hasName())
2575 Base->takeName(Callsite);
2576 Callsite->eraseFromParent();
2577 break;
2578 }
2579 case Intrinsic::experimental_gc_get_pointer_offset: {
2580 Changed = true;
2581 Value *Derived = Callsite->getOperand(0);
2582 Value *Base = findBasePointer(Derived, DVCache, KnownBases);
2583 assert(!DVCache.count(Callsite));
2584 unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
2585 unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
2586 IRBuilder<> Builder(Callsite);
2587 Value *BaseInt =
2588 Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
2589 suffixed_name_or(Base, ".int", ""));
2590 Value *DerivedInt =
2591 Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
2592 suffixed_name_or(Derived, ".int", ""));
2593 Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
2594 Callsite->replaceAllUsesWith(Offset);
2595 Offset->takeName(Callsite);
2596 Callsite->eraseFromParent();
2597 break;
2598 }
2599 default:
2600 llvm_unreachable("Unknown intrinsic");
2601 }
2602
2603 return Changed;
2604}
2605
2606static bool insertParsePoints(const ScalarOptions &Opts, Function &F,
2609 DefiningValueMapTy &DVCache,
2610 IsKnownBaseMapTy &KnownBases) {
2611 std::unique_ptr<GCStrategy> GC = findGCStrategy(F);
2612
2613#ifndef NDEBUG
2614 // Validate the input
2615 std::set<CallBase *> Uniqued;
2616 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2617 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2618
2619 for (CallBase *Call : ToUpdate)
2620 assert(Call->getFunction() == &F);
2621#endif
2622
2623 // When inserting gc.relocates for invokes, we need to be able to insert at
2624 // the top of the successor blocks. See the comment on
2625 // normalForInvokeSafepoint on exactly what is needed. Note that this step
2626 // may restructure the CFG.
2627 for (InvokeInst *II : make_isa_range<InvokeInst>(ToUpdate)) {
2628 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2629 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2630 }
2631
2632 // A list of dummy calls added to the IR to keep various values obviously
2633 // live in the IR. We'll remove all of these when done.
2635
2636 // Insert a dummy call with all of the deopt operands we'll need for the
2637 // actual safepoint insertion as arguments. This ensures reference operands
2638 // in the deopt argument list are considered live through the safepoint (and
2639 // thus makes sure they get relocated.)
2640 for (CallBase *Call : ToUpdate) {
2641 SmallVector<Value *, 64> DeoptValues;
2642
2643 for (Value *Arg : getDeoptBundleOperands(Opts, Call)) {
2644 assert(!isUnhandledGCPointerType(Arg->getType(), GC.get()) &&
2645 "support for FCA unimplemented");
2646 if (isHandledGCPointerType(Arg->getType(), GC.get()))
2647 DeoptValues.push_back(Arg);
2648 }
2649
2650 insertUseHolderAfter(Call, DeoptValues, Holders);
2651 }
2652
2654
2655 // A) Identify all gc pointers which are statically live at the given call
2656 // site.
2657 findLiveReferences(Opts, F, DT, ToUpdate, Records, GC.get());
2658
2659 /// Global mapping from live pointers to a base-defining-value.
2660 PointerToBaseTy PointerToBase;
2661
2662 // B) Find the base pointers for each live pointer
2663 for (size_t i = 0; i < Records.size(); i++) {
2664 PartiallyConstructedSafepointRecord &info = Records[i];
2665 findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
2666 }
2667 if (Opts.spp_print_base_pointers) {
2668 errs() << "Base Pairs (w/o Relocation):\n";
2669 for (auto &Pair : PointerToBase) {
2670 errs() << " derived ";
2671 Pair.first->printAsOperand(errs(), false);
2672 errs() << " base ";
2673 Pair.second->printAsOperand(errs(), false);
2674 errs() << "\n";
2675 ;
2676 }
2677 }
2678
2679 // The base phi insertion logic (for any safepoint) may have inserted new
2680 // instructions which are now live at some safepoint. The simplest such
2681 // example is:
2682 // loop:
2683 // phi a <-- will be a new base_phi here
2684 // safepoint 1 <-- that needs to be live here
2685 // gep a + 1
2686 // safepoint 2
2687 // br loop
2688 // We insert some dummy calls after each safepoint to definitely hold live
2689 // the base pointers which were identified for that safepoint. We'll then
2690 // ask liveness for _every_ base inserted to see what is now live. Then we
2691 // remove the dummy calls.
2692 Holders.reserve(Holders.size() + Records.size());
2693 for (size_t i = 0; i < Records.size(); i++) {
2694 PartiallyConstructedSafepointRecord &Info = Records[i];
2695
2697 for (auto *Derived : Info.LiveSet) {
2698 assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
2699 Bases.push_back(PointerToBase[Derived]);
2700 }
2701
2702 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2703 }
2704
2705 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2706 // need to rerun liveness. We may *also* have inserted new defs, but that's
2707 // not the key issue.
2708 recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase, GC.get());
2709
2710 if (Opts.spp_print_base_pointers) {
2711 errs() << "Base Pairs: (w/Relocation)\n";
2712 for (auto Pair : PointerToBase) {
2713 errs() << " derived ";
2714 Pair.first->printAsOperand(errs(), false);
2715 errs() << " base ";
2716 Pair.second->printAsOperand(errs(), false);
2717 errs() << "\n";
2718 }
2719 }
2720
2721 // It is possible that non-constant live variables have a constant base. For
2722 // example, a GEP with a variable offset from a global. In this case we can
2723 // remove it from the liveset. We already don't add constants to the liveset
2724 // because we assume they won't move at runtime and the GC doesn't need to be
2725 // informed about them. The same reasoning applies if the base is constant.
2726 // Note that the relocation placement code relies on this filtering for
2727 // correctness as it expects the base to be in the liveset, which isn't true
2728 // if the base is constant.
2729 for (auto &Info : Records) {
2730 Info.LiveSet.remove_if([&](Value *LiveV) {
2731 assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
2732 return isa<Constant>(PointerToBase[LiveV]);
2733 });
2734 }
2735
2736 for (CallInst *CI : Holders)
2737 CI->eraseFromParent();
2738
2739 Holders.clear();
2740
2741 // Compute the cost of possible re-materialization of derived pointers.
2742 RematCandTy RematerizationCandidates;
2743 findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
2744
2745 // In order to reduce live set of statepoint we might choose to rematerialize
2746 // some values instead of relocating them. This is purely an optimization and
2747 // does not influence correctness.
2748 // First try rematerialization at uses, then after statepoints.
2749 rematerializeLiveValuesAtUses(Opts, RematerizationCandidates, Records,
2750 PointerToBase);
2751 for (size_t i = 0; i < Records.size(); i++)
2752 rematerializeLiveValues(Opts, ToUpdate[i], Records[i], PointerToBase,
2753 RematerizationCandidates, TTI);
2754
2755 // We need this to safely RAUW and delete call or invoke return values that
2756 // may themselves be live over a statepoint. For details, please see usage in
2757 // makeStatepointExplicitImpl.
2758 std::vector<DeferredReplacement> Replacements;
2759
2760 // Now run through and replace the existing statepoints with new ones with
2761 // the live variables listed. We do not yet update uses of the values being
2762 // relocated. We have references to live variables that need to
2763 // survive to the last iteration of this loop. (By construction, the
2764 // previous statepoint can not be a live variable, thus we can and remove
2765 // the old statepoint calls as we go.)
2766 for (size_t i = 0; i < Records.size(); i++)
2767 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
2768 PointerToBase, GC.get());
2769
2770 ToUpdate.clear(); // prevent accident use of invalid calls.
2771
2772 for (auto &PR : Replacements)
2773 PR.doReplacement();
2774
2775 Replacements.clear();
2776
2777 for (auto &Info : Records) {
2778 // These live sets may contain state Value pointers, since we replaced calls
2779 // with operand bundles with calls wrapped in gc.statepoint, and some of
2780 // those calls may have been def'ing live gc pointers. Clear these out to
2781 // avoid accidentally using them.
2782 //
2783 // TODO: We should create a separate data structure that does not contain
2784 // these live sets, and migrate to using that data structure from this point
2785 // onward.
2786 Info.LiveSet.clear();
2787 }
2788 PointerToBase.clear();
2789
2790 // Do all the fixups of the original live variables to their relocated selves.
2791 // A SmallSetVector is used to collect live variables while retaining the
2792 // order in which we add them, which is important for reproducible tests.
2794 for (const PartiallyConstructedSafepointRecord &Info : Records) {
2795 // We can't simply save the live set from the original insertion. One of
2796 // the live values might be the result of a call which needs a safepoint.
2797 // That Value* no longer exists and we need to use the new gc_result.
2798 // Thankfully, the live set is embedded in the statepoint (and updated), so
2799 // we just grab that.
2800 Live.insert_range(Info.StatepointToken->gc_live());
2801#ifndef NDEBUG
2802 // Do some basic validation checking on our liveness results before
2803 // performing relocation. Relocation can and will turn mistakes in liveness
2804 // results into non-sensical code which is must harder to debug.
2805 // TODO: It would be nice to test consistency as well
2806 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2807 "statepoint must be reachable or liveness is meaningless");
2808 for (Value *V : Info.StatepointToken->gc_live()) {
2809 if (!isa<Instruction>(V))
2810 // Non-instruction values trivial dominate all possible uses
2811 continue;
2812 auto *LiveInst = cast<Instruction>(V);
2813 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2814 "unreachable values should never be live");
2815 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2816 "basic SSA liveness expectation violated by liveness analysis");
2817 }
2818#endif
2819 }
2820
2821#ifndef NDEBUG
2822 // Validation check
2823 for (auto *Ptr : Live)
2824 assert(isHandledGCPointerType(Ptr->getType(), GC.get()) &&
2825 "must be a gc pointer type");
2826#endif
2827
2828 relocationViaAlloca(F, DT, Live.getArrayRef(), Records);
2829 return !Records.empty();
2830}
2831
2832// List of all parameter and return attributes which must be stripped when
2833// lowering from the abstract machine model. Note that we list attributes
2834// here which aren't valid as return attributes, that is okay.
2836 AttributeMask R;
2837 R.addAttribute(Attribute::Dereferenceable);
2838 R.addAttribute(Attribute::DereferenceableOrNull);
2839 R.addAttribute(Attribute::ReadNone);
2840 R.addAttribute(Attribute::ReadOnly);
2841 R.addAttribute(Attribute::WriteOnly);
2842 R.addAttribute(Attribute::NoAlias);
2843 R.addAttribute(Attribute::NoFree);
2844 return R;
2845}
2846
2848 LLVMContext &Ctx = F.getContext();
2849
2850 // Intrinsics are very delicate. Lowering sometimes depends the presence
2851 // of certain attributes for correctness, but we may have also inferred
2852 // additional ones in the abstract machine model which need stripped. This
2853 // assumes that the attributes defined in Intrinsic.td are conservatively
2854 // correct for both physical and abstract model.
2855 if (Intrinsic::ID id = F.getIntrinsicID()) {
2856 F.setAttributes(Intrinsic::getAttributes(Ctx, id, F.getFunctionType()));
2857 return;
2858 }
2859
2861 for (Argument &A : F.args())
2862 if (isa<PointerType>(A.getType()))
2863 F.removeParamAttrs(A.getArgNo(), R);
2864
2865 if (isa<PointerType>(F.getReturnType()))
2866 F.removeRetAttrs(R);
2867
2868 for (auto Attr : FnAttrsToStrip)
2869 F.removeFnAttr(Attr);
2870}
2871
2872/// Certain metadata on instructions are invalid after running RS4GC.
2873/// Optimizations that run after RS4GC can incorrectly use this metadata to
2874/// optimize functions. We drop such metadata on the instruction.
2876 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2877 return;
2878 // These are the attributes that are still valid on loads and stores after
2879 // RS4GC.
2880 // The metadata implying dereferenceability and noalias are (conservatively)
2881 // dropped. This is because semantically, after RewriteStatepointsForGC runs,
2882 // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2883 // touch the entire heap including noalias objects. Note: The reasoning is
2884 // same as stripping the dereferenceability and noalias attributes that are
2885 // analogous to the metadata counterparts.
2886 // We also drop the invariant.load metadata on the load because that metadata
2887 // implies the address operand to the load points to memory that is never
2888 // changed once it became dereferenceable. This is no longer true after RS4GC.
2889 // Similar reasoning applies to invariant.group metadata, which applies to
2890 // loads within a group.
2891 unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2892 LLVMContext::MD_range,
2893 LLVMContext::MD_alias_scope,
2894 LLVMContext::MD_nontemporal,
2895 LLVMContext::MD_nonnull,
2896 LLVMContext::MD_align,
2897 LLVMContext::MD_type};
2898
2899 // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2900 I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2901}
2902
2904 if (F.empty())
2905 return;
2906
2907 LLVMContext &Ctx = F.getContext();
2908 MDBuilder Builder(Ctx);
2909
2910 // Set of invariantstart instructions that we need to remove.
2911 // Use this to avoid invalidating the instruction iterator.
2912 SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2913
2914 for (Instruction &I : instructions(F)) {
2915 // invariant.start on memory location implies that the referenced memory
2916 // location is constant and unchanging. This is no longer true after
2917 // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2918 // which frees the entire heap and the presence of invariant.start allows
2919 // the optimizer to sink the load of a memory location past a statepoint,
2920 // which is incorrect.
2921 if (auto *II = dyn_cast<IntrinsicInst>(&I))
2922 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2923 InvariantStartInstructions.push_back(II);
2924 continue;
2925 }
2926
2927 if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2928 MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2929 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2930 }
2931
2933
2935 if (auto *Call = dyn_cast<CallBase>(&I)) {
2936 for (int i = 0, e = Call->arg_size(); i != e; i++)
2937 if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2938 Call->removeParamAttrs(i, R);
2939 if (isa<PointerType>(Call->getType()))
2940 Call->removeRetAttrs(R);
2941 }
2942 }
2943
2944 // Delete the invariant.start instructions and RAUW poison.
2945 for (auto *II : InvariantStartInstructions) {
2946 II->replaceAllUsesWith(PoisonValue::get(II->getType()));
2947 II->eraseFromParent();
2948 }
2949}
2950
2951/// Looks up the GC strategy for a given function, returning null if the
2952/// function doesn't have a GC tag. The strategy is stored in the cache.
2953static std::unique_ptr<GCStrategy> findGCStrategy(Function &F) {
2954 if (!F.hasGC())
2955 return nullptr;
2956
2957 return getGCStrategy(F.getGC());
2958}
2959
2960/// Returns true if this function should be rewritten by this pass. The main
2961/// point of this function is as an extension point for custom logic.
2963 if (!F.hasGC())
2964 return false;
2965
2966 std::unique_ptr<GCStrategy> Strategy = findGCStrategy(F);
2967
2968 assert(Strategy && "GC strategy is required by function, but was not found");
2969
2970 return Strategy->useRS4GC();
2971}
2972
2973static void stripNonValidData(Module &M) {
2974#ifndef NDEBUG
2975 assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
2976#endif
2977
2978 for (Function &F : M)
2980
2981 for (Function &F : M)
2983}
2984
2987 const TargetLibraryInfo &TLI) {
2988 assert(!F.isDeclaration() && !F.empty() &&
2989 "need function body to rewrite statepoints in");
2990 assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
2991 const ScalarOptions &Opts = getScalarOptions(F);
2992
2993 auto NeedsRewrite = [&](Instruction &I) {
2994 if (const auto *Call = dyn_cast<CallBase>(&I)) {
2996 return false;
2997 if (callsGCLeafFunction(Call, TLI))
2998 return false;
2999
3000 // Normally it's up to the frontend to make sure that non-leaf calls also
3001 // have proper deopt state if it is required. We make an exception for
3002 // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
3003 // these are non-leaf by default. They might be generated by the optimizer
3004 // which doesn't know how to produce a proper deopt state. So if we see a
3005 // non-leaf memcpy/memmove without deopt state just treat it as a leaf
3006 // copy and don't produce a statepoint.
3007 if (!Opts.rs4gc_allow_statepoint_with_no_deopt_info &&
3008 !Call->hasDeoptState()) {
3010 cast<AnyMemTransferInst>(Call)->isAtomic() &&
3011 "Don't expect any other calls here!");
3012 return false;
3013 }
3014 return true;
3015 }
3016 return false;
3017 };
3018
3019 // Delete any unreachable statepoints so that we don't have unrewritten
3020 // statepoints surviving this pass. This makes testing easier and the
3021 // resulting IR less confusing to human readers.
3022 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3023 bool MadeChange = removeUnreachableBlocks(F, &DTU);
3024 // Flush the Dominator Tree.
3025 DTU.getDomTree();
3026
3027 // Gather all the statepoints which need rewritten. Be careful to only
3028 // consider those in reachable code since we need to ask dominance queries
3029 // when rewriting. We'll delete the unreachable ones in a moment.
3030 SmallVector<CallBase *, 64> ParsePointNeeded;
3031 SmallVector<CallInst *, 64> Intrinsics;
3032 for (Instruction &I : instructions(F)) {
3033 // TODO: only the ones with the flag set!
3034 if (NeedsRewrite(I)) {
3035 // NOTE removeUnreachableBlocks() is stronger than
3036 // DominatorTree::isReachableFromEntry(). In other words
3037 // removeUnreachableBlocks can remove some blocks for which
3038 // isReachableFromEntry() returns true.
3039 assert(DT.isReachableFromEntry(I.getParent()) &&
3040 "no unreachable blocks expected");
3041 ParsePointNeeded.push_back(cast<CallBase>(&I));
3042 }
3043 if (auto *CI = dyn_cast<CallInst>(&I))
3044 if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
3045 CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
3046 Intrinsics.emplace_back(CI);
3047 }
3048
3049 // Return early if no work to do.
3050 if (ParsePointNeeded.empty() && Intrinsics.empty())
3051 return MadeChange;
3052
3053 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
3054 // These are created by LCSSA. They have the effect of increasing the size
3055 // of liveness sets for no good reason. It may be harder to do this post
3056 // insertion since relocations and base phis can confuse things.
3057 for (BasicBlock &BB : F)
3058 if (BB.getUniquePredecessor())
3059 MadeChange |= FoldSingleEntryPHINodes(&BB);
3060
3061 // Before we start introducing relocations, we want to tweak the IR a bit to
3062 // avoid unfortunate code generation effects. The main example is that we
3063 // want to try to make sure the comparison feeding a branch is after any
3064 // safepoints. Otherwise, we end up with a comparison of pre-relocation
3065 // values feeding a branch after relocation. This is semantically correct,
3066 // but results in extra register pressure since both the pre-relocation and
3067 // post-relocation copies must be available in registers. For code without
3068 // relocations this is handled elsewhere, but teaching the scheduler to
3069 // reverse the transform we're about to do would be slightly complex.
3070 // Note: This may extend the live range of the inputs to the icmp and thus
3071 // increase the liveset of any statepoint we move over. This is profitable
3072 // as long as all statepoints are in rare blocks. If we had in-register
3073 // lowering for live values this would be a much safer transform.
3074 auto getConditionInst = [](Instruction *TI) -> Instruction * {
3075 if (auto *BI = dyn_cast<CondBrInst>(TI))
3076 return dyn_cast<Instruction>(BI->getCondition());
3077 // TODO: Extend this to handle switches
3078 return nullptr;
3079 };
3080 for (BasicBlock &BB : F) {
3081 Instruction *TI = BB.getTerminator();
3082 if (auto *Cond = getConditionInst(TI))
3083 // TODO: Handle more than just ICmps here. We should be able to move
3084 // most instructions without side effects or memory access.
3085 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
3086 MadeChange = true;
3087 Cond->moveBefore(TI->getIterator());
3088 }
3089 }
3090
3091 // Nasty workaround - The base computation code in the main algorithm doesn't
3092 // consider the fact that a GEP can be used to convert a scalar to a vector.
3093 // The right fix for this is to integrate GEPs into the base rewriting
3094 // algorithm properly, this is just a short term workaround to prevent
3095 // crashes by canonicalizing such GEPs into fully vector GEPs.
3096 for (Instruction &I : instructions(F)) {
3098 continue;
3099
3100 unsigned VF = 0;
3101 for (unsigned i = 0; i < I.getNumOperands(); i++)
3102 if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
3103 assert(VF == 0 ||
3104 VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
3105 VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
3106 }
3107
3108 // It's the vector to scalar traversal through the pointer operand which
3109 // confuses base pointer rewriting, so limit ourselves to that case.
3110 if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
3111 IRBuilder<> B(&I);
3112 auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
3113 I.setOperand(0, Splat);
3114 MadeChange = true;
3115 }
3116 }
3117
3118 // Cache the 'defining value' relation used in the computation and
3119 // insertion of base phis and selects. This ensures that we don't insert
3120 // large numbers of duplicate base_phis. Use one cache for both
3121 // inlineGetBaseAndOffset() and insertParsePoints().
3122 DefiningValueMapTy DVCache;
3123
3124 // Mapping between a base values and a flag indicating whether it's a known
3125 // base or not.
3126 IsKnownBaseMapTy KnownBases;
3127
3128 if (!Intrinsics.empty())
3129 // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
3130 // live references.
3131 MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
3132
3133 if (!ParsePointNeeded.empty())
3134 MadeChange |= insertParsePoints(Opts, F, DT, TTI, ParsePointNeeded, DVCache,
3135 KnownBases);
3136
3137 return MadeChange;
3138}
3139
3140// liveness computation via standard dataflow
3141// -------------------------------------------------------------------
3142
3143// TODO: Consider using bitvectors for liveness, the set of potentially
3144// interesting values should be small and easy to pre-compute.
3145
3146/// Compute the live-in set for the location rbegin starting from
3147/// the live-out set of the basic block
3150 SetVector<Value *> &LiveTmp, GCStrategy *GC) {
3151 for (auto &I : make_range(Begin, End)) {
3152 // KILL/Def - Remove this definition from LiveIn
3153 LiveTmp.remove(&I);
3154
3155 // Don't consider *uses* in PHI nodes, we handle their contribution to
3156 // predecessor blocks when we seed the LiveOut sets
3157 if (isa<PHINode>(I))
3158 continue;
3159
3160 // USE - Add to the LiveIn set for this instruction
3161 for (Value *V : I.operands()) {
3162 assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3163 "support for FCA unimplemented");
3164 if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V)) {
3165 // The choice to exclude all things constant here is slightly subtle.
3166 // There are two independent reasons:
3167 // - We assume that things which are constant (from LLVM's definition)
3168 // do not move at runtime. For example, the address of a global
3169 // variable is fixed, even though it's contents may not be.
3170 // - Second, we can't disallow arbitrary inttoptr constants even
3171 // if the language frontend does. Optimization passes are free to
3172 // locally exploit facts without respect to global reachability. This
3173 // can create sections of code which are dynamically unreachable and
3174 // contain just about anything. (see constants.ll in tests)
3175 LiveTmp.insert(V);
3176 }
3177 }
3178 }
3179}
3180
3182 GCStrategy *GC) {
3183 for (BasicBlock *Succ : successors(BB)) {
3184 for (auto &I : *Succ) {
3185 PHINode *PN = dyn_cast<PHINode>(&I);
3186 if (!PN)
3187 break;
3188
3189 Value *V = PN->getIncomingValueForBlock(BB);
3190 assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3191 "support for FCA unimplemented");
3192 if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V))
3193 LiveTmp.insert(V);
3194 }
3195 }
3196}
3197
3199 SetVector<Value *> KillSet;
3200 for (Instruction &I : *BB)
3201 if (isHandledGCPointerType(I.getType(), GC))
3202 KillSet.insert(&I);
3203 return KillSet;
3204}
3205
3206#ifndef NDEBUG
3207/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
3208/// validation check for the liveness computation.
3210 Instruction *TI, bool TermOkay = false) {
3211 for (Value *V : Live) {
3212 if (auto *I = dyn_cast<Instruction>(V)) {
3213 // The terminator can be a member of the LiveOut set. LLVM's definition
3214 // of instruction dominance states that V does not dominate itself. As
3215 // such, we need to special case this to allow it.
3216 if (TermOkay && TI == I)
3217 continue;
3218 assert(DT.dominates(I, TI) &&
3219 "basic SSA liveness expectation violated by liveness analysis");
3220 }
3221 }
3222}
3223
3224/// Check that all the liveness sets used during the computation of liveness
3225/// obey basic SSA properties. This is useful for finding cases where we miss
3226/// a def.
3227static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
3228 BasicBlock &BB) {
3229 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
3230 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
3231 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
3232}
3233#endif
3234
3236 GCPtrLivenessData &Data, GCStrategy *GC) {
3238
3239 // Seed the liveness for each individual block
3240 for (BasicBlock &BB : F) {
3241 Data.KillSet[&BB] = computeKillSet(&BB, GC);
3242 auto &LiveSet = Data.LiveSet[&BB];
3243 LiveSet.clear();
3244 computeLiveInValues(BB.rbegin(), BB.rend(), LiveSet, GC);
3245
3246#ifndef NDEBUG
3247 for (Value *Kill : Data.KillSet[&BB])
3248 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
3249#endif
3250
3251 auto &Out = Data.LiveOut[&BB] = SetVector<Value *>();
3252 computeLiveOutSeed(&BB, Out, GC);
3253 auto &In = Data.LiveIn[&BB] = Data.LiveSet[&BB];
3254 In.set_union(Out);
3255 In.set_subtract(Data.KillSet[&BB]);
3256 if (!In.empty())
3257 Worklist.insert_range(predecessors(&BB));
3258 }
3259
3260 // Propagate that liveness until stable
3261 while (!Worklist.empty()) {
3262 BasicBlock *BB = Worklist.pop_back_val();
3263
3264 // Compute our new liveout set, then exit early if it hasn't changed despite
3265 // the contribution of our successor.
3266 SetVector<Value *> &LiveOut = Data.LiveOut[BB];
3267 const auto OldLiveOutSize = LiveOut.size();
3268 for (BasicBlock *Succ : successors(BB)) {
3269 assert(Data.LiveIn.count(Succ));
3270 LiveOut.set_union(Data.LiveIn[Succ]);
3271 }
3272 // assert OutLiveOut is a subset of LiveOut
3273 if (OldLiveOutSize == LiveOut.size()) {
3274 // If the sets are the same size, then we didn't actually add anything
3275 // when unioning our successors LiveIn. Thus, the LiveIn of this block
3276 // hasn't changed.
3277 continue;
3278 }
3279
3280 // Apply the effects of this basic block
3281 SetVector<Value *> LiveTmp = LiveOut;
3282 LiveTmp.set_union(Data.LiveSet[BB]);
3283 LiveTmp.set_subtract(Data.KillSet[BB]);
3284
3285 assert(Data.LiveIn.count(BB));
3286 SetVector<Value *> &LiveIn = Data.LiveIn[BB];
3287 // assert: LiveIn is a subset of LiveTmp
3288 if (LiveIn.size() != LiveTmp.size()) {
3289 LiveIn = std::move(LiveTmp);
3290 Worklist.insert_range(predecessors(BB));
3291 }
3292 } // while (!Worklist.empty())
3293
3294#ifndef NDEBUG
3295 // Verify our output against SSA properties. This helps catch any
3296 // missing kills during the above iteration.
3297 for (BasicBlock &BB : F)
3298 checkBasicSSA(DT, Data, BB);
3299#endif
3300}
3301
3302static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
3303 StatepointLiveSetTy &Out, GCStrategy *GC) {
3304 BasicBlock *BB = Inst->getParent();
3305
3306 // Note: The copy is intentional and required
3307 assert(Data.LiveOut.count(BB));
3308 SetVector<Value *> LiveOut = Data.LiveOut[BB];
3309
3310 // We want to handle the statepoint itself oddly. It's
3311 // call result is not live (normal), nor are it's arguments
3312 // (unless they're used again later). This adjustment is
3313 // specifically what we need to relocate
3314 computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(), LiveOut,
3315 GC);
3316 LiveOut.remove(Inst);
3317 Out.insert_range(LiveOut);
3318}
3319
3320static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
3321 CallBase *Call,
3322 PartiallyConstructedSafepointRecord &Info,
3323 PointerToBaseTy &PointerToBase,
3324 GCStrategy *GC) {
3325 StatepointLiveSetTy Updated;
3326 findLiveSetAtInst(Call, RevisedLivenessData, Updated, GC);
3327
3328 // We may have base pointers which are now live that weren't before. We need
3329 // to update the PointerToBase structure to reflect this.
3330 for (auto *V : Updated)
3331 PointerToBase.insert({ V, V });
3332
3333 Info.LiveSet = Updated;
3334}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
SmallVector< MachineOperand, 4 > Cond
Remove Loads Into Fake Uses
static void makeStatepointExplicitImpl(CallBase *Call, const SmallVectorImpl< Value * > &BasePtrs, const SmallVectorImpl< Value * > &LiveVariables, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements, const PointerToBaseTy &PointerToBase, GCStrategy *GC)
static void findRematerializationCandidates(PointerToBaseTy PointerToBase, RematCandTy &RematerizationCandidates, TargetTransformInfo &TTI)
static std::unique_ptr< GCStrategy > findGCStrategy(Function &F)
Looks up the GC strategy for a given function, returning null if the function doesn't have a GC tag.
static void stripNonValidDataFromBody(Function &F)
static void analyzeParsePointLiveness(const ScalarOptions &Opts, DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call, PartiallyConstructedSafepointRecord &Result, GCStrategy *GC)
static ArrayRef< Use > getDeoptBundleOperands(const ScalarOptions &Opts, const CallBase *Call)
static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases)
Returns true if V is a known base.
static Value * findBasePointer(Value *I, DefiningValueMapTy &Cache, IsKnownBaseMapTy &KnownBases)
For a given value or instruction, figure out what base ptr its derived from.
static cl::opt< bool, true > ClobberNonLiveOverride("rs4gc-clobber-non-live", cl::location(ClobberNonLive), cl::Hidden)
static BasicBlock * normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, DominatorTree &DT)
static bool insertParsePoints(const ScalarOptions &Opts, Function &F, DominatorTree &DT, TargetTransformInfo &TTI, SmallVectorImpl< CallBase * > &ToUpdate, DefiningValueMapTy &DVCache, IsKnownBaseMapTy &KnownBases)
static void computeLiveOutSeed(BasicBlock *BB, SetVector< Value * > &LiveTmp, GCStrategy *GC)
static void relocationViaAlloca(Function &F, DominatorTree &DT, ArrayRef< Value * > Live, ArrayRef< PartiallyConstructedSafepointRecord > Records)
Do all the relocation update via allocas and mem2reg.
static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi)
static void rematerializeLiveValues(const ScalarOptions &Opts, CallBase *Call, PartiallyConstructedSafepointRecord &Info, PointerToBaseTy &PointerToBase, RematCandTy &RematerizationCandidates, TargetTransformInfo &TTI)
static Value * findBaseOrBDV(Value *I, DefiningValueMapTy &Cache, IsKnownBaseMapTy &KnownBases)
Return a base pointer for this value if known.
static Value * findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache, IsKnownBaseMapTy &KnownBases)
Returns the base defining value for this value.
static void insertUseHolderAfter(CallBase *Call, const ArrayRef< Value * > Values, SmallVectorImpl< CallInst * > &Holders)
Insert holders so that each Value is obviously live through the entire lifetime of the call.
static AttributeList legalizeCallAttributes(CallBase *Call, bool IsMemIntrinsic, AttributeList StatepointAL)
static void insertRematerializationStores(const RematerializedValueMapTy &RematerializedValues, DenseMap< Value *, AllocaInst * > &AllocaMap, DenseSet< Value * > &VisitedLiveValues)
static void findBasePointers(const StatepointLiveSetTy &live, PointerToBaseTy &PointerToBase, DominatorTree *DT, DefiningValueMapTy &DVCache, IsKnownBaseMapTy &KnownBases)
static bool shouldRewriteStatepointsIn(Function &F)
Returns true if this function should be rewritten by this pass.
static Instruction * rematerializeChain(ArrayRef< Instruction * > ChainToBase, BasicBlock::iterator InsertBefore, Value *RootOfChain, Value *AlternateLiveBase)
static void stripNonValidAttributesFromPrototype(Function &F)
static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data, StatepointLiveSetTy &out, GCStrategy *GC)
Given results from the dataflow liveness computation, find the set of live Values at a particular ins...
static void computeLiveInValues(DominatorTree &DT, Function &F, GCPtrLivenessData &Data, GCStrategy *GC)
Compute the live-in set for every basic block in the function.
static void stripInvalidMetadataFromInstruction(Instruction &I)
Certain metadata on instructions are invalid after running RS4GC.
static constexpr Attribute::AttrKind FnAttrsToStrip[]
static bool areBothVectorOrScalar(Value *First, Value *Second)
static bool isHandledGCPointerType(Type *T, GCStrategy *GC)
static Value * findRematerializableChainToBasePointer(SmallVectorImpl< Instruction * > &ChainToBase, Value *CurrentValue)
static Value * findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache, IsKnownBaseMapTy &KnownBases)
Return a base defining value for the 'Index' element of the given vector instruction 'I'.
static void stripNonValidData(Module &M)
The IR fed into RewriteStatepointsForGC may have had attributes and metadata implying dereferenceabil...
static InstructionCost chainToBasePointerCost(SmallVectorImpl< Instruction * > &Chain, TargetTransformInfo &TTI)
static bool isUnhandledGCPointerType(Type *Ty, GCStrategy *GC)
static SetVector< Value * > computeKillSet(BasicBlock *BB, GCStrategy *GC)
static bool ClobberNonLive
static bool isOriginalBaseResult(Value *V)
This value is a base pointer that is not generated by RS4GC, i.e.
static void insertRelocationStores(iterator_range< Instruction::user_iterator > GCRelocs, DenseMap< Value *, AllocaInst * > &AllocaMap, DenseSet< Value * > &VisitedLiveValues)
static void setKnownBase(Value *V, bool IsKnownBase, IsKnownBaseMapTy &KnownBases)
Caches the IsKnownBase flag for a value and asserts that it wasn't present in the cache before.
static void makeStatepointExplicit(DominatorTree &DT, CallBase *Call, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements, const PointerToBaseTy &PointerToBase, GCStrategy *GC)
static std::string suffixed_name_or(Value *V, StringRef Suffix, StringRef DefaultName)
static void CreateGCRelocates(ArrayRef< Value * > LiveVariables, ArrayRef< Value * > BasePtrs, Instruction *StatepointToken, IRBuilder<> &Builder, GCStrategy *GC)
Helper function to place all gc relocates necessary for the given statepoint.
static void checkBasicSSA(DominatorTree &DT, SetVector< Value * > &Live, Instruction *TI, bool TermOkay=false)
Check that the items in 'Live' dominate 'TI'.
static StringRef getDeoptLowering(CallBase *Call)
static void findLiveReferences(const ScalarOptions &Opts, Function &F, DominatorTree &DT, ArrayRef< CallBase * > toUpdate, MutableArrayRef< struct PartiallyConstructedSafepointRecord > records, GCStrategy *GC)
static AttributeMask getParamAndReturnAttributesToRemove()
static bool inlineGetBaseAndOffset(Function &F, SmallVectorImpl< CallInst * > &Intrinsics, DefiningValueMapTy &DVCache, IsKnownBaseMapTy &KnownBases)
static Value * findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache, IsKnownBaseMapTy &KnownBases)
Helper function for findBasePointer - Will return a value which either a) defines the base pointer fo...
static void rematerializeLiveValuesAtUses(const ScalarOptions &Opts, RematCandTy &RematerizationCandidates, MutableArrayRef< PartiallyConstructedSafepointRecord > Records, PointerToBaseTy &PointerToBase)
static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, CallBase *Call, PartiallyConstructedSafepointRecord &result, PointerToBaseTy &PointerToBase, GCStrategy *GC)
Given an updated version of the dataflow liveness results, update the liveset and base pointer maps f...
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR static false bool isGCPointerType(Type *T)
static bool containsGCPtrType(Type *Ty)
Provides some synthesis utilities to produce sequences of values.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
The Input class is used to parse a yaml document into in-memory structs and vectors.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
Value handle that asserts if the Value is deleted.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
reverse_iterator rbegin()
Definition BasicBlock.h:456
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:172
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Represents calls to the gc.relocate intrinsic.
LLVM_ABI Value * getDerivedPtr() const
Represents a gc.statepoint intrinsic call.
Definition Statepoint.h:61
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition GCStrategy.h:64
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
A wrapper class for inspecting calls to intrinsic functions.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
size_type count(const KeyT &Key) const
Definition MapVector.h:152
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool set_union(const STy &S)
Compute This := This u S, return whether 'This' changed.
Definition SetVector.h:303
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
void set_subtract(const STy &S)
Compute This := This - B TODO: We should be able to use set_subtract from SetOperations....
Definition SetVector.h:317
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Class to represent struct types.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
Definition Value.cpp:181
LLVM_ABI unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition Value.cpp:258
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
bool user_empty() const
Definition Value.h:391
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
LocationClass< Ty > location(Ty &L)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
InstructionCost Cost
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Unknown
Not known to have no common set bits.
@ Kill
The last use of a register.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2911
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI StatepointDirectives parseStatepointDirectivesFromAttrs(AttributeList AS)
Parse out statepoint directives from the function attributes present in AS.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
DWARFExpression::Operation Op
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
@ DeoptLiveIn
Mark the deopt arguments associated with the statepoint as only being "live-in".
Definition Statepoint.h:49
@ GCTransition
Indicates that this statepoint is a transition from GC-aware code to code that is not GC-aware.
Definition Statepoint.h:41
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI bool isStatepointDirectiveAttr(Attribute Attr)
Return true if the Attr is an attribute that is a statepoint directive.
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition Local.cpp:3325
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI bool runOnFunction(Function &F, DominatorTree &, TargetTransformInfo &, const TargetLibraryInfo &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Call sites that get wrapped by a gc.statepoint (currently only in RewriteStatepointsForGC and potenti...
Definition Statepoint.h:235
std::optional< uint32_t > NumPatchBytes
Definition Statepoint.h:236
std::optional< uint64_t > StatepointID
Definition Statepoint.h:237
static const uint64_t DefaultStatepointID
Definition Statepoint.h:239