1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the X86 specific subclass of TargetMachine.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "X86TargetMachine.h"
14 #include "MCTargetDesc/X86MCTargetDesc.h"
15 #include "TargetInfo/X86TargetInfo.h"
16 #include "X86.h"
17 #include "X86CallLowering.h"
18 #include "X86LegalizerInfo.h"
19 #include "X86MacroFusion.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetObjectFile.h"
22 #include "X86TargetTransformInfo.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/ExecutionDomainFix.h"
30 #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
31 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
32 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
33 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
34 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
35 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
36 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
37 #include "llvm/CodeGen/MachineScheduler.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/CodeGen/TargetPassConfig.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/TargetRegistry.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Transforms/CFGuard.h"
53 #include <memory>
54 #include <string>
55
56 using namespace llvm;
57
58 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
59 cl::desc("Enable the machine combiner pass"),
60 cl::init(true), cl::Hidden);
61
62 static cl::opt<bool>
63 EnableTileRAPass("x86-tile-ra",
64 cl::desc("Enable the tile register allocation pass"),
65 cl::init(true), cl::Hidden);
66
LLVMInitializeX86Target()67 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86Target() {
68 // Register the target.
69 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
70 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
71
72 PassRegistry &PR = *PassRegistry::getPassRegistry();
73 initializeX86LowerAMXIntrinsicsLegacyPassPass(PR);
74 initializeX86LowerAMXTypeLegacyPassPass(PR);
75 initializeX86PreAMXConfigPassPass(PR);
76 initializeX86PreTileConfigPass(PR);
77 initializeGlobalISel(PR);
78 initializeWinEHStatePassPass(PR);
79 initializeFixupBWInstPassPass(PR);
80 initializeEvexToVexInstPassPass(PR);
81 initializeFixupLEAPassPass(PR);
82 initializeFPSPass(PR);
83 initializeX86FixupSetCCPassPass(PR);
84 initializeX86CallFrameOptimizationPass(PR);
85 initializeX86CmovConverterPassPass(PR);
86 initializeX86TileConfigPass(PR);
87 initializeX86FastPreTileConfigPass(PR);
88 initializeX86FastTileConfigPass(PR);
89 initializeX86LowerTileCopyPass(PR);
90 initializeX86ExpandPseudoPass(PR);
91 initializeX86ExecutionDomainFixPass(PR);
92 initializeX86DomainReassignmentPass(PR);
93 initializeX86AvoidSFBPassPass(PR);
94 initializeX86AvoidTrailingCallPassPass(PR);
95 initializeX86SpeculativeLoadHardeningPassPass(PR);
96 initializeX86SpeculativeExecutionSideEffectSuppressionPass(PR);
97 initializeX86FlagsCopyLoweringPassPass(PR);
98 initializeX86LoadValueInjectionLoadHardeningPassPass(PR);
99 initializeX86LoadValueInjectionRetHardeningPassPass(PR);
100 initializeX86OptimizeLEAPassPass(PR);
101 initializeX86PartialReductionPass(PR);
102 initializePseudoProbeInserterPass(PR);
103 initializeX86ReturnThunksPass(PR);
104 }
105
createTLOF(const Triple & TT)106 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
107 if (TT.isOSBinFormatMachO()) {
108 if (TT.getArch() == Triple::x86_64)
109 return std::make_unique<X86_64MachoTargetObjectFile>();
110 return std::make_unique<TargetLoweringObjectFileMachO>();
111 }
112
113 if (TT.isOSBinFormatCOFF())
114 return std::make_unique<TargetLoweringObjectFileCOFF>();
115 return std::make_unique<X86ELFTargetObjectFile>();
116 }
117
computeDataLayout(const Triple & TT)118 static std::string computeDataLayout(const Triple &TT) {
119 // X86 is little endian
120 std::string Ret = "e";
121
122 Ret += DataLayout::getManglingComponent(TT);
123 // X86 and x32 have 32 bit pointers.
124 if (!TT.isArch64Bit() || TT.isX32() || TT.isOSNaCl())
125 Ret += "-p:32:32";
126
127 // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
128 Ret += "-p270:32:32-p271:32:32-p272:64:64";
129
130 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
131 if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
132 Ret += "-i64:64";
133 else if (TT.isOSIAMCU())
134 Ret += "-i64:32-f64:32";
135 else
136 Ret += "-f64:32:64";
137
138 // Some ABIs align long double to 128 bits, others to 32.
139 if (TT.isOSNaCl() || TT.isOSIAMCU())
140 ; // No f80
141 else if (TT.isArch64Bit() || TT.isOSDarwin() || TT.isWindowsMSVCEnvironment())
142 Ret += "-f80:128";
143 else
144 Ret += "-f80:32";
145
146 if (TT.isOSIAMCU())
147 Ret += "-f128:32";
148
149 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
150 if (TT.isArch64Bit())
151 Ret += "-n8:16:32:64";
152 else
153 Ret += "-n8:16:32";
154
155 // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
156 if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
157 Ret += "-a:0:32-S32";
158 else
159 Ret += "-S128";
160
161 return Ret;
162 }
163
getEffectiveRelocModel(const Triple & TT,bool JIT,Optional<Reloc::Model> RM)164 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
165 bool JIT,
166 Optional<Reloc::Model> RM) {
167 bool is64Bit = TT.getArch() == Triple::x86_64;
168 if (!RM) {
169 // JIT codegen should use static relocations by default, since it's
170 // typically executed in process and not relocatable.
171 if (JIT)
172 return Reloc::Static;
173
174 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
175 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
176 // use static relocation model by default.
177 if (TT.isOSDarwin()) {
178 if (is64Bit)
179 return Reloc::PIC_;
180 return Reloc::DynamicNoPIC;
181 }
182 if (TT.isOSWindows() && is64Bit)
183 return Reloc::PIC_;
184 return Reloc::Static;
185 }
186
187 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
188 // is defined as a model for code which may be used in static or dynamic
189 // executables but not necessarily a shared library. On X86-32 we just
190 // compile in -static mode, in x86-64 we use PIC.
191 if (*RM == Reloc::DynamicNoPIC) {
192 if (is64Bit)
193 return Reloc::PIC_;
194 if (!TT.isOSDarwin())
195 return Reloc::Static;
196 }
197
198 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
199 // the Mach-O file format doesn't support it.
200 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
201 return Reloc::PIC_;
202
203 return *RM;
204 }
205
getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,bool JIT,bool Is64Bit)206 static CodeModel::Model getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,
207 bool JIT, bool Is64Bit) {
208 if (CM) {
209 if (*CM == CodeModel::Tiny)
210 report_fatal_error("Target does not support the tiny CodeModel", false);
211 return *CM;
212 }
213 if (JIT)
214 return Is64Bit ? CodeModel::Large : CodeModel::Small;
215 return CodeModel::Small;
216 }
217
218 /// Create an X86 target.
219 ///
X86TargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)220 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
221 StringRef CPU, StringRef FS,
222 const TargetOptions &Options,
223 Optional<Reloc::Model> RM,
224 Optional<CodeModel::Model> CM,
225 CodeGenOpt::Level OL, bool JIT)
226 : LLVMTargetMachine(
227 T, computeDataLayout(TT), TT, CPU, FS, Options,
228 getEffectiveRelocModel(TT, JIT, RM),
229 getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64),
230 OL),
231 TLOF(createTLOF(getTargetTriple())), IsJIT(JIT) {
232 // On PS4/PS5, the "return address" of a 'noreturn' call must still be within
233 // the calling function, and TrapUnreachable is an easy way to get that.
234 if (TT.isPS() || TT.isOSBinFormatMachO()) {
235 this->Options.TrapUnreachable = true;
236 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
237 }
238
239 setMachineOutliner(true);
240
241 // x86 supports the debug entry values.
242 setSupportsDebugEntryValues(true);
243
244 initAsmInfo();
245 }
246
247 X86TargetMachine::~X86TargetMachine() = default;
248
249 const X86Subtarget *
getSubtargetImpl(const Function & F) const250 X86TargetMachine::getSubtargetImpl(const Function &F) const {
251 Attribute CPUAttr = F.getFnAttribute("target-cpu");
252 Attribute TuneAttr = F.getFnAttribute("tune-cpu");
253 Attribute FSAttr = F.getFnAttribute("target-features");
254
255 StringRef CPU =
256 CPUAttr.isValid() ? CPUAttr.getValueAsString() : (StringRef)TargetCPU;
257 // "x86-64" is a default target setting for many front ends. In these cases,
258 // they actually request for "generic" tuning unless the "tune-cpu" was
259 // specified.
260 StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString()
261 : CPU == "x86-64" ? "generic"
262 : (StringRef)CPU;
263 StringRef FS =
264 FSAttr.isValid() ? FSAttr.getValueAsString() : (StringRef)TargetFS;
265
266 SmallString<512> Key;
267 // The additions here are ordered so that the definitely short strings are
268 // added first so we won't exceed the small size. We append the
269 // much longer FS string at the end so that we only heap allocate at most
270 // one time.
271
272 // Extract prefer-vector-width attribute.
273 unsigned PreferVectorWidthOverride = 0;
274 Attribute PreferVecWidthAttr = F.getFnAttribute("prefer-vector-width");
275 if (PreferVecWidthAttr.isValid()) {
276 StringRef Val = PreferVecWidthAttr.getValueAsString();
277 unsigned Width;
278 if (!Val.getAsInteger(0, Width)) {
279 Key += 'p';
280 Key += Val;
281 PreferVectorWidthOverride = Width;
282 }
283 }
284
285 // Extract min-legal-vector-width attribute.
286 unsigned RequiredVectorWidth = UINT32_MAX;
287 Attribute MinLegalVecWidthAttr = F.getFnAttribute("min-legal-vector-width");
288 if (MinLegalVecWidthAttr.isValid()) {
289 StringRef Val = MinLegalVecWidthAttr.getValueAsString();
290 unsigned Width;
291 if (!Val.getAsInteger(0, Width)) {
292 Key += 'm';
293 Key += Val;
294 RequiredVectorWidth = Width;
295 }
296 }
297
298 // Add CPU to the Key.
299 Key += CPU;
300
301 // Add tune CPU to the Key.
302 Key += TuneCPU;
303
304 // Keep track of the start of the feature portion of the string.
305 unsigned FSStart = Key.size();
306
307 // FIXME: This is related to the code below to reset the target options,
308 // we need to know whether or not the soft float flag is set on the
309 // function before we can generate a subtarget. We also need to use
310 // it as a key for the subtarget since that can be the only difference
311 // between two functions.
312 bool SoftFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
313 // If the soft float attribute is set on the function turn on the soft float
314 // subtarget feature.
315 if (SoftFloat)
316 Key += FS.empty() ? "+soft-float" : "+soft-float,";
317
318 Key += FS;
319
320 // We may have added +soft-float to the features so move the StringRef to
321 // point to the full string in the Key.
322 FS = Key.substr(FSStart);
323
324 auto &I = SubtargetMap[Key];
325 if (!I) {
326 // This needs to be done before we create a new subtarget since any
327 // creation will depend on the TM and the code generation flags on the
328 // function that reside in TargetOptions.
329 resetTargetOptions(F);
330 I = std::make_unique<X86Subtarget>(
331 TargetTriple, CPU, TuneCPU, FS, *this,
332 MaybeAlign(F.getParent()->getOverrideStackAlignment()),
333 PreferVectorWidthOverride, RequiredVectorWidth);
334 }
335 return I.get();
336 }
337
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS) const338 bool X86TargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
339 unsigned DestAS) const {
340 assert(SrcAS != DestAS && "Expected different address spaces!");
341 if (getPointerSize(SrcAS) != getPointerSize(DestAS))
342 return false;
343 return SrcAS < 256 && DestAS < 256;
344 }
345
346 //===----------------------------------------------------------------------===//
347 // X86 TTI query.
348 //===----------------------------------------------------------------------===//
349
350 TargetTransformInfo
getTargetTransformInfo(const Function & F) const351 X86TargetMachine::getTargetTransformInfo(const Function &F) const {
352 return TargetTransformInfo(X86TTIImpl(this, F));
353 }
354
355 //===----------------------------------------------------------------------===//
356 // Pass Pipeline Configuration
357 //===----------------------------------------------------------------------===//
358
359 namespace {
360
361 /// X86 Code Generator Pass Configuration Options.
362 class X86PassConfig : public TargetPassConfig {
363 public:
X86PassConfig(X86TargetMachine & TM,PassManagerBase & PM)364 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
365 : TargetPassConfig(TM, PM) {}
366
getX86TargetMachine() const367 X86TargetMachine &getX86TargetMachine() const {
368 return getTM<X86TargetMachine>();
369 }
370
371 ScheduleDAGInstrs *
createMachineScheduler(MachineSchedContext * C) const372 createMachineScheduler(MachineSchedContext *C) const override {
373 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
374 DAG->addMutation(createX86MacroFusionDAGMutation());
375 return DAG;
376 }
377
378 ScheduleDAGInstrs *
createPostMachineScheduler(MachineSchedContext * C) const379 createPostMachineScheduler(MachineSchedContext *C) const override {
380 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
381 DAG->addMutation(createX86MacroFusionDAGMutation());
382 return DAG;
383 }
384
385 void addIRPasses() override;
386 bool addInstSelector() override;
387 bool addIRTranslator() override;
388 bool addLegalizeMachineIR() override;
389 bool addRegBankSelect() override;
390 bool addGlobalInstructionSelect() override;
391 bool addILPOpts() override;
392 bool addPreISel() override;
393 void addMachineSSAOptimization() override;
394 void addPreRegAlloc() override;
395 bool addPostFastRegAllocRewrite() override;
396 void addPostRegAlloc() override;
397 void addPreEmitPass() override;
398 void addPreEmitPass2() override;
399 void addPreSched2() override;
400 bool addRegAssignAndRewriteOptimized() override;
401
402 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
403 };
404
405 class X86ExecutionDomainFix : public ExecutionDomainFix {
406 public:
407 static char ID;
X86ExecutionDomainFix()408 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
getPassName() const409 StringRef getPassName() const override {
410 return "X86 Execution Dependency Fix";
411 }
412 };
413 char X86ExecutionDomainFix::ID;
414
415 } // end anonymous namespace
416
417 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
418 "X86 Execution Domain Fix", false, false)
INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)419 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
420 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
421 "X86 Execution Domain Fix", false, false)
422
423 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
424 return new X86PassConfig(*this, PM);
425 }
426
addIRPasses()427 void X86PassConfig::addIRPasses() {
428 addPass(createAtomicExpandPass());
429
430 // We add both pass anyway and when these two passes run, we skip the pass
431 // based on the option level and option attribute.
432 addPass(createX86LowerAMXIntrinsicsPass());
433 addPass(createX86LowerAMXTypePass());
434
435 TargetPassConfig::addIRPasses();
436
437 if (TM->getOptLevel() != CodeGenOpt::None) {
438 addPass(createInterleavedAccessPass());
439 addPass(createX86PartialReductionPass());
440 }
441
442 // Add passes that handle indirect branch removal and insertion of a retpoline
443 // thunk. These will be a no-op unless a function subtarget has the retpoline
444 // feature enabled.
445 addPass(createIndirectBrExpandPass());
446
447 // Add Control Flow Guard checks.
448 const Triple &TT = TM->getTargetTriple();
449 if (TT.isOSWindows()) {
450 if (TT.getArch() == Triple::x86_64) {
451 addPass(createCFGuardDispatchPass());
452 } else {
453 addPass(createCFGuardCheckPass());
454 }
455 }
456
457 if (TM->Options.JMCInstrument)
458 addPass(createJMCInstrumenterPass());
459 }
460
addInstSelector()461 bool X86PassConfig::addInstSelector() {
462 // Install an instruction selector.
463 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
464
465 // For ELF, cleanup any local-dynamic TLS accesses.
466 if (TM->getTargetTriple().isOSBinFormatELF() &&
467 getOptLevel() != CodeGenOpt::None)
468 addPass(createCleanupLocalDynamicTLSPass());
469
470 addPass(createX86GlobalBaseRegPass());
471 return false;
472 }
473
addIRTranslator()474 bool X86PassConfig::addIRTranslator() {
475 addPass(new IRTranslator(getOptLevel()));
476 return false;
477 }
478
addLegalizeMachineIR()479 bool X86PassConfig::addLegalizeMachineIR() {
480 addPass(new Legalizer());
481 return false;
482 }
483
addRegBankSelect()484 bool X86PassConfig::addRegBankSelect() {
485 addPass(new RegBankSelect());
486 return false;
487 }
488
addGlobalInstructionSelect()489 bool X86PassConfig::addGlobalInstructionSelect() {
490 addPass(new InstructionSelect(getOptLevel()));
491 return false;
492 }
493
addILPOpts()494 bool X86PassConfig::addILPOpts() {
495 addPass(&EarlyIfConverterID);
496 if (EnableMachineCombinerPass)
497 addPass(&MachineCombinerID);
498 addPass(createX86CmovConverterPass());
499 return true;
500 }
501
addPreISel()502 bool X86PassConfig::addPreISel() {
503 // Only add this pass for 32-bit x86 Windows.
504 const Triple &TT = TM->getTargetTriple();
505 if (TT.isOSWindows() && TT.getArch() == Triple::x86)
506 addPass(createX86WinEHStatePass());
507 return true;
508 }
509
addPreRegAlloc()510 void X86PassConfig::addPreRegAlloc() {
511 if (getOptLevel() != CodeGenOpt::None) {
512 addPass(&LiveRangeShrinkID);
513 addPass(createX86FixupSetCC());
514 addPass(createX86OptimizeLEAs());
515 addPass(createX86CallFrameOptimization());
516 addPass(createX86AvoidStoreForwardingBlocks());
517 }
518
519 addPass(createX86SpeculativeLoadHardeningPass());
520 addPass(createX86FlagsCopyLoweringPass());
521 addPass(createX86DynAllocaExpander());
522
523 if (getOptLevel() != CodeGenOpt::None)
524 addPass(createX86PreTileConfigPass());
525 else
526 addPass(createX86FastPreTileConfigPass());
527 }
528
addMachineSSAOptimization()529 void X86PassConfig::addMachineSSAOptimization() {
530 addPass(createX86DomainReassignmentPass());
531 TargetPassConfig::addMachineSSAOptimization();
532 }
533
addPostRegAlloc()534 void X86PassConfig::addPostRegAlloc() {
535 addPass(createX86LowerTileCopyPass());
536 addPass(createX86FloatingPointStackifierPass());
537 // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
538 // to using the Speculative Execution Side Effect Suppression pass for
539 // mitigation. This is to prevent slow downs due to
540 // analyses needed by the LVIHardening pass when compiling at -O0.
541 if (getOptLevel() != CodeGenOpt::None)
542 addPass(createX86LoadValueInjectionLoadHardeningPass());
543 }
544
addPreSched2()545 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
546
addPreEmitPass()547 void X86PassConfig::addPreEmitPass() {
548 if (getOptLevel() != CodeGenOpt::None) {
549 addPass(new X86ExecutionDomainFix());
550 addPass(createBreakFalseDeps());
551 }
552
553 addPass(createX86IndirectBranchTrackingPass());
554
555 addPass(createX86IssueVZeroUpperPass());
556
557 if (getOptLevel() != CodeGenOpt::None) {
558 addPass(createX86FixupBWInsts());
559 addPass(createX86PadShortFunctions());
560 addPass(createX86FixupLEAs());
561 }
562 addPass(createX86EvexToVexInsts());
563 addPass(createX86DiscriminateMemOpsPass());
564 addPass(createX86InsertPrefetchPass());
565 addPass(createX86InsertX87waitPass());
566 }
567
addPreEmitPass2()568 void X86PassConfig::addPreEmitPass2() {
569 const Triple &TT = TM->getTargetTriple();
570 const MCAsmInfo *MAI = TM->getMCAsmInfo();
571
572 // The X86 Speculative Execution Pass must run after all control
573 // flow graph modifying passes. As a result it was listed to run right before
574 // the X86 Retpoline Thunks pass. The reason it must run after control flow
575 // graph modifications is that the model of LFENCE in LLVM has to be updated
576 // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
577 // placement of this pass was hand checked to ensure that the subsequent
578 // passes don't move the code around the LFENCEs in a way that will hurt the
579 // correctness of this pass. This placement has been shown to work based on
580 // hand inspection of the codegen output.
581 addPass(createX86SpeculativeExecutionSideEffectSuppression());
582 addPass(createX86IndirectThunksPass());
583 addPass(createX86ReturnThunksPass());
584
585 // Insert extra int3 instructions after trailing call instructions to avoid
586 // issues in the unwinder.
587 if (TT.isOSWindows() && TT.getArch() == Triple::x86_64)
588 addPass(createX86AvoidTrailingCallPass());
589
590 // Verify basic block incoming and outgoing cfa offset and register values and
591 // correct CFA calculation rule where needed by inserting appropriate CFI
592 // instructions.
593 if (!TT.isOSDarwin() &&
594 (!TT.isOSWindows() ||
595 MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
596 addPass(createCFIInstrInserter());
597
598 if (TT.isOSWindows()) {
599 // Identify valid longjmp targets for Windows Control Flow Guard.
600 addPass(createCFGuardLongjmpPass());
601 // Identify valid eh continuation targets for Windows EHCont Guard.
602 addPass(createEHContGuardCatchretPass());
603 }
604 addPass(createX86LoadValueInjectionRetHardeningPass());
605
606 // Insert pseudo probe annotation for callsite profiling
607 addPass(createPseudoProbeInserter());
608
609 // On Darwin platforms, BLR_RVMARKER pseudo instructions are lowered to
610 // bundles.
611 if (TT.isOSDarwin())
612 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
613 // Only run bundle expansion if there are relevant ObjC runtime functions
614 // present in the module.
615 const Function &F = MF.getFunction();
616 const Module *M = F.getParent();
617 return M->getFunction("objc_retainAutoreleasedReturnValue") ||
618 M->getFunction("objc_unsafeClaimAutoreleasedReturnValue");
619 }));
620 }
621
addPostFastRegAllocRewrite()622 bool X86PassConfig::addPostFastRegAllocRewrite() {
623 addPass(createX86FastTileConfigPass());
624 return true;
625 }
626
getCSEConfig() const627 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
628 return getStandardCSEConfigForOpt(TM->getOptLevel());
629 }
630
onlyAllocateTileRegisters(const TargetRegisterInfo & TRI,const TargetRegisterClass & RC)631 static bool onlyAllocateTileRegisters(const TargetRegisterInfo &TRI,
632 const TargetRegisterClass &RC) {
633 return static_cast<const X86RegisterInfo &>(TRI).isTileRegisterClass(&RC);
634 }
635
addRegAssignAndRewriteOptimized()636 bool X86PassConfig::addRegAssignAndRewriteOptimized() {
637 // Don't support tile RA when RA is specified by command line "-regalloc".
638 if (!isCustomizedRegAlloc() && EnableTileRAPass) {
639 // Allocate tile register first.
640 addPass(createGreedyRegisterAllocator(onlyAllocateTileRegisters));
641 addPass(createX86TileConfigPass());
642 }
643 return TargetPassConfig::addRegAssignAndRewriteOptimized();
644 }
645