-Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
- Module &M = *F.getParent();
- Triple TargetTriple(M.getTargetTriple());
-
- unsigned Offset;
- unsigned AddressSpace;
- // Check if the target keeps the unsafe stack pointer at a fixed offset.
- if (TLI && TLI->getSafeStackPointerLocation(AddressSpace, Offset)) {
- Constant *OffsetVal =
- ConstantInt::get(Type::getInt32Ty(F.getContext()), Offset);
- return ConstantExpr::getIntToPtr(OffsetVal,
- StackPtrTy->getPointerTo(AddressSpace));
- }
-
- // Android provides a libc function that returns the stack pointer address.
- if (TargetTriple.isAndroid()) {
- Value *Fn = M.getOrInsertFunction(kUnsafeStackPtrAddrFn,
- StackPtrTy->getPointerTo(0), nullptr);
- return IRB.CreateCall(Fn);
- } else {
- // Otherwise, declare a thread-local variable with a magic name.
- auto UnsafeStackPtr =
- dyn_cast_or_null<GlobalVariable>(M.getNamedValue(kUnsafeStackPtrVar));
-
- if (!UnsafeStackPtr) {
- // The global variable is not defined yet, define it ourselves.
- // We use the initial-exec TLS model because we do not support the
- // variable living anywhere other than in the main executable.
- UnsafeStackPtr = new GlobalVariable(
- /*Module=*/M, /*Type=*/StackPtrTy,
- /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage,
- /*Initializer=*/nullptr, /*Name=*/kUnsafeStackPtrVar,
- /*InsertBefore=*/nullptr,
- /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel);
- } else {
- // The variable exists, check its type and attributes.
- if (UnsafeStackPtr->getValueType() != StackPtrTy) {
- report_fatal_error(Twine(kUnsafeStackPtrVar) + " must have void* type");
- }
-
- if (!UnsafeStackPtr->isThreadLocal()) {
- report_fatal_error(Twine(kUnsafeStackPtrVar) + " must be thread-local");
- }
- }
- return UnsafeStackPtr;
- }
-}
-