clang-format all the GC related files (NFC)

Nothing interesting here...




git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@226342 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Philip Reames 2015-01-16 23:16:12 +00:00
parent 61bd005d1b
commit 999412767a
14 changed files with 583 additions and 597 deletions

View File

@ -41,42 +41,41 @@
#include <memory>
namespace llvm {
class AsmPrinter;
class Constant;
class MCSymbol;
class AsmPrinter;
class Constant;
class MCSymbol;
/// GCPoint - Metadata for a collector-safe point in machine code.
///
struct GCPoint {
/// GCPoint - Metadata for a collector-safe point in machine code.
///
struct GCPoint {
GC::PointKind Kind; ///< The kind of the safe point.
MCSymbol *Label; ///< A label.
DebugLoc Loc;
GCPoint(GC::PointKind K, MCSymbol *L, DebugLoc DL)
: Kind(K), Label(L), Loc(DL) {}
};
};
/// GCRoot - Metadata for a pointer to an object managed by the garbage
/// collector.
struct GCRoot {
/// GCRoot - Metadata for a pointer to an object managed by the garbage
/// collector.
struct GCRoot {
int Num; ///< Usually a frame index.
int StackOffset; ///< Offset from the stack pointer.
const Constant *Metadata; ///< Metadata straight from the call
///< to llvm.gcroot.
GCRoot(int N, const Constant *MD) : Num(N), StackOffset(-1), Metadata(MD) {}
};
};
/// Garbage collection metadata for a single function. Currently, this
/// information only applies to GCStrategies which use GCRoot.
class GCFunctionInfo {
public:
/// Garbage collection metadata for a single function. Currently, this
/// information only applies to GCStrategies which use GCRoot.
class GCFunctionInfo {
public:
typedef std::vector<GCPoint>::iterator iterator;
typedef std::vector<GCRoot>::iterator roots_iterator;
typedef std::vector<GCRoot>::const_iterator live_iterator;
private:
private:
const Function &F;
GCStrategy &S;
uint64_t FrameSize;
@ -93,7 +92,7 @@ namespace llvm {
// The bit vector is the more compact representation where >3.2% of roots
// are live per safe point (1.5% on 64-bit hosts).
public:
public:
GCFunctionInfo(const Function &F, GCStrategy &S);
~GCFunctionInfo();
@ -138,24 +137,25 @@ namespace llvm {
/// roots_begin/roots_end - Iterators for all roots in the function.
///
roots_iterator roots_begin() { return Roots.begin(); }
roots_iterator roots_end () { return Roots.end(); }
roots_iterator roots_end() { return Roots.end(); }
size_t roots_size() const { return Roots.size(); }
/// live_begin/live_end - Iterators for live roots at a given safe point.
///
live_iterator live_begin(const iterator &p) { return roots_begin(); }
live_iterator live_end (const iterator &p) { return roots_end(); }
live_iterator live_end(const iterator &p) { return roots_end(); }
size_t live_size(const iterator &p) const { return roots_size(); }
};
};
/// An analysis pass which caches information about the entire Module.
/// Records both the function level information used by GCRoots and a
/// cache of the 'active' gc strategy objects for the current Module.
class GCModuleInfo : public ImmutablePass {
/// An analysis pass which caches information about the entire Module.
/// Records both the function level information used by GCRoots and a
/// cache of the 'active' gc strategy objects for the current Module.
class GCModuleInfo : public ImmutablePass {
/// A list of GCStrategies which are active in this Module. These are
/// not owning pointers.
std::vector<GCStrategy*> StrategyList;
public:
std::vector<GCStrategy *> StrategyList;
public:
/// List of per function info objects. In theory, Each of these
/// may be associated with a different GC.
typedef std::vector<std::unique_ptr<GCFunctionInfo>> FuncInfoVec;
@ -163,18 +163,17 @@ namespace llvm {
FuncInfoVec::iterator funcinfo_begin() { return Functions.begin(); }
FuncInfoVec::iterator funcinfo_end() { return Functions.end(); }
private:
private:
/// Owning list of all GCFunctionInfos associated with this Module
FuncInfoVec Functions;
/// Non-owning map to bypass linear search when finding the GCFunctionInfo
/// associated with a particular Function.
typedef DenseMap<const Function*,GCFunctionInfo*> finfo_map_type;
typedef DenseMap<const Function *, GCFunctionInfo *> finfo_map_type;
finfo_map_type FInfoMap;
public:
typedef std::vector<GCStrategy*>::const_iterator iterator;
public:
typedef std::vector<GCStrategy *>::const_iterator iterator;
static char ID;
@ -194,8 +193,7 @@ namespace llvm {
/// have the side effect of initializing the associated GCStrategy. That
/// will soon change.
GCFunctionInfo &getFunctionInfo(const Function &F);
};
};
}
#endif

View File

@ -26,43 +26,39 @@
namespace llvm {
class GCMetadataPrinter;
class GCMetadataPrinter;
/// GCMetadataPrinterRegistry - The GC assembly printer registry uses all the
/// defaults from Registry.
typedef Registry<GCMetadataPrinter> GCMetadataPrinterRegistry;
/// GCMetadataPrinterRegistry - The GC assembly printer registry uses all the
/// defaults from Registry.
typedef Registry<GCMetadataPrinter> GCMetadataPrinterRegistry;
/// GCMetadataPrinter - Emits GC metadata as assembly code. Instances are
/// created, managed, and owned by the AsmPrinter.
class GCMetadataPrinter {
private:
/// GCMetadataPrinter - Emits GC metadata as assembly code. Instances are
/// created, managed, and owned by the AsmPrinter.
class GCMetadataPrinter {
private:
GCStrategy *S;
friend class AsmPrinter;
protected:
protected:
// May only be subclassed.
GCMetadataPrinter();
private:
private:
GCMetadataPrinter(const GCMetadataPrinter &) LLVM_DELETED_FUNCTION;
GCMetadataPrinter &
operator=(const GCMetadataPrinter &) LLVM_DELETED_FUNCTION;
GCMetadataPrinter &operator=(const GCMetadataPrinter &) LLVM_DELETED_FUNCTION;
public:
public:
GCStrategy &getStrategy() { return *S; }
/// Called before the assembly for the module is generated by
/// the AsmPrinter (but after target specific hooks.)
virtual void beginAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) {}
virtual void beginAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) {}
/// Called after the assembly for the module is generated by
/// the AsmPrinter (but before target specific hooks)
virtual void finishAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) {}
virtual void finishAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) {}
virtual ~GCMetadataPrinter();
};
};
}
#endif

View File

@ -15,29 +15,29 @@
#define LLVM_CODEGEN_GCS_H
namespace llvm {
class GCStrategy;
class GCMetadataPrinter;
class GCStrategy;
class GCMetadataPrinter;
/// FIXME: Collector instances are not useful on their own. These no longer
/// serve any purpose except to link in the plugins.
/// FIXME: Collector instances are not useful on their own. These no longer
/// serve any purpose except to link in the plugins.
/// Creates an ocaml-compatible garbage collector.
void linkOcamlGC();
/// Creates an ocaml-compatible garbage collector.
void linkOcamlGC();
/// Creates an ocaml-compatible metadata printer.
void linkOcamlGCPrinter();
/// Creates an ocaml-compatible metadata printer.
void linkOcamlGCPrinter();
/// Creates an erlang-compatible garbage collector.
void linkErlangGC();
/// Creates an erlang-compatible garbage collector.
void linkErlangGC();
/// Creates an erlang-compatible metadata printer.
void linkErlangGCPrinter();
/// Creates an erlang-compatible metadata printer.
void linkErlangGCPrinter();
/// Creates a shadow stack garbage collector. This collector requires no code
/// generator support.
void linkShadowStackGC();
/// Creates a shadow stack garbage collector. This collector requires no code
/// generator support.
void linkShadowStackGC();
void linkStatepointExampleGC();
void linkStatepointExampleGC();
}
#endif

View File

@ -59,29 +59,28 @@
#include <string>
namespace llvm {
namespace GC {
/// PointKind - The type of a collector-safe point.
///
enum PointKind {
namespace GC {
/// PointKind - The type of a collector-safe point.
///
enum PointKind {
Loop, ///< Instr is a loop (backwards branch).
Return, ///< Instr is a return instruction.
PreCall, ///< Instr is a call instruction.
PostCall ///< Instr is the return address of a call.
};
}
};
}
/// GCStrategy describes a garbage collector algorithm's code generation
/// requirements, and provides overridable hooks for those needs which cannot
/// be abstractly described. GCStrategy objects must be looked up through
/// the Function. The objects themselves are owned by the Context and must
/// be immutable.
class GCStrategy {
private:
/// GCStrategy describes a garbage collector algorithm's code generation
/// requirements, and provides overridable hooks for those needs which cannot
/// be abstractly described. GCStrategy objects must be looked up through
/// the Function. The objects themselves are owned by the Context and must
/// be immutable.
class GCStrategy {
private:
std::string Name;
friend class LLVMContextImpl;
protected:
protected:
bool UseStatepoints; /// Uses gc.statepoints as opposed to gc.roots,
/// if set, none of the other options can be
/// anything but their default values.
@ -93,7 +92,7 @@ namespace llvm {
bool InitRoots; ///< If set, roots are nulled during lowering.
bool UsesMetadata; ///< If set, backend must emit metadata tables.
public:
public:
GCStrategy();
virtual ~GCStrategy() {}
@ -135,9 +134,7 @@ namespace llvm {
/// True if safe points of any kind are required. By default, none are
/// recorded.
bool needsSafePoints() const {
return NeededSafePoints != 0;
}
bool needsSafePoints() const { return NeededSafePoints != 0; }
/// True if the given kind of safe point is required. By default, none are
/// recorded.
@ -178,19 +175,19 @@ namespace llvm {
llvm_unreachable("GCStrategy subclass specified a configuration which"
"requires a custom lowering without providing one");
}
};
};
/// Subclasses of GCStrategy are made available for use during compilation by
/// adding them to the global GCRegistry. This can done either within the
/// LLVM source tree or via a loadable plugin. An example registeration
/// would be:
/// static GCRegistry::Add<CustomGC> X("custom-name",
/// "my custom supper fancy gc strategy");
///
/// Note that to use a custom GCMetadataPrinter w/gc.roots, you must also
/// register your GCMetadataPrinter subclass with the
/// GCMetadataPrinterRegistery as well.
typedef Registry<GCStrategy> GCRegistry;
/// Subclasses of GCStrategy are made available for use during compilation by
/// adding them to the global GCRegistry. This can done either within the
/// LLVM source tree or via a loadable plugin. An example registeration
/// would be:
/// static GCRegistry::Add<CustomGC> X("custom-name",
/// "my custom supper fancy gc strategy");
///
/// Note that to use a custom GCMetadataPrinter w/gc.roots, you must also
/// register your GCMetadataPrinter subclass with the
/// GCMetadataPrinterRegistery as well.
typedef Registry<GCStrategy> GCRegistry;
}
#endif

View File

@ -34,18 +34,16 @@ using namespace llvm;
namespace {
class ErlangGCPrinter : public GCMetadataPrinter {
public:
void finishAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) override;
};
class ErlangGCPrinter : public GCMetadataPrinter {
public:
void finishAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) override;
};
}
static GCMetadataPrinterRegistry::Add<ErlangGCPrinter>
X("erlang", "erlang-compatible garbage collector");
X("erlang", "erlang-compatible garbage collector");
void llvm::linkErlangGCPrinter() { }
void llvm::linkErlangGCPrinter() {}
void ErlangGCPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) {
@ -54,9 +52,9 @@ void ErlangGCPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
// Put this in a custom .note section.
AP.OutStreamer.SwitchSection(AP.getObjFileLowering().getContext()
.getELFSection(".note.gc", ELF::SHT_PROGBITS, 0,
SectionKind::getDataRel()));
AP.OutStreamer.SwitchSection(
AP.getObjFileLowering().getContext().getELFSection(
".note.gc", ELF::SHT_PROGBITS, 0, SectionKind::getDataRel()));
// For each function...
for (GCModuleInfo::FuncInfoVec::iterator FI = Info.funcinfo_begin(),
@ -91,7 +89,7 @@ void ErlangGCPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
// Emit the address of the safe point.
OS.AddComment("safe point address");
MCSymbol *Label = PI->Label;
AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
AP.EmitLabelPlusOffset(Label /*Hi*/, 0 /*Offset*/, 4 /*Size*/);
}
// Stack information never change in safe points! Only print info from the
@ -104,8 +102,9 @@ void ErlangGCPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
// Emit stack arity, i.e. the number of stacked arguments.
unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
MD.getFunction().arg_size() - RegisteredArgs : 0;
unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs
? MD.getFunction().arg_size() - RegisteredArgs
: 0;
OS.AddComment("stack arity");
AP.EmitInt16(StackArity);

View File

@ -32,20 +32,17 @@ using namespace llvm;
namespace {
class OcamlGCMetadataPrinter : public GCMetadataPrinter {
public:
void beginAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) override;
void finishAssembly(Module &M, GCModuleInfo &Info,
AsmPrinter &AP) override;
};
class OcamlGCMetadataPrinter : public GCMetadataPrinter {
public:
void beginAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) override;
void finishAssembly(Module &M, GCModuleInfo &Info, AsmPrinter &AP) override;
};
}
static GCMetadataPrinterRegistry::Add<OcamlGCMetadataPrinter>
Y("ocaml", "ocaml 3.10-compatible collector");
Y("ocaml", "ocaml 3.10-compatible collector");
void llvm::linkOcamlGCPrinter() { }
void llvm::linkOcamlGCPrinter() {}
static void EmitCamlGlobal(const Module &M, AsmPrinter &AP, const char *Id) {
const std::string &MId = M.getModuleIdentifier();
@ -113,7 +110,8 @@ void OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
int NumDescriptors = 0;
for (GCModuleInfo::FuncInfoVec::iterator I = Info.funcinfo_begin(),
IE = Info.funcinfo_end(); I != IE; ++I) {
IE = Info.funcinfo_end();
I != IE; ++I) {
GCFunctionInfo &FI = **I;
if (FI.getStrategy().getName() != getStrategy().getName())
// this function is managed by some other GC
@ -123,7 +121,7 @@ void OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
}
}
if (NumDescriptors >= 1<<16) {
if (NumDescriptors >= 1 << 16) {
// Very rude!
report_fatal_error(" Too much descriptor for ocaml GC");
}
@ -131,19 +129,22 @@ void OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
for (GCModuleInfo::FuncInfoVec::iterator I = Info.funcinfo_begin(),
IE = Info.funcinfo_end(); I != IE; ++I) {
IE = Info.funcinfo_end();
I != IE; ++I) {
GCFunctionInfo &FI = **I;
if (FI.getStrategy().getName() != getStrategy().getName())
// this function is managed by some other GC
continue;
uint64_t FrameSize = FI.getFrameSize();
if (FrameSize >= 1<<16) {
if (FrameSize >= 1 << 16) {
// Very rude!
report_fatal_error("Function '" + FI.getFunction().getName() +
"' is too large for the ocaml GC! "
"Frame size " + Twine(FrameSize) + ">= 65536.\n"
"(" + Twine(uintptr_t(&FI)) + ")");
"Frame size " +
Twine(FrameSize) + ">= 65536.\n"
"(" +
Twine(uintptr_t(&FI)) + ")");
}
AP.OutStreamer.AddComment("live roots for " +
@ -152,11 +153,12 @@ void OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
for (GCFunctionInfo::iterator J = FI.begin(), JE = FI.end(); J != JE; ++J) {
size_t LiveCount = FI.live_size(J);
if (LiveCount >= 1<<16) {
if (LiveCount >= 1 << 16) {
// Very rude!
report_fatal_error("Function '" + FI.getFunction().getName() +
"' is too large for the ocaml GC! "
"Live root count "+Twine(LiveCount)+" >= 65536.");
"Live root count " +
Twine(LiveCount) + " >= 65536.");
}
AP.OutStreamer.EmitSymbolValue(J->Label, IntPtrSize);
@ -164,8 +166,9 @@ void OcamlGCMetadataPrinter::finishAssembly(Module &M, GCModuleInfo &Info,
AP.EmitInt16(LiveCount);
for (GCFunctionInfo::live_iterator K = FI.live_begin(J),
KE = FI.live_end(J); K != KE; ++K) {
if (K->StackOffset >= 1<<16) {
KE = FI.live_end(J);
K != KE; ++K) {
if (K->StackOffset >= 1 << 16) {
// Very rude!
report_fatal_error(
"GC root stack offset is outside of fixed stack frame and out "

View File

@ -27,17 +27,16 @@ using namespace llvm;
namespace {
class ErlangGC : public GCStrategy {
public:
class ErlangGC : public GCStrategy {
public:
ErlangGC();
};
};
}
static GCRegistry::Add<ErlangGC>
X("erlang", "erlang-compatible garbage collector");
static GCRegistry::Add<ErlangGC> X("erlang",
"erlang-compatible garbage collector");
void llvm::linkErlangGC() { }
void llvm::linkErlangGC() {}
ErlangGC::ErlangGC() {
InitRoots = false;

View File

@ -25,21 +25,19 @@ using namespace llvm;
namespace {
class Printer : public FunctionPass {
class Printer : public FunctionPass {
static char ID;
raw_ostream &OS;
public:
public:
explicit Printer(raw_ostream &OS) : FunctionPass(ID), OS(OS) {}
const char *getPassName() const override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
bool doFinalization(Module &M) override;
};
};
}
INITIALIZE_PASS(GCModuleInfo, "collector-metadata",
@ -56,8 +54,7 @@ GCFunctionInfo::~GCFunctionInfo() {}
char GCModuleInfo::ID = 0;
GCModuleInfo::GCModuleInfo()
: ImmutablePass(ID) {
GCModuleInfo::GCModuleInfo() : ImmutablePass(ID) {
initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
}
@ -98,7 +95,6 @@ FunctionPass *llvm::createGCInfoPrinter(raw_ostream &OS) {
return new Printer(OS);
}
const char *Printer::getPassName() const {
return "Print Garbage Collector Information";
}
@ -111,33 +107,40 @@ void Printer::getAnalysisUsage(AnalysisUsage &AU) const {
static const char *DescKind(GC::PointKind Kind) {
switch (Kind) {
case GC::Loop: return "loop";
case GC::Return: return "return";
case GC::PreCall: return "pre-call";
case GC::PostCall: return "post-call";
case GC::Loop:
return "loop";
case GC::Return:
return "return";
case GC::PreCall:
return "pre-call";
case GC::PostCall:
return "post-call";
}
llvm_unreachable("Invalid point kind");
}
bool Printer::runOnFunction(Function &F) {
if (F.hasGC()) return false;
if (F.hasGC())
return false;
GCFunctionInfo *FD = &getAnalysis<GCModuleInfo>().getFunctionInfo(F);
OS << "GC roots for " << FD->getFunction().getName() << ":\n";
for (GCFunctionInfo::roots_iterator RI = FD->roots_begin(),
RE = FD->roots_end(); RI != RE; ++RI)
RE = FD->roots_end();
RI != RE; ++RI)
OS << "\t" << RI->Num << "\t" << RI->StackOffset << "[sp]\n";
OS << "GC safe points for " << FD->getFunction().getName() << ":\n";
for (GCFunctionInfo::iterator PI = FD->begin(),
PE = FD->end(); PI != PE; ++PI) {
for (GCFunctionInfo::iterator PI = FD->begin(), PE = FD->end(); PI != PE;
++PI) {
OS << "\t" << PI->Label->getName() << ": "
<< DescKind(PI->Kind) << ", live = {";
OS << "\t" << PI->Label->getName() << ": " << DescKind(PI->Kind)
<< ", live = {";
for (GCFunctionInfo::live_iterator RI = FD->live_begin(PI),
RE = FD->live_end(PI);;) {
RE = FD->live_end(PI);
;) {
OS << " " << RI->Num;
if (++RI == RE)
break;

View File

@ -14,6 +14,6 @@
#include "llvm/CodeGen/GCMetadataPrinter.h"
using namespace llvm;
GCMetadataPrinter::GCMetadataPrinter() { }
GCMetadataPrinter::GCMetadataPrinter() {}
GCMetadataPrinter::~GCMetadataPrinter() { }
GCMetadataPrinter::~GCMetadataPrinter() {}

View File

@ -116,8 +116,6 @@ static bool NeedsCustomLoweringPass(const GCStrategy &C) {
return C.customWriteBarrier() || C.customReadBarrier() || C.customRoots();
}
/// doInitialization - If this module uses the GC intrinsics, find them now.
bool LowerIntrinsics::doInitialization(Module &M) {
// FIXME: This is rather antisocial in the context of a JIT since it performs
@ -139,7 +137,6 @@ bool LowerIntrinsics::doInitialization(Module &M) {
return MadeChange;
}
/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
/// instruction could introduce a safe point.
static bool CouldBecomeSafePoint(Instruction *I) {
@ -199,7 +196,6 @@ static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
return MadeChange;
}
/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
/// Leave gcroot intrinsics; the code generator needs to see those.
bool LowerIntrinsics::runOnFunction(Function &F) {

View File

@ -20,16 +20,15 @@
using namespace llvm;
namespace {
class OcamlGC : public GCStrategy {
public:
class OcamlGC : public GCStrategy {
public:
OcamlGC();
};
};
}
static GCRegistry::Add<OcamlGC>
X("ocaml", "ocaml 3.10-compatible GC");
static GCRegistry::Add<OcamlGC> X("ocaml", "ocaml 3.10-compatible GC");
void llvm::linkOcamlGC() { }
void llvm::linkOcamlGC() {}
OcamlGC::OcamlGC() {
NeededSafePoints = 1 << GC::PostCall;

View File

@ -39,7 +39,7 @@ using namespace llvm;
namespace {
class ShadowStackGC : public GCStrategy {
class ShadowStackGC : public GCStrategy {
/// RootChain - This is the global linked-list that contains the chain of GC
/// roots.
GlobalVariable *Head;
@ -51,42 +51,41 @@ namespace {
/// Roots - GC roots in the current function. Each is a pair of the
/// intrinsic call and its corresponding alloca.
std::vector<std::pair<CallInst*,AllocaInst*> > Roots;
std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
public:
public:
ShadowStackGC();
bool initializeCustomLowering(Module &M) override;
bool performCustomLowering(Function &F) override;
private:
private:
bool IsNullValue(Value *V);
Constant *GetFrameMap(Function &F);
Type* GetConcreteStackEntryType(Function &F);
Type *GetConcreteStackEntryType(Function &F);
void CollectRoots(Function &F);
static GetElementPtrInst *CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Value *BasePtr,
int Idx1, const char *Name);
static GetElementPtrInst *CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Value *BasePtr,
int Idx1, int Idx2, const char *Name);
};
static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
Value *BasePtr, int Idx1,
const char *Name);
static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
Value *BasePtr, int Idx1, int Idx2,
const char *Name);
};
}
static GCRegistry::Add<ShadowStackGC>
X("shadow-stack", "Very portable GC for uncooperative code generators");
X("shadow-stack", "Very portable GC for uncooperative code generators");
namespace {
/// EscapeEnumerator - This is a little algorithm to find all escape points
/// from a function so that "finally"-style code can be inserted. In addition
/// to finding the existing return and unwind instructions, it also (if
/// necessary) transforms any call instructions into invokes and sends them to
/// a landing pad.
///
/// It's wrapped up in a state machine using the same transform C# uses for
/// 'yield return' enumerators, This transform allows it to be non-allocating.
class EscapeEnumerator {
/// EscapeEnumerator - This is a little algorithm to find all escape points
/// from a function so that "finally"-style code can be inserted. In addition
/// to finding the existing return and unwind instructions, it also (if
/// necessary) transforms any call instructions into invokes and sends them to
/// a landing pad.
///
/// It's wrapped up in a state machine using the same transform C# uses for
/// 'yield return' enumerators, This transform allows it to be non-allocating.
class EscapeEnumerator {
Function &F;
const char *CleanupBBName;
@ -95,7 +94,7 @@ namespace {
Function::iterator StateBB, StateE;
IRBuilder<> Builder;
public:
public:
EscapeEnumerator(Function &F, const char *N = "cleanup")
: F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
@ -127,11 +126,10 @@ namespace {
State = 2;
// Find all 'call' instructions.
SmallVector<Instruction*,16> Calls;
for (Function::iterator BB = F.begin(),
E = F.end(); BB != E; ++BB)
for (BasicBlock::iterator II = BB->begin(),
EE = BB->end(); II != EE; ++II)
SmallVector<Instruction *, 16> Calls;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
for (BasicBlock::iterator II = BB->begin(), EE = BB->end(); II != EE;
++II)
if (CallInst *CI = dyn_cast<CallInst>(II))
if (!CI->getCalledFunction() ||
!CI->getCalledFunction()->getIntrinsicID())
@ -143,22 +141,19 @@ namespace {
// Create a cleanup block.
LLVMContext &C = F.getContext();
BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
Type *ExnTy = StructType::get(Type::getInt8PtrTy(C),
Type::getInt32Ty(C), nullptr);
Constant *PersFn =
F.getParent()->
getOrInsertFunction("__gcc_personality_v0",
FunctionType::get(Type::getInt32Ty(C), true));
LandingPadInst *LPad = LandingPadInst::Create(ExnTy, PersFn, 1,
"cleanup.lpad",
CleanupBB);
Type *ExnTy =
StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr);
Constant *PersFn = F.getParent()->getOrInsertFunction(
"__gcc_personality_v0", FunctionType::get(Type::getInt32Ty(C), true));
LandingPadInst *LPad =
LandingPadInst::Create(ExnTy, PersFn, 1, "cleanup.lpad", CleanupBB);
LPad->setCleanup(true);
ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
// Transform the 'call' instructions into 'invoke's branching to the
// cleanup block. Go in reverse order to make prettier BB names.
SmallVector<Value*,16> Args;
for (unsigned I = Calls.size(); I != 0; ) {
SmallVector<Value *, 16> Args;
for (unsigned I = Calls.size(); I != 0;) {
CallInst *CI = cast<CallInst>(Calls[--I]);
// Split the basic block containing the function call.
@ -175,9 +170,9 @@ namespace {
CallSite CS(CI);
Args.append(CS.arg_begin(), CS.arg_end());
InvokeInst *II = InvokeInst::Create(CI->getCalledValue(),
NewBB, CleanupBB,
Args, CI->getName(), CallBB);
InvokeInst *II =
InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, Args,
CI->getName(), CallBB);
II->setCallingConv(CI->getCallingConv());
II->setAttributes(CI->getAttributes());
CI->replaceAllUsesWith(II);
@ -188,12 +183,12 @@ namespace {
return &Builder;
}
}
};
};
}
// -----------------------------------------------------------------------------
void llvm::linkShadowStackGC() { }
void llvm::linkShadowStackGC() {}
ShadowStackGC::ShadowStackGC() : Head(nullptr), StackEntryTy(nullptr) {
InitRoots = true;
@ -206,7 +201,7 @@ Constant *ShadowStackGC::GetFrameMap(Function &F) {
// Truncate the ShadowStackDescriptor if some metadata is null.
unsigned NumMeta = 0;
SmallVector<Constant*, 16> Metadata;
SmallVector<Constant *, 16> Metadata;
for (unsigned I = 0; I != Roots.size(); ++I) {
Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
if (!C->isNullValue())
@ -224,11 +219,10 @@ Constant *ShadowStackGC::GetFrameMap(Function &F) {
Constant *DescriptorElts[] = {
ConstantStruct::get(FrameMapTy, BaseElts),
ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)
};
ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
Type *EltTys[] = { DescriptorElts[0]->getType(),DescriptorElts[1]->getType()};
StructType *STy = StructType::create(EltTys, "gc_map."+utostr(NumMeta));
Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
@ -246,24 +240,23 @@ Constant *ShadowStackGC::GetFrameMap(Function &F) {
// (which uses a FunctionPassManager (which segfaults (not asserts) if
// provided a ModulePass))).
Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
GlobalVariable::InternalLinkage,
FrameMap, "__gc_" + F.getName());
GlobalVariable::InternalLinkage, FrameMap,
"__gc_" + F.getName());
Constant *GEPIndices[2] = {
ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)
};
ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
return ConstantExpr::getGetElementPtr(GV, GEPIndices);
}
Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
Type *ShadowStackGC::GetConcreteStackEntryType(Function &F) {
// doInitialization creates the generic version of this type.
std::vector<Type*> EltTys;
std::vector<Type *> EltTys;
EltTys.push_back(StackEntryTy);
for (size_t I = 0; I != Roots.size(); I++)
EltTys.push_back(Roots[I].second->getAllocatedType());
return StructType::create(EltTys, "gc_stackentry."+F.getName().str());
return StructType::create(EltTys, "gc_stackentry." + F.getName().str());
}
/// doInitialization - If this module uses the GC intrinsics, find them now. If
@ -274,7 +267,7 @@ bool ShadowStackGC::initializeCustomLowering(Module &M) {
// int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
// void *Meta[]; // May be absent for roots without metadata.
// };
std::vector<Type*> EltTys;
std::vector<Type *> EltTys;
// 32 bits is ok up to a 32GB stack frame. :)
EltTys.push_back(Type::getInt32Ty(M.getContext()));
// Specifies length of variable length array.
@ -301,10 +294,9 @@ bool ShadowStackGC::initializeCustomLowering(Module &M) {
if (!Head) {
// If the root chain does not exist, insert a new one with linkonce
// linkage!
Head = new GlobalVariable(M, StackEntryPtrTy, false,
GlobalValue::LinkOnceAnyLinkage,
Constant::getNullValue(StackEntryPtrTy),
"llvm_gc_root_chain");
Head = new GlobalVariable(
M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
} else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
@ -326,15 +318,16 @@ void ShadowStackGC::CollectRoots(Function &F) {
assert(Roots.empty() && "Not cleaned up?");
SmallVector<std::pair<CallInst*, AllocaInst*>, 16> MetaRoots;
SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
if (Function *F = CI->getCalledFunction())
if (F->getIntrinsicID() == Intrinsic::gcroot) {
std::pair<CallInst*, AllocaInst*> Pair = std::make_pair(
CI, cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
CI,
cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
if (IsNullValue(CI->getArgOperand(1)))
Roots.push_back(Pair);
else
@ -346,24 +339,25 @@ void ShadowStackGC::CollectRoots(Function &F) {
Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
}
GetElementPtrInst *
ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
int Idx, int Idx2, const char *Name) {
Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
GetElementPtrInst *ShadowStackGC::CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Value *BasePtr,
int Idx, int Idx2,
const char *Name) {
Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
ConstantInt::get(Type::getInt32Ty(Context), Idx),
ConstantInt::get(Type::getInt32Ty(Context), Idx2) };
Value* Val = B.CreateGEP(BasePtr, Indices, Name);
ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
Value *Val = B.CreateGEP(BasePtr, Indices, Name);
assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
return dyn_cast<GetElementPtrInst>(Val);
}
GetElementPtrInst *
ShadowStackGC::CreateGEP(LLVMContext &Context, IRBuilder<> &B, Value *BasePtr,
GetElementPtrInst *ShadowStackGC::CreateGEP(LLVMContext &Context,
IRBuilder<> &B, Value *BasePtr,
int Idx, const char *Name) {
Value *Indices[] = { ConstantInt::get(Type::getInt32Ty(Context), 0),
ConstantInt::get(Type::getInt32Ty(Context), Idx) };
Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
ConstantInt::get(Type::getInt32Ty(Context), Idx)};
Value *Val = B.CreateGEP(BasePtr, Indices, Name);
assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
@ -391,16 +385,17 @@ bool ShadowStackGC::performCustomLowering(Function &F) {
BasicBlock::iterator IP = F.getEntryBlock().begin();
IRBuilder<> AtEntry(IP->getParent(), IP);
Instruction *StackEntry = AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr,
"gc_frame");
Instruction *StackEntry =
AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
while (isa<AllocaInst>(IP)) ++IP;
while (isa<AllocaInst>(IP))
++IP;
AtEntry.SetInsertPoint(IP->getParent(), IP);
// Initialize the map pointer and load the current head of the shadow stack.
Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, StackEntry,
0,1,"gc_frame.map");
Instruction *EntryMapPtr =
CreateGEP(Context, AtEntry, StackEntry, 0, 1, "gc_frame.map");
AtEntry.CreateStore(FrameMap, EntryMapPtr);
// After all the allocas...
@ -418,14 +413,15 @@ bool ShadowStackGC::performCustomLowering(Function &F) {
// really necessary (the collector would never see the intermediate state at
// runtime), but it's nicer not to push the half-initialized entry onto the
// shadow stack.
while (isa<StoreInst>(IP)) ++IP;
while (isa<StoreInst>(IP))
++IP;
AtEntry.SetInsertPoint(IP->getParent(), IP);
// Push the entry onto the shadow stack.
Instruction *EntryNextPtr = CreateGEP(Context, AtEntry,
StackEntry,0,0,"gc_frame.next");
Instruction *NewHeadVal = CreateGEP(Context, AtEntry,
StackEntry, 0, "gc_newhead");
Instruction *EntryNextPtr =
CreateGEP(Context, AtEntry, StackEntry, 0, 0, "gc_frame.next");
Instruction *NewHeadVal =
CreateGEP(Context, AtEntry, StackEntry, 0, "gc_newhead");
AtEntry.CreateStore(CurrentHead, EntryNextPtr);
AtEntry.CreateStore(NewHeadVal, Head);
@ -434,8 +430,8 @@ bool ShadowStackGC::performCustomLowering(Function &F) {
while (IRBuilder<> *AtExit = EE.Next()) {
// Pop the entry from the shadow stack. Don't reuse CurrentHead from
// AtEntry, since that would make the value live for the entire function.
Instruction *EntryNextPtr2 = CreateGEP(Context, *AtExit, StackEntry, 0, 0,
"gc_frame.next");
Instruction *EntryNextPtr2 =
CreateGEP(Context, *AtExit, StackEntry, 0, 0, "gc_frame.next");
Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
AtExit->CreateStore(SavedHead, Head);
}

View File

@ -45,8 +45,8 @@ public:
};
}
static GCRegistry::Add<StatepointGC>
X("statepoint-example", "an example strategy for statepoint");
static GCRegistry::Add<StatepointGC> X("statepoint-example",
"an example strategy for statepoint");
namespace llvm {
void linkStatepointExampleGC() {}

View File

@ -18,5 +18,5 @@ using namespace llvm;
GCStrategy::GCStrategy()
: UseStatepoints(false), NeededSafePoints(0), CustomReadBarriers(false),
CustomWriteBarriers(false), CustomRoots(false),
InitRoots(true), UsesMetadata(false) {}
CustomWriteBarriers(false), CustomRoots(false), InitRoots(true),
UsesMetadata(false) {}