blob: e442cb1cdedaa9bf23e90bb93540d99fd9f04179 [file] [log] [blame]
Dan Gohman10e730a2015-06-29 23:51:55 +00001//===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file defines the WebAssembly-specific subclass of TargetMachine.
12///
13//===----------------------------------------------------------------------===//
14
15#include "WebAssembly.h"
16#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17#include "WebAssemblyTargetMachine.h"
Dan Gohman5bf22fc2015-12-17 04:55:44 +000018#include "WebAssemblyTargetObjectFile.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000019#include "WebAssemblyTargetTransformInfo.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/CodeGen/RegAllocRegistry.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000023#include "llvm/CodeGen/TargetPassConfig.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000024#include "llvm/IR/Function.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000025#include "llvm/Support/TargetRegistry.h"
26#include "llvm/Target/TargetOptions.h"
JF Bastien03855df2015-07-01 23:41:25 +000027#include "llvm/Transforms/Scalar.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000028using namespace llvm;
29
30#define DEBUG_TYPE "wasm"
31
Derek Schufff41f67d2016-08-01 21:34:04 +000032// Emscripten's asm.js-style exception handling
33static cl::opt<bool> EnableEmExceptionHandling(
Derek Schuff53b9af02016-08-09 00:29:55 +000034 "enable-emscripten-cxx-exceptions",
Derek Schufff41f67d2016-08-01 21:34:04 +000035 cl::desc("WebAssembly Emscripten-style exception handling"),
36 cl::init(false));
37
Dan Gohman10e730a2015-06-29 23:51:55 +000038extern "C" void LLVMInitializeWebAssemblyTarget() {
39 // Register the target.
Dan Gohmand82494b2015-07-01 21:42:34 +000040 RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
41 RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
Derek Schufff41f67d2016-08-01 21:34:04 +000042
43 // Register exception handling pass to opt
44 initializeWebAssemblyLowerEmscriptenExceptionsPass(
45 *PassRegistry::getPassRegistry());
Dan Gohman10e730a2015-06-29 23:51:55 +000046}
47
48//===----------------------------------------------------------------------===//
49// WebAssembly Lowering public interface.
50//===----------------------------------------------------------------------===//
51
Dan Gohman41133a32016-05-19 03:00:05 +000052static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
53 if (!RM.hasValue())
54 return Reloc::PIC_;
55 return *RM;
56}
57
Dan Gohman10e730a2015-06-29 23:51:55 +000058/// Create an WebAssembly architecture model.
59///
60WebAssemblyTargetMachine::WebAssemblyTargetMachine(
61 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
Dan Gohman41133a32016-05-19 03:00:05 +000062 const TargetOptions &Options, Optional<Reloc::Model> RM,
63 CodeModel::Model CM, CodeGenOpt::Level OL)
Dan Gohman0c6f5ac2016-01-07 03:19:23 +000064 : LLVMTargetMachine(T,
65 TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
66 : "e-m:e-p:32:32-i64:64-n32:64-S128",
Dan Gohman41133a32016-05-19 03:00:05 +000067 TT, CPU, FS, Options, getEffectiveRelocModel(RM),
68 CM, OL),
Dan Gohman5bf22fc2015-12-17 04:55:44 +000069 TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
Derek Schuffffa143c2015-11-10 00:30:57 +000070 // WebAssembly type-checks expressions, but a noreturn function with a return
71 // type that doesn't match the context will cause a check failure. So we lower
72 // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
73 // 'unreachable' expression which is meant for that case.
74 this->Options.TrapUnreachable = true;
75
Dan Gohman10e730a2015-06-29 23:51:55 +000076 initAsmInfo();
77
Dan Gohmand85ab7f2016-02-18 06:32:53 +000078 // Note that we don't use setRequiresStructuredCFG(true). It disables
79 // optimizations than we're ok with, and want, such as critical edge
80 // splitting and tail merging.
Dan Gohman10e730a2015-06-29 23:51:55 +000081}
82
83WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
84
85const WebAssemblySubtarget *
86WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
87 Attribute CPUAttr = F.getFnAttribute("target-cpu");
88 Attribute FSAttr = F.getFnAttribute("target-features");
89
90 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
91 ? CPUAttr.getValueAsString().str()
92 : TargetCPU;
93 std::string FS = !FSAttr.hasAttribute(Attribute::None)
94 ? FSAttr.getValueAsString().str()
95 : TargetFS;
96
97 auto &I = SubtargetMap[CPU + FS];
98 if (!I) {
99 // This needs to be done before we create a new subtarget since any
100 // creation will depend on the TM and the code generation flags on the
101 // function that reside in TargetOptions.
102 resetTargetOptions(F);
Rafael Espindola3adc7ce2015-08-11 18:11:17 +0000103 I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
Dan Gohman10e730a2015-06-29 23:51:55 +0000104 }
105 return I.get();
106}
107
108namespace {
109/// WebAssembly Code Generator Pass Configuration Options.
110class WebAssemblyPassConfig final : public TargetPassConfig {
111public:
112 WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
113 : TargetPassConfig(TM, PM) {}
114
115 WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
116 return getTM<WebAssemblyTargetMachine>();
117 }
118
119 FunctionPass *createTargetRegisterAllocator(bool) override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000120
121 void addIRPasses() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000122 bool addInstSelector() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000123 void addPostRegAlloc() override;
Derek Schuffad154c82016-03-28 17:05:30 +0000124 bool addGCPasses() override { return false; }
Dan Gohman10e730a2015-06-29 23:51:55 +0000125 void addPreEmitPass() override;
126};
127} // end anonymous namespace
128
129TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
Hans Wennborg9099b5e62015-09-16 23:59:57 +0000130 return TargetIRAnalysis([this](const Function &F) {
Dan Gohman10e730a2015-06-29 23:51:55 +0000131 return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
132 });
133}
134
135TargetPassConfig *
136WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
137 return new WebAssemblyPassConfig(this, PM);
138}
139
140FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
141 return nullptr; // No reg alloc
142}
143
Dan Gohman10e730a2015-06-29 23:51:55 +0000144//===----------------------------------------------------------------------===//
145// The following functions are called from lib/CodeGen/Passes.cpp to modify
146// the CodeGen pass sequence.
147//===----------------------------------------------------------------------===//
148
149void WebAssemblyPassConfig::addIRPasses() {
JF Bastien03855df2015-07-01 23:41:25 +0000150 if (TM->Options.ThreadModel == ThreadModel::Single)
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000151 // In "single" mode, atomics get lowered to non-atomics.
JF Bastien03855df2015-07-01 23:41:25 +0000152 addPass(createLowerAtomicPass());
153 else
154 // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
155 // control specifically what gets lowered.
156 addPass(createAtomicExpandPass(TM));
Dan Gohman10e730a2015-06-29 23:51:55 +0000157
Dan Gohman81719f82015-11-25 16:55:01 +0000158 // Optimize "returned" function attributes.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000159 if (getOptLevel() != CodeGenOpt::None)
160 addPass(createWebAssemblyOptimizeReturned());
Dan Gohman81719f82015-11-25 16:55:01 +0000161
Derek Schufff41f67d2016-08-01 21:34:04 +0000162 // Handle exceptions.
163 if (EnableEmExceptionHandling)
164 addPass(createWebAssemblyLowerEmscriptenExceptions());
165
Dan Gohman10e730a2015-06-29 23:51:55 +0000166 TargetPassConfig::addIRPasses();
167}
168
Dan Gohman10e730a2015-06-29 23:51:55 +0000169bool WebAssemblyPassConfig::addInstSelector() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000170 (void)TargetPassConfig::addInstSelector();
Dan Gohman10e730a2015-06-29 23:51:55 +0000171 addPass(
172 createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
Dan Gohman1cf96c02015-12-09 16:23:59 +0000173 // Run the argument-move pass immediately after the ScheduleDAG scheduler
174 // so that we can fix up the ARGUMENT instructions before anything else
175 // sees them in the wrong place.
176 addPass(createWebAssemblyArgumentMove());
Dan Gohmanbb372242016-01-26 03:39:31 +0000177 // Set the p2align operands. This information is present during ISel, however
178 // it's inconvenient to collect. Collect it now, and update the immediate
179 // operands.
180 addPass(createWebAssemblySetP2AlignOperands());
Dan Gohman10e730a2015-06-29 23:51:55 +0000181 return false;
182}
183
JF Bastien600aee92015-07-31 17:53:38 +0000184void WebAssemblyPassConfig::addPostRegAlloc() {
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000185 // TODO: The following CodeGen passes don't currently support code containing
186 // virtual registers. Consider removing their restrictions and re-enabling
187 // them.
Derek Schuffad154c82016-03-28 17:05:30 +0000188
189 // Has no asserts of its own, but was not written to handle virtual regs.
190 disablePass(&ShrinkWrapID);
Derek Schuffecabac62016-03-28 22:52:20 +0000191
192 // These functions all require the AllVRegsAllocated property.
JF Bastien600aee92015-07-31 17:53:38 +0000193 disablePass(&MachineCopyPropagationID);
Derek Schuffecabac62016-03-28 22:52:20 +0000194 disablePass(&PostRASchedulerID);
195 disablePass(&FuncletLayoutID);
196 disablePass(&StackMapLivenessID);
197 disablePass(&LiveDebugValuesID);
Sanjoy Dasfe71ec72016-04-19 06:24:58 +0000198 disablePass(&PatchableFunctionID);
Dan Gohman950a13c2015-09-16 16:51:30 +0000199
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000200 TargetPassConfig::addPostRegAlloc();
JF Bastien600aee92015-07-31 17:53:38 +0000201}
Dan Gohman10e730a2015-06-29 23:51:55 +0000202
Dan Gohman950a13c2015-09-16 16:51:30 +0000203void WebAssemblyPassConfig::addPreEmitPass() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000204 TargetPassConfig::addPreEmitPass();
Dan Gohman05ac43f2015-12-17 01:39:00 +0000205
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000206 // Now that we have a prologue and epilogue and all frame indices are
207 // rewritten, eliminate SP and FP. This allows them to be stackified,
208 // colored, and numbered with the rest of the registers.
209 addPass(createWebAssemblyReplacePhysRegs());
210
211 if (getOptLevel() != CodeGenOpt::None) {
212 // LiveIntervals isn't commonly run this late. Re-establish preconditions.
213 addPass(createWebAssemblyPrepareForLiveIntervals());
214
215 // Depend on LiveIntervals and perform some optimizations on it.
216 addPass(createWebAssemblyOptimizeLiveIntervals());
217
218 // Prepare store instructions for register stackifying.
219 addPass(createWebAssemblyStoreResults());
220
221 // Mark registers as representing wasm's expression stack. This is a key
222 // code-compression technique in WebAssembly. We run this pass (and
223 // StoreResults above) very late, so that it sees as much code as possible,
224 // including code emitted by PEI and expanded by late tail duplication.
225 addPass(createWebAssemblyRegStackify());
226
227 // Run the register coloring pass to reduce the total number of registers.
228 // This runs after stackification so that it doesn't consider registers
229 // that become stackified.
230 addPass(createWebAssemblyRegColoring());
231 }
232
Dan Gohmand7a2eea2016-03-09 02:01:14 +0000233 // Eliminate multiple-entry loops.
234 addPass(createWebAssemblyFixIrreducibleControlFlow());
235
Dan Gohman5941bde2015-11-25 21:32:06 +0000236 // Put the CFG in structured form; insert BLOCK and LOOP markers.
Dan Gohman950a13c2015-09-16 16:51:30 +0000237 addPass(createWebAssemblyCFGStackify());
Dan Gohman5941bde2015-11-25 21:32:06 +0000238
Dan Gohmanf0b165a2015-12-05 03:03:35 +0000239 // Lower br_unless into br_if.
240 addPass(createWebAssemblyLowerBrUnless());
241
Dan Gohman5941bde2015-11-25 21:32:06 +0000242 // Perform the very last peephole optimizations on the code.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000243 if (getOptLevel() != CodeGenOpt::None)
244 addPass(createWebAssemblyPeephole());
Dan Gohmanb7c24002016-05-21 00:21:56 +0000245
246 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
247 addPass(createWebAssemblyRegNumbering());
Dan Gohman950a13c2015-09-16 16:51:30 +0000248}