Skip to content

Commit

Permalink
Merge retpoline support from the upstream llvm, clang and lld 5.0
Browse files Browse the repository at this point in the history
branches.  Upstream merge revisions:

  r324007: merging r323155 for llvm
  r324009: merging r323915 for llvm
  r324012: merging r323155 for clang
  r324025: merging r323155 for lld, with modifications to
           handle int3 fill
  r324026: merging r323288 for lld
  r325088: merging r324449 for llvm
  r325089: merging r324645 for llvm
  r325090: merging r325049 for llvm
  r325091: merging r325085 for llvm

Original commit messages:

r323155 (by Chandler Carruth):

  Introduce the "retpoline" x86 mitigation technique for variant #2 of
  the speculative execution vulnerabilities disclosed today,
  specifically identified by CVE-2017-5715, "Branch Target Injection",
  and is one of the two halves to Spectre.

  Summary:
  First, we need to explain the core of the vulnerability. Note that
  this is a very incomplete description, please see the Project Zero
  blog post for details:
  https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html

  The basis for branch target injection is to direct speculative
  execution of the processor to some "gadget" of executable code by
  poisoning the prediction of indirect branches with the address of
  that gadget. The gadget in turn contains an operation that provides a
  side channel for reading data. Most commonly, this will look like a
  load of secret data followed by a branch on the loaded value and then
  a load of some predictable cache line. The attacker then uses timing
  of the processors cache to determine which direction the branch took
  *in the speculative execution*, and in turn what one bit of the
  loaded value was. Due to the nature of these timing side channels and
  the branch predictor on Intel processors, this allows an attacker to
  leak data only accessible to a privileged domain (like the kernel)
  back into an unprivileged domain.

  The goal is simple: avoid generating code which contains an indirect
  branch that could have its prediction poisoned by an attacker. In
  many cases, the compiler can simply use directed conditional branches
  and a small search tree. LLVM already has support for lowering
  switches in this way and the first step of this patch is to disable
  jump-table lowering of switches and introduce a pass to rewrite
  explicit indirectbr sequences into a switch over integers.

  However, there is no fully general alternative to indirect calls. We
  introduce a new construct we call a "retpoline" to implement indirect
  calls in a non-speculatable way. It can be thought of loosely as a
  trampoline for indirect calls which uses the RET instruction on x86.
  Further, we arrange for a specific call->ret sequence which ensures
  the processor predicts the return to go to a controlled, known
  location. The retpoline then "smashes" the return address pushed onto
  the stack by the call with the desired target of the original
  indirect call. The result is a predicted return to the next
  instruction after a call (which can be used to trap speculative
  execution within an infinite loop) and an actual indirect branch to
  an arbitrary address.

  On 64-bit x86 ABIs, this is especially easily done in the compiler by
  using a guaranteed scratch register to pass the target into this
  device.  For 32-bit ABIs there isn't a guaranteed scratch register
  and so several different retpoline variants are introduced to use a
  scratch register if one is available in the calling convention and to
  otherwise use direct stack push/pop sequences to pass the target
  address.

  This "retpoline" mitigation is fully described in the following blog
  post: https://support.google.com/faqs/answer/7625886

  We also support a target feature that disables emission of the
  retpoline thunk by the compiler to allow for custom thunks if users
  want them.  These are particularly useful in environments like
  kernels that routinely do hot-patching on boot and want to hot-patch
  their thunk to different code sequences. They can write this custom
  thunk and use `-mretpoline-external-thunk` *in addition* to
  `-mretpoline`. In this case, on x86-64 thu thunk names must be:
  ```
    __llvm_external_retpoline_r11
  ```
  or on 32-bit:
  ```
    __llvm_external_retpoline_eax
    __llvm_external_retpoline_ecx
    __llvm_external_retpoline_edx
    __llvm_external_retpoline_push
  ```

  And the target of the retpoline is passed in the named register, or
  in the case of the `push` suffix on the top of the stack via a
  `pushl` instruction.

  There is one other important source of indirect branches in x86 ELF
  binaries: the PLT. These patches also include support for LLD to
  generate PLT entries that perform a retpoline-style indirection.

  The only other indirect branches remaining that we are aware of are
  from precompiled runtimes (such as crt0.o and similar). The ones we
  have found are not really attackable, and so we have not focused on
  them here, but eventually these runtimes should also be replicated
  for retpoline-ed configurations for completeness.

  For kernels or other freestanding or fully static executables, the
  compiler switch `-mretpoline` is sufficient to fully mitigate this
  particular attack. For dynamic executables, you must compile *all*
  libraries with `-mretpoline` and additionally link the dynamic
  executable and all shared libraries with LLD and pass `-z
  retpolineplt` (or use similar functionality from some other linker).
  We strongly recommend also using `-z now` as non-lazy binding allows
  the retpoline-mitigated PLT to be substantially smaller.

  When manually apply similar transformations to `-mretpoline` to the
  Linux kernel we observed very small performance hits to applications
  running typical workloads, and relatively minor hits (approximately
  2%) even for extremely syscall-heavy applications. This is largely
  due to the small number of indirect branches that occur in
  performance sensitive paths of the kernel.

  When using these patches on statically linked applications,
  especially C++ applications, you should expect to see a much more
  dramatic performance hit. For microbenchmarks that are switch,
  indirect-, or virtual-call heavy we have seen overheads ranging from
  10% to 50%.

  However, real-world workloads exhibit substantially lower performance
  impact. Notably, techniques such as PGO and ThinLTO dramatically
  reduce the impact of hot indirect calls (by speculatively promoting
  them to direct calls) and allow optimized search trees to be used to
  lower switches. If you need to deploy these techniques in C++
  applications, we *strongly* recommend that you ensure all hot call
  targets are statically linked (avoiding PLT indirection) and use both
  PGO and ThinLTO. Well tuned servers using all of these techniques saw
  5% - 10% overhead from the use of retpoline.

  We will add detailed documentation covering these components in
  subsequent patches, but wanted to make the core functionality
  available as soon as possible. Happy for more code review, but we'd
  really like to get these patches landed and backported ASAP for
  obvious reasons. We're planning to backport this to both 6.0 and 5.0
  release streams and get a 5.0 release with just this cherry picked
  ASAP for distros and vendors.

  This patch is the work of a number of people over the past month:
  Eric, Reid, Rui, and myself. I'm mailing it out as a single commit
  due to the time sensitive nature of landing this and the need to
  backport it. Huge thanks to everyone who helped out here, and
  everyone at Intel who helped out in discussions about how to craft
  this. Also, credit goes to Paul Turner (at Google, but not an LLVM
  contributor) for much of the underlying retpoline design.

  Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer

  Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini,
  hiraditya, llvm-commits

  Differential Revision: https://reviews.llvm.org/D41723

r323915 (by Chandler Carruth):

  [x86] Make the retpoline thunk insertion a machine function pass.

  Summary:
  This removes the need for a machine module pass using some deeply
  questionable hacks. This should address PR36123 which is a case where
  in full LTO the memory usage of a machine module pass actually ended
  up being significant.

  We should revert this on trunk as soon as we understand and fix the
  memory usage issue, but we should include this in any backports of
  retpolines themselves.

  Reviewers: echristo, MatzeB

  Subscribers: sanjoy, mcrosier, mehdi_amini, hiraditya, llvm-commits

  Differential Revision: https://reviews.llvm.org/D42726

r323288 (by Rui Ueyama):

  Fix retpoline PLT header size for i386.

  Differential Revision: https://reviews.llvm.org/D42397

r324449 (by Chandler Carruth):

  [x86/retpoline] Make the external thunk names exactly match the names
  that happened to end up in GCC.

  This is really unfortunate, as the names don't have much rhyme or
  reason to them. Originally in the discussions it seemed fine to rely
  on aliases to map different names to whatever external thunk code
  developers wished to use but there are practical problems with that
  in the kernel it turns out. And since we're discovering this
  practical problems late and since GCC has already shipped a release
  with one set of names, we are forced, yet again, to blindly match
  what is there.

  Somewhat rushing this patch out for the Linux kernel folks to test
  and so we can get it patched into our releases.

  Differential Revision: https://reviews.llvm.org/D42998

r324645 (by David Woodhouse):

  [X86] Support 'V' register operand modifier

  This allows the register name to be printed without the leading '%'.
  This can be used for emitting calls to the retpoline thunks from
  inline asm.

r325049 (by Reid Kleckner):

  [X86] Use EDI for retpoline when no scratch regs are left

  Summary:
  Instead of solving the hard problem of how to pass the callee to the
  indirect jump thunk without a register, just use a CSR. At a call
  boundary, there's nothing stopping us from using a CSR to hold the
  callee as long as we save and restore it in the prologue.

  Also, add tests for this mregparm=3 case. I wrote execution tests for
  __llvm_retpoline_push, but they never got committed as lit tests,
  either because I never rewrote them or because they got lost in merge
  conflicts.

  Reviewers: chandlerc, dwmw2

  Subscribers: javed.absar, kristof.beyls, hiraditya, llvm-commits

  Differential Revision: https://reviews.llvm.org/D43214

r325085 (by Reid Kleckner):

  [X86] Remove dead code from retpoline thunk generation

Differential Revision: https://reviews.freebsd.org/D14720
  • Loading branch information
DimitryAndric committed Mar 19, 2018
1 parent 31fc150 commit 4479011
Show file tree
Hide file tree
Showing 36 changed files with 1,080 additions and 25 deletions.
3 changes: 3 additions & 0 deletions contrib/llvm/include/llvm/CodeGen/Passes.h
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,9 @@ namespace llvm {
/// shuffles.
FunctionPass *createExpandReductionsPass();

// This pass expands indirectbr instructions.
FunctionPass *createIndirectBrExpandPass();

} // End llvm namespace

#endif
7 changes: 7 additions & 0 deletions contrib/llvm/include/llvm/CodeGen/TargetPassConfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,13 @@ class TargetPassConfig : public ImmutablePass {
/// immediately before machine code is emitted.
virtual void addPreEmitPass() { }

/// Targets may add passes immediately before machine code is emitted in this
/// callback. This is called even later than `addPreEmitPass`.
// FIXME: Rename `addPreEmitPass` to something more sensible given its actual
// position and remove the `2` suffix here as this callback is what
// `addPreEmitPass` *should* be but in reality isn't.
virtual void addPreEmitPass2() {}

/// Utilities for targets to add passes to the pass manager.
///

Expand Down
1 change: 1 addition & 0 deletions contrib/llvm/include/llvm/InitializePasses.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ void initializeIVUsersWrapperPassPass(PassRegistry&);
void initializeIfConverterPass(PassRegistry&);
void initializeImplicitNullChecksPass(PassRegistry&);
void initializeIndVarSimplifyLegacyPassPass(PassRegistry&);
void initializeIndirectBrExpandPassPass(PassRegistry&);
void initializeInductiveRangeCheckEliminationPass(PassRegistry&);
void initializeInferAddressSpacesPass(PassRegistry&);
void initializeInferFunctionAttrsLegacyPassPass(PassRegistry&);
Expand Down
2 changes: 1 addition & 1 deletion contrib/llvm/include/llvm/Target/TargetLowering.h
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,7 @@ class TargetLoweringBase {
}

/// Return true if lowering to a jump table is allowed.
bool areJTsAllowed(const Function *Fn) const {
virtual bool areJTsAllowed(const Function *Fn) const {
if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
return false;

Expand Down
3 changes: 3 additions & 0 deletions contrib/llvm/include/llvm/Target/TargetSubtargetInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ class TargetSubtargetInfo : public MCSubtargetInfo {
/// \brief True if the subtarget should run the atomic expansion pass.
virtual bool enableAtomicExpand() const;

/// True if the subtarget should run the indirectbr expansion pass.
virtual bool enableIndirectBrExpand() const;

/// \brief Override generic scheduling policy within a region.
///
/// This is a convenient way for targets that don't provide any custom
Expand Down
1 change: 1 addition & 0 deletions contrib/llvm/lib/CodeGen/CodeGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ void llvm::initializeCodeGen(PassRegistry &Registry) {
initializeGCModuleInfoPass(Registry);
initializeIfConverterPass(Registry);
initializeImplicitNullChecksPass(Registry);
initializeIndirectBrExpandPassPass(Registry);
initializeInterleavedAccessPass(Registry);
initializeLiveDebugValuesPass(Registry);
initializeLiveDebugVariablesPass(Registry);
Expand Down
221 changes: 221 additions & 0 deletions contrib/llvm/lib/CodeGen/IndirectBrExpandPass.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
//===- IndirectBrExpandPass.cpp - Expand indirectbr to switch -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// Implements an expansion pass to turn `indirectbr` instructions in the IR
/// into `switch` instructions. This works by enumerating the basic blocks in
/// a dense range of integers, replacing each `blockaddr` constant with the
/// corresponding integer constant, and then building a switch that maps from
/// the integers to the actual blocks. All of the indirectbr instructions in the
/// function are redirected to this common switch.
///
/// While this is generically useful if a target is unable to codegen
/// `indirectbr` natively, it is primarily useful when there is some desire to
/// get the builtin non-jump-table lowering of a switch even when the input
/// source contained an explicit indirect branch construct.
///
/// Note that it doesn't make any sense to enable this pass unless a target also
/// disables jump-table lowering of switches. Doing that is likely to pessimize
/// the code.
///
//===----------------------------------------------------------------------===//

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"

using namespace llvm;

#define DEBUG_TYPE "indirectbr-expand"

namespace {

class IndirectBrExpandPass : public FunctionPass {
const TargetLowering *TLI = nullptr;

public:
static char ID; // Pass identification, replacement for typeid

IndirectBrExpandPass() : FunctionPass(ID) {
initializeIndirectBrExpandPassPass(*PassRegistry::getPassRegistry());
}

bool runOnFunction(Function &F) override;
};

} // end anonymous namespace

char IndirectBrExpandPass::ID = 0;

INITIALIZE_PASS(IndirectBrExpandPass, DEBUG_TYPE,
"Expand indirectbr instructions", false, false)

FunctionPass *llvm::createIndirectBrExpandPass() {
return new IndirectBrExpandPass();
}

bool IndirectBrExpandPass::runOnFunction(Function &F) {
auto &DL = F.getParent()->getDataLayout();
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
if (!TPC)
return false;

auto &TM = TPC->getTM<TargetMachine>();
auto &STI = *TM.getSubtargetImpl(F);
if (!STI.enableIndirectBrExpand())
return false;
TLI = STI.getTargetLowering();

SmallVector<IndirectBrInst *, 1> IndirectBrs;

// Set of all potential successors for indirectbr instructions.
SmallPtrSet<BasicBlock *, 4> IndirectBrSuccs;

// Build a list of indirectbrs that we want to rewrite.
for (BasicBlock &BB : F)
if (auto *IBr = dyn_cast<IndirectBrInst>(BB.getTerminator())) {
// Handle the degenerate case of no successors by replacing the indirectbr
// with unreachable as there is no successor available.
if (IBr->getNumSuccessors() == 0) {
(void)new UnreachableInst(F.getContext(), IBr);
IBr->eraseFromParent();
continue;
}

IndirectBrs.push_back(IBr);
for (BasicBlock *SuccBB : IBr->successors())
IndirectBrSuccs.insert(SuccBB);
}

if (IndirectBrs.empty())
return false;

// If we need to replace any indirectbrs we need to establish integer
// constants that will correspond to each of the basic blocks in the function
// whose address escapes. We do that here and rewrite all the blockaddress
// constants to just be those integer constants cast to a pointer type.
SmallVector<BasicBlock *, 4> BBs;

for (BasicBlock &BB : F) {
// Skip blocks that aren't successors to an indirectbr we're going to
// rewrite.
if (!IndirectBrSuccs.count(&BB))
continue;

auto IsBlockAddressUse = [&](const Use &U) {
return isa<BlockAddress>(U.getUser());
};
auto BlockAddressUseIt = llvm::find_if(BB.uses(), IsBlockAddressUse);
if (BlockAddressUseIt == BB.use_end())
continue;

assert(std::find_if(std::next(BlockAddressUseIt), BB.use_end(),
IsBlockAddressUse) == BB.use_end() &&
"There should only ever be a single blockaddress use because it is "
"a constant and should be uniqued.");

auto *BA = cast<BlockAddress>(BlockAddressUseIt->getUser());

// Skip if the constant was formed but ended up not being used (due to DCE
// or whatever).
if (!BA->isConstantUsed())
continue;

// Compute the index we want to use for this basic block. We can't use zero
// because null can be compared with block addresses.
int BBIndex = BBs.size() + 1;
BBs.push_back(&BB);

auto *ITy = cast<IntegerType>(DL.getIntPtrType(BA->getType()));
ConstantInt *BBIndexC = ConstantInt::get(ITy, BBIndex);

// Now rewrite the blockaddress to an integer constant based on the index.
// FIXME: We could potentially preserve the uses as arguments to inline asm.
// This would allow some uses such as diagnostic information in crashes to
// have higher quality even when this transform is enabled, but would break
// users that round-trip blockaddresses through inline assembly and then
// back into an indirectbr.
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(BBIndexC, BA->getType()));
}

if (BBs.empty()) {
// There are no blocks whose address is taken, so any indirectbr instruction
// cannot get a valid input and we can replace all of them with unreachable.
for (auto *IBr : IndirectBrs) {
(void)new UnreachableInst(F.getContext(), IBr);
IBr->eraseFromParent();
}
return true;
}

BasicBlock *SwitchBB;
Value *SwitchValue;

// Compute a common integer type across all the indirectbr instructions.
IntegerType *CommonITy = nullptr;
for (auto *IBr : IndirectBrs) {
auto *ITy =
cast<IntegerType>(DL.getIntPtrType(IBr->getAddress()->getType()));
if (!CommonITy || ITy->getBitWidth() > CommonITy->getBitWidth())
CommonITy = ITy;
}

auto GetSwitchValue = [DL, CommonITy](IndirectBrInst *IBr) {
return CastInst::CreatePointerCast(
IBr->getAddress(), CommonITy,
Twine(IBr->getAddress()->getName()) + ".switch_cast", IBr);
};

if (IndirectBrs.size() == 1) {
// If we only have one indirectbr, we can just directly replace it within
// its block.
SwitchBB = IndirectBrs[0]->getParent();
SwitchValue = GetSwitchValue(IndirectBrs[0]);
IndirectBrs[0]->eraseFromParent();
} else {
// Otherwise we need to create a new block to hold the switch across BBs,
// jump to that block instead of each indirectbr, and phi together the
// values for the switch.
SwitchBB = BasicBlock::Create(F.getContext(), "switch_bb", &F);
auto *SwitchPN = PHINode::Create(CommonITy, IndirectBrs.size(),
"switch_value_phi", SwitchBB);
SwitchValue = SwitchPN;

// Now replace the indirectbr instructions with direct branches to the
// switch block and fill out the PHI operands.
for (auto *IBr : IndirectBrs) {
SwitchPN->addIncoming(GetSwitchValue(IBr), IBr->getParent());
BranchInst::Create(SwitchBB, IBr);
IBr->eraseFromParent();
}
}

// Now build the switch in the block. The block will have no terminator
// already.
auto *SI = SwitchInst::Create(SwitchValue, BBs[0], BBs.size(), SwitchBB);

// Add a case for each block.
for (int i : llvm::seq<int>(1, BBs.size()))
SI->addCase(ConstantInt::get(CommonITy, i + 1), BBs[i]);

return true;
}
3 changes: 3 additions & 0 deletions contrib/llvm/lib/CodeGen/TargetPassConfig.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,9 @@ void TargetPassConfig::addMachinePasses() {
if (EnableMachineOutliner)
PM->add(createMachineOutlinerPass());

// Add passes that directly emit MI after all other MI passes.
addPreEmitPass2();

AddingMachinePasses = false;
}

Expand Down
4 changes: 4 additions & 0 deletions contrib/llvm/lib/CodeGen/TargetSubtargetInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ bool TargetSubtargetInfo::enableAtomicExpand() const {
return true;
}

bool TargetSubtargetInfo::enableIndirectBrExpand() const {
return false;
}

bool TargetSubtargetInfo::enableMachineScheduler() const {
return false;
}
Expand Down
4 changes: 4 additions & 0 deletions contrib/llvm/lib/Target/X86/X86.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ namespace llvm {
class FunctionPass;
class ImmutablePass;
class InstructionSelector;
class ModulePass;
class PassRegistry;
class X86RegisterBankInfo;
class X86Subtarget;
Expand Down Expand Up @@ -98,6 +99,9 @@ void initializeFixupBWInstPassPass(PassRegistry &);
/// encoding when possible in order to reduce code size.
FunctionPass *createX86EvexToVexInsts();

/// This pass creates the thunks for the retpoline feature.
FunctionPass *createX86RetpolineThunksPass();

InstructionSelector *createX86InstructionSelector(const X86TargetMachine &TM,
X86Subtarget &,
X86RegisterBankInfo &);
Expand Down
21 changes: 21 additions & 0 deletions contrib/llvm/lib/Target/X86/X86.td
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,27 @@ def FeatureERMSB
"ermsb", "HasERMSB", "true",
"REP MOVS/STOS are fast">;

// Enable mitigation of some aspects of speculative execution related
// vulnerabilities by removing speculatable indirect branches. This disables
// jump-table formation, rewrites explicit `indirectbr` instructions into
// `switch` instructions, and uses a special construct called a "retpoline" to
// prevent speculation of the remaining indirect branches (indirect calls and
// tail calls).
def FeatureRetpoline
: SubtargetFeature<"retpoline", "UseRetpoline", "true",
"Remove speculation of indirect branches from the "
"generated code, either by avoiding them entirely or "
"lowering them with a speculation blocking construct.">;

// Rely on external thunks for the emitted retpoline calls. This allows users
// to provide their own custom thunk definitions in highly specialized
// environments such as a kernel that does boot-time hot patching.
def FeatureRetpolineExternalThunk
: SubtargetFeature<
"retpoline-external-thunk", "UseRetpolineExternalThunk", "true",
"Enable retpoline, but with an externally provided thunk.",
[FeatureRetpoline]>;

//===----------------------------------------------------------------------===//
// X86 processors supported.
//===----------------------------------------------------------------------===//
Expand Down
11 changes: 10 additions & 1 deletion contrib/llvm/lib/Target/X86/X86AsmPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,8 @@ static void printIntelMemReference(X86AsmPrinter &P, const MachineInstr *MI,
static bool printAsmMRegister(X86AsmPrinter &P, const MachineOperand &MO,
char Mode, raw_ostream &O) {
unsigned Reg = MO.getReg();
bool EmitPercent = true;

switch (Mode) {
default: return true; // Unknown mode.
case 'b': // Print QImode register
Expand All @@ -358,14 +360,20 @@ static bool printAsmMRegister(X86AsmPrinter &P, const MachineOperand &MO,
case 'k': // Print SImode register
Reg = getX86SubSuperRegister(Reg, 32);
break;
case 'V':
EmitPercent = false;
LLVM_FALLTHROUGH;
case 'q':
// Print 64-bit register names if 64-bit integer registers are available.
// Otherwise, print 32-bit register names.
Reg = getX86SubSuperRegister(Reg, P.getSubtarget().is64Bit() ? 64 : 32);
break;
}

O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
if (EmitPercent)
O << '%';

O << X86ATTInstPrinter::getRegisterName(Reg);
return false;
}

Expand Down Expand Up @@ -438,6 +446,7 @@ bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
case 'w': // Print HImode register
case 'k': // Print SImode register
case 'q': // Print DImode register
case 'V': // Print native register without '%'
if (MO.isReg())
return printAsmMRegister(*this, MO, ExtraCode[0], O);
printOperand(*this, MI, OpNo, O);
Expand Down
1 change: 1 addition & 0 deletions contrib/llvm/lib/Target/X86/X86AsmPrinter.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class LLVM_LIBRARY_VISIBILITY X86AsmPrinter : public AsmPrinter {
StackMaps SM;
FaultMaps FM;
std::unique_ptr<MCCodeEmitter> CodeEmitter;
bool NeedsRetpoline = false;

// This utility class tracks the length of a stackmap instruction's 'shadow'.
// It is used by the X86AsmPrinter to ensure that the stackmap shadow
Expand Down
Loading

0 comments on commit 4479011

Please sign in to comment.