110e730a2SDan Gohman //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
210e730a2SDan Gohman //
310e730a2SDan Gohman //                     The LLVM Compiler Infrastructure
410e730a2SDan Gohman //
510e730a2SDan Gohman // This file is distributed under the University of Illinois Open Source
610e730a2SDan Gohman // License. See LICENSE.TXT for details.
710e730a2SDan Gohman //
810e730a2SDan Gohman //===----------------------------------------------------------------------===//
910e730a2SDan Gohman ///
1010e730a2SDan Gohman /// \file
1110e730a2SDan Gohman /// \brief This file defines the WebAssembly-specific subclass of TargetMachine.
1210e730a2SDan Gohman ///
1310e730a2SDan Gohman //===----------------------------------------------------------------------===//
1410e730a2SDan Gohman 
1510e730a2SDan Gohman #include "WebAssembly.h"
1610e730a2SDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
1710e730a2SDan Gohman #include "WebAssemblyTargetMachine.h"
185bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h"
1910e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h"
2010e730a2SDan Gohman #include "llvm/CodeGen/MachineFunctionPass.h"
2110e730a2SDan Gohman #include "llvm/CodeGen/Passes.h"
2210e730a2SDan Gohman #include "llvm/CodeGen/RegAllocRegistry.h"
2310e730a2SDan Gohman #include "llvm/IR/Function.h"
2410e730a2SDan Gohman #include "llvm/Support/TargetRegistry.h"
2510e730a2SDan Gohman #include "llvm/Target/TargetOptions.h"
2603855df1SJF Bastien #include "llvm/Transforms/Scalar.h"
2710e730a2SDan Gohman using namespace llvm;
2810e730a2SDan Gohman 
2910e730a2SDan Gohman #define DEBUG_TYPE "wasm"
3010e730a2SDan Gohman 
3110e730a2SDan Gohman extern "C" void LLVMInitializeWebAssemblyTarget() {
3210e730a2SDan Gohman   // Register the target.
33d82494bbSDan Gohman   RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
34d82494bbSDan Gohman   RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
3510e730a2SDan Gohman }
3610e730a2SDan Gohman 
3710e730a2SDan Gohman //===----------------------------------------------------------------------===//
3810e730a2SDan Gohman // WebAssembly Lowering public interface.
3910e730a2SDan Gohman //===----------------------------------------------------------------------===//
4010e730a2SDan Gohman 
4110e730a2SDan Gohman /// Create an WebAssembly architecture model.
4210e730a2SDan Gohman ///
4310e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine(
4410e730a2SDan Gohman     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
4510e730a2SDan Gohman     const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
4610e730a2SDan Gohman     CodeGenOpt::Level OL)
470c6f5ac5SDan Gohman     : LLVMTargetMachine(T,
480c6f5ac5SDan Gohman                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
490c6f5ac5SDan Gohman                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
5010e730a2SDan Gohman                         TT, CPU, FS, Options, RM, CM, OL),
515bf22fc8SDan Gohman       TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
52ffa143ceSDerek Schuff   // WebAssembly type-checks expressions, but a noreturn function with a return
53ffa143ceSDerek Schuff   // type that doesn't match the context will cause a check failure. So we lower
54ffa143ceSDerek Schuff   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
55ffa143ceSDerek Schuff   // 'unreachable' expression which is meant for that case.
56ffa143ceSDerek Schuff   this->Options.TrapUnreachable = true;
57ffa143ceSDerek Schuff 
5810e730a2SDan Gohman   initAsmInfo();
5910e730a2SDan Gohman 
60d85ab7fcSDan Gohman   // Note that we don't use setRequiresStructuredCFG(true). It disables
61d85ab7fcSDan Gohman   // optimizations than we're ok with, and want, such as critical edge
62d85ab7fcSDan Gohman   // splitting and tail merging.
6310e730a2SDan Gohman }
6410e730a2SDan Gohman 
6510e730a2SDan Gohman WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
6610e730a2SDan Gohman 
6710e730a2SDan Gohman const WebAssemblySubtarget *
6810e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
6910e730a2SDan Gohman   Attribute CPUAttr = F.getFnAttribute("target-cpu");
7010e730a2SDan Gohman   Attribute FSAttr = F.getFnAttribute("target-features");
7110e730a2SDan Gohman 
7210e730a2SDan Gohman   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
7310e730a2SDan Gohman                         ? CPUAttr.getValueAsString().str()
7410e730a2SDan Gohman                         : TargetCPU;
7510e730a2SDan Gohman   std::string FS = !FSAttr.hasAttribute(Attribute::None)
7610e730a2SDan Gohman                        ? FSAttr.getValueAsString().str()
7710e730a2SDan Gohman                        : TargetFS;
7810e730a2SDan Gohman 
7910e730a2SDan Gohman   auto &I = SubtargetMap[CPU + FS];
8010e730a2SDan Gohman   if (!I) {
8110e730a2SDan Gohman     // This needs to be done before we create a new subtarget since any
8210e730a2SDan Gohman     // creation will depend on the TM and the code generation flags on the
8310e730a2SDan Gohman     // function that reside in TargetOptions.
8410e730a2SDan Gohman     resetTargetOptions(F);
853adc7ce9SRafael Espindola     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
8610e730a2SDan Gohman   }
8710e730a2SDan Gohman   return I.get();
8810e730a2SDan Gohman }
8910e730a2SDan Gohman 
9010e730a2SDan Gohman namespace {
9110e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options.
9210e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig {
9310e730a2SDan Gohman public:
9410e730a2SDan Gohman   WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
9510e730a2SDan Gohman       : TargetPassConfig(TM, PM) {}
9610e730a2SDan Gohman 
9710e730a2SDan Gohman   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
9810e730a2SDan Gohman     return getTM<WebAssemblyTargetMachine>();
9910e730a2SDan Gohman   }
10010e730a2SDan Gohman 
10110e730a2SDan Gohman   FunctionPass *createTargetRegisterAllocator(bool) override;
10210e730a2SDan Gohman 
10310e730a2SDan Gohman   void addIRPasses() override;
10410e730a2SDan Gohman   bool addInstSelector() override;
10510e730a2SDan Gohman   bool addILPOpts() override;
10610e730a2SDan Gohman   void addPreRegAlloc() override;
10710e730a2SDan Gohman   void addPostRegAlloc() override;
108ad154c83SDerek Schuff   bool addGCPasses() override { return false; }
10910e730a2SDan Gohman   void addPreEmitPass() override;
11010e730a2SDan Gohman };
11110e730a2SDan Gohman } // end anonymous namespace
11210e730a2SDan Gohman 
11310e730a2SDan Gohman TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
1149099b5e6SHans Wennborg   return TargetIRAnalysis([this](const Function &F) {
11510e730a2SDan Gohman     return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
11610e730a2SDan Gohman   });
11710e730a2SDan Gohman }
11810e730a2SDan Gohman 
11910e730a2SDan Gohman TargetPassConfig *
12010e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
12110e730a2SDan Gohman   return new WebAssemblyPassConfig(this, PM);
12210e730a2SDan Gohman }
12310e730a2SDan Gohman 
12410e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
12510e730a2SDan Gohman   return nullptr; // No reg alloc
12610e730a2SDan Gohman }
12710e730a2SDan Gohman 
12810e730a2SDan Gohman //===----------------------------------------------------------------------===//
12910e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify
13010e730a2SDan Gohman // the CodeGen pass sequence.
13110e730a2SDan Gohman //===----------------------------------------------------------------------===//
13210e730a2SDan Gohman 
13310e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() {
13403855df1SJF Bastien   if (TM->Options.ThreadModel == ThreadModel::Single)
1359c54d3b4SDan Gohman     // In "single" mode, atomics get lowered to non-atomics.
13603855df1SJF Bastien     addPass(createLowerAtomicPass());
13703855df1SJF Bastien   else
13810e730a2SDan Gohman     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
13910e730a2SDan Gohman     // control specifically what gets lowered.
14003855df1SJF Bastien     addPass(createAtomicExpandPass(TM));
14110e730a2SDan Gohman 
14281719f85SDan Gohman   // Optimize "returned" function attributes.
143b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
14481719f85SDan Gohman     addPass(createWebAssemblyOptimizeReturned());
14581719f85SDan Gohman 
14610e730a2SDan Gohman   TargetPassConfig::addIRPasses();
14710e730a2SDan Gohman }
14810e730a2SDan Gohman 
14910e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() {
150b0921ca9SDan Gohman   (void)TargetPassConfig::addInstSelector();
15110e730a2SDan Gohman   addPass(
15210e730a2SDan Gohman       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
1531cf96c0cSDan Gohman   // Run the argument-move pass immediately after the ScheduleDAG scheduler
1541cf96c0cSDan Gohman   // so that we can fix up the ARGUMENT instructions before anything else
1551cf96c0cSDan Gohman   // sees them in the wrong place.
1561cf96c0cSDan Gohman   addPass(createWebAssemblyArgumentMove());
157bb372243SDan Gohman   // Set the p2align operands. This information is present during ISel, however
158bb372243SDan Gohman   // it's inconvenient to collect. Collect it now, and update the immediate
159bb372243SDan Gohman   // operands.
160bb372243SDan Gohman   addPass(createWebAssemblySetP2AlignOperands());
16110e730a2SDan Gohman   return false;
16210e730a2SDan Gohman }
16310e730a2SDan Gohman 
164b0921ca9SDan Gohman bool WebAssemblyPassConfig::addILPOpts() {
165b0921ca9SDan Gohman   (void)TargetPassConfig::addILPOpts();
166b0921ca9SDan Gohman   return true;
167b0921ca9SDan Gohman }
16810e730a2SDan Gohman 
1694ba4816bSDan Gohman void WebAssemblyPassConfig::addPreRegAlloc() {
170b0921ca9SDan Gohman   TargetPassConfig::addPreRegAlloc();
171b0921ca9SDan Gohman 
17281719f85SDan Gohman   // Prepare store instructions for register stackifying.
173b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
17481719f85SDan Gohman     addPass(createWebAssemblyStoreResults());
1754ba4816bSDan Gohman }
17610e730a2SDan Gohman 
177600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() {
1789c54d3b4SDan Gohman   // TODO: The following CodeGen passes don't currently support code containing
1799c54d3b4SDan Gohman   // virtual registers. Consider removing their restrictions and re-enabling
1809c54d3b4SDan Gohman   // them.
181ad154c83SDerek Schuff 
182ad154c83SDerek Schuff   // Has no asserts of its own, but was not written to handle virtual regs.
183ad154c83SDerek Schuff   disablePass(&ShrinkWrapID);
1849769debfSDerek Schuff   // We use our own PrologEpilogInserter which is very slightly modified to
1859769debfSDerek Schuff   // tolerate virtual registers.
186600aee98SJF Bastien   disablePass(&PrologEpilogCodeInserterID);
187ecabac62SDerek Schuff 
188ecabac62SDerek Schuff   // These functions all require the AllVRegsAllocated property.
189600aee98SJF Bastien   disablePass(&MachineCopyPropagationID);
190ecabac62SDerek Schuff   disablePass(&PostRASchedulerID);
191ecabac62SDerek Schuff   disablePass(&FuncletLayoutID);
192ecabac62SDerek Schuff   disablePass(&StackMapLivenessID);
193ecabac62SDerek Schuff   disablePass(&LiveDebugValuesID);
194*fe71ec77SSanjoy Das   disablePass(&PatchableFunctionID);
195950a13cfSDan Gohman 
19671434ff6SDerek Schuff   if (getOptLevel() != CodeGenOpt::None) {
1978887d1faSDan Gohman     // Mark registers as representing wasm's expression stack.
1988887d1faSDan Gohman     addPass(createWebAssemblyRegStackify());
1998887d1faSDan Gohman 
2004ba4816bSDan Gohman     // Run the register coloring pass to reduce the total number of registers.
2014ba4816bSDan Gohman     addPass(createWebAssemblyRegColoring());
20271434ff6SDerek Schuff   }
203b0921ca9SDan Gohman 
204b0921ca9SDan Gohman   TargetPassConfig::addPostRegAlloc();
2059769debfSDerek Schuff 
2069769debfSDerek Schuff   // Run WebAssembly's version of the PrologEpilogInserter. Target-independent
2079769debfSDerek Schuff   // PEI runs after PostRegAlloc and after ShrinkWrap. Putting it here will run
2089769debfSDerek Schuff   // PEI before ShrinkWrap but otherwise in the same position in the order.
2099769debfSDerek Schuff   addPass(createWebAssemblyPEI());
210600aee98SJF Bastien }
21110e730a2SDan Gohman 
212950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() {
213b0921ca9SDan Gohman   TargetPassConfig::addPreEmitPass();
214b0921ca9SDan Gohman 
215d7a2eea6SDan Gohman   // Eliminate multiple-entry loops.
216d7a2eea6SDan Gohman   addPass(createWebAssemblyFixIrreducibleControlFlow());
217d7a2eea6SDan Gohman 
2185941bde0SDan Gohman   // Put the CFG in structured form; insert BLOCK and LOOP markers.
219950a13cfSDan Gohman   addPass(createWebAssemblyCFGStackify());
2205941bde0SDan Gohman 
221f0b165a7SDan Gohman   // Lower br_unless into br_if.
222f0b165a7SDan Gohman   addPass(createWebAssemblyLowerBrUnless());
223f0b165a7SDan Gohman 
2245941bde0SDan Gohman   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
225cf4748f1SDan Gohman   addPass(createWebAssemblyRegNumbering());
2265941bde0SDan Gohman 
2275941bde0SDan Gohman   // Perform the very last peephole optimizations on the code.
228b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
22981719f85SDan Gohman     addPass(createWebAssemblyPeephole());
230950a13cfSDan Gohman }
231