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 "X86MachineFunctionInfo.h"
18#include "X86MacroFusion.h"
19#include "X86Subtarget.h"
20#include "X86TargetObjectFile.h"
21#include "X86TargetTransformInfo.h"
22#include "llvm-c/Visibility.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/CodeGen/ExecutionDomainFix.h"
27#include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28#include "llvm/CodeGen/GlobalISel/CallLowering.h"
29#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
30#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
31#include "llvm/CodeGen/GlobalISel/Legalizer.h"
32#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
33#include "llvm/CodeGen/MIRParser/MIParser.h"
34#include "llvm/CodeGen/MIRYamlMapping.h"
35#include "llvm/CodeGen/MachineScheduler.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/CodeGen/TargetPassConfig.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/Function.h"
41#include "llvm/MC/MCAsmInfo.h"
42#include "llvm/MC/TargetRegistry.h"
43#include "llvm/Pass.h"
44#include "llvm/Support/CodeGen.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Target/TargetLoweringObjectFile.h"
48#include "llvm/Target/TargetOptions.h"
49#include "llvm/TargetParser/Triple.h"
50#include "llvm/Transforms/CFGuard.h"
51#include <memory>
52#include <optional>
53
54using namespace llvm;
55
56cl::opt<bool>
57 X86EnableMachineCombinerPass("x86-machine-combiner",
58 cl::desc("Enable the machine combiner pass"),
59 cl::init(Val: true), cl::Hidden);
60
61static cl::opt<bool>
62 EnableTileRAPass("x86-tile-ra",
63 cl::desc("Enable the tile register allocation pass"),
64 cl::init(Val: true), cl::Hidden);
65
66extern "C" LLVM_C_ABI void LLVMInitializeX86Target() {
67 // Register the target.
68 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
69 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
70
71 PassRegistry &PR = *PassRegistry::getPassRegistry();
72 initializeX86LowerAMXIntrinsicsLegacyPassPass(PR);
73 initializeX86LowerAMXTypeLegacyPassPass(PR);
74 initializeX86PreTileConfigLegacyPass(PR);
75 initializeGlobalISel(PR);
76 initializeWinEHStateLegacyPass(PR);
77 initializeX86FixupBWInstLegacyPass(PR);
78 initializeCompressEVEXLegacyPass(PR);
79 initializeFixupLEAsLegacyPass(PR);
80 initializeX86FPStackifierLegacyPass(PR);
81 initializeX86FixupSetCCLegacyPass(PR);
82 initializeX86CallFrameOptimizationLegacyPass(PR);
83 initializeX86CmovConversionLegacyPass(PR);
84 initializeX86TileConfigLegacyPass(PR);
85 initializeX86FastPreTileConfigLegacyPass(PR);
86 initializeX86FastTileConfigLegacyPass(PR);
87 initializeMachineKCFILegacyPass(PR);
88 initializeX86LowerTileCopyLegacyPass(PR);
89 initializeX86ExpandPseudoLegacyPass(PR);
90 initializeX86ExecutionDomainFixPass(PR);
91 initializeX86DomainReassignmentLegacyPass(PR);
92 initializeX86AvoidSFBLegacyPass(PR);
93 initializeX86AvoidTrailingCallLegacyPassPass(PR);
94 initializeX86SpeculativeLoadHardeningLegacyPass(PR);
95 initializeX86SpeculativeExecutionSideEffectSuppressionLegacyPass(PR);
96 initializeX86FlagsCopyLoweringLegacyPass(PR);
97 initializeX86LoadValueInjectionLoadHardeningLegacyPass(PR);
98 initializeX86LoadValueInjectionRetHardeningLegacyPass(PR);
99 initializeX86OptimizeLEAsLegacyPass(PR);
100 initializeX86PartialReductionLegacyPass(PR);
101 initializeX86ReturnThunksLegacyPass(PR);
102 initializeX86DAGToDAGISelLegacyPass(PR);
103 initializeX86ArgumentStackSlotLegacyPass(PR);
104 initializeX86AsmPrinterPass(PR);
105 initializeX86FixupInstTuningLegacyPass(PR);
106 initializeX86FixupVectorConstantsLegacyPass(PR);
107 initializeX86DynAllocaExpanderLegacyPass(PR);
108 initializeX86SuppressAPXForRelocationLegacyPass(PR);
109 initializeX86WinEHUnwindV2LegacyPass(PR);
110 initializeX86PreLegalizerCombinerLegacyPass(PR);
111 initializeX86PostLegalizerCombinerLegacyPass(PR);
112 initializeX86WinEHUnwindV3Pass(PR);
113}
114
115static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
116 if (TT.isOSBinFormatMachO()) {
117 if (TT.isX86_64())
118 return std::make_unique<X86_64MachoTargetObjectFile>();
119 return std::make_unique<TargetLoweringObjectFileMachO>();
120 }
121
122 if (TT.isOSBinFormatCOFF())
123 return std::make_unique<TargetLoweringObjectFileCOFF>();
124
125 if (TT.isX86_64())
126 return std::make_unique<X86_64ELFTargetObjectFile>();
127 return std::make_unique<X86ELFTargetObjectFile>();
128}
129
130static Reloc::Model getEffectiveRelocModel(const Triple &TT, bool JIT,
131 std::optional<Reloc::Model> RM) {
132 bool is64Bit = TT.isX86_64();
133 if (!RM) {
134 // JIT codegen should use static relocations by default, since it's
135 // typically executed in process and not relocatable.
136 if (JIT)
137 return Reloc::Static;
138
139 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
140 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
141 // use static relocation model by default.
142 if (TT.isOSDarwin()) {
143 if (is64Bit)
144 return Reloc::PIC_;
145 return Reloc::DynamicNoPIC;
146 }
147 if (TT.isOSWindows() && is64Bit)
148 return Reloc::PIC_;
149 return Reloc::Static;
150 }
151
152 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
153 // is defined as a model for code which may be used in static or dynamic
154 // executables but not necessarily a shared library. On X86-32 we just
155 // compile in -static mode, in x86-64 we use PIC.
156 if (*RM == Reloc::DynamicNoPIC) {
157 if (is64Bit)
158 return Reloc::PIC_;
159 if (!TT.isOSDarwin())
160 return Reloc::Static;
161 }
162
163 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
164 // the Mach-O file format doesn't support it.
165 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
166 return Reloc::PIC_;
167
168 return *RM;
169}
170
171static CodeModel::Model
172getEffectiveX86CodeModel(const Triple &TT, std::optional<CodeModel::Model> CM,
173 bool JIT) {
174 bool Is64Bit = TT.isX86_64();
175 if (CM) {
176 if (*CM == CodeModel::Tiny)
177 reportFatalUsageError(reason: "target does not support the tiny CodeModel");
178 return *CM;
179 }
180 if (JIT)
181 return Is64Bit ? CodeModel::Large : CodeModel::Small;
182 return CodeModel::Small;
183}
184
185/// Create an X86 target.
186///
187X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
188 StringRef CPU, StringRef FS,
189 const TargetOptions &Options,
190 std::optional<Reloc::Model> RM,
191 std::optional<CodeModel::Model> CM,
192 CodeGenOptLevel OL, bool JIT)
193 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
194 getEffectiveRelocModel(TT, JIT, RM),
195 getEffectiveX86CodeModel(TT, CM, JIT), OL),
196 TLOF(createTLOF(TT: getTargetTriple())), IsJIT(JIT) {
197 // On PS4/PS5, the "return address" of a 'noreturn' call must still be within
198 // the calling function. Note that this also includes __stack_chk_fail,
199 // so there was some target-specific logic in the instruction selectors
200 // to handle that. That code has since been generalized, so the only thing
201 // needed is to set TrapUnreachable here.
202 if (TT.isPS() || TT.isOSBinFormatMachO()) {
203 this->Options.TrapUnreachable = true;
204 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
205 }
206
207 setMachineOutliner(true);
208
209 // x86 supports the debug entry values.
210 setSupportsDebugEntryValues(true);
211
212 initAsmInfo();
213}
214
215X86TargetMachine::~X86TargetMachine() = default;
216
217const X86Subtarget *
218X86TargetMachine::getSubtargetImpl(const Function &F) const {
219 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
220 Attribute TuneAttr = F.getFnAttribute(Kind: "tune-cpu");
221 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
222
223 StringRef CPU =
224 CPUAttr.isValid() ? CPUAttr.getValueAsString() : (StringRef)TargetCPU;
225 // "x86-64" is a default target setting for many front ends. In these cases,
226 // they actually request for "generic" tuning unless the "tune-cpu" was
227 // specified.
228 StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString()
229 : CPU == "x86-64" ? "generic"
230 : (StringRef)CPU;
231 StringRef FS =
232 FSAttr.isValid() ? FSAttr.getValueAsString() : (StringRef)TargetFS;
233
234 SmallString<512> Key;
235 // The additions here are ordered so that the definitely short strings are
236 // added first so we won't exceed the small size. We append the
237 // much longer FS string at the end so that we only heap allocate at most
238 // one time.
239
240 // Extract prefer-vector-width attribute.
241 unsigned PreferVectorWidthOverride = 0;
242 Attribute PreferVecWidthAttr = F.getFnAttribute(Kind: "prefer-vector-width");
243 if (PreferVecWidthAttr.isValid()) {
244 StringRef Val = PreferVecWidthAttr.getValueAsString();
245 unsigned Width;
246 if (!Val.getAsInteger(Radix: 0, Result&: Width)) {
247 Key += 'p';
248 Key += Val;
249 PreferVectorWidthOverride = Width;
250 }
251 }
252
253 // Extract min-legal-vector-width attribute.
254 unsigned RequiredVectorWidth = UINT32_MAX;
255 Attribute MinLegalVecWidthAttr = F.getFnAttribute(Kind: "min-legal-vector-width");
256 if (MinLegalVecWidthAttr.isValid()) {
257 StringRef Val = MinLegalVecWidthAttr.getValueAsString();
258 unsigned Width;
259 if (!Val.getAsInteger(Radix: 0, Result&: Width)) {
260 Key += 'm';
261 Key += Val;
262 RequiredVectorWidth = Width;
263 }
264 }
265
266 // Add CPU to the Key.
267 Key += CPU;
268
269 // Add tune CPU to the Key.
270 Key += TuneCPU;
271
272 // Keep track of the start of the feature portion of the string.
273 unsigned FSStart = Key.size();
274
275 // FIXME: This is related to the code below to reset the target options,
276 // we need to know whether or not the soft float flag is set on the
277 // function before we can generate a subtarget. We also need to use
278 // it as a key for the subtarget since that can be the only difference
279 // between two functions.
280 bool SoftFloat = F.getFnAttribute(Kind: "use-soft-float").getValueAsBool();
281 // If the soft float attribute is set on the function turn on the soft float
282 // subtarget feature.
283 if (SoftFloat)
284 Key += FS.empty() ? "+soft-float" : "+soft-float,";
285
286 Key += FS;
287
288 // We may have added +soft-float to the features so move the StringRef to
289 // point to the full string in the Key.
290 FS = Key.substr(Start: FSStart);
291
292 auto &I = SubtargetMap[Key];
293 if (!I) {
294 I = std::make_unique<X86Subtarget>(
295 args: TargetTriple, args&: CPU, args&: TuneCPU, args&: FS, args: *this,
296 args: MaybeAlign(F.getParent()->getOverrideStackAlignment()),
297 args&: PreferVectorWidthOverride, args&: RequiredVectorWidth);
298 }
299 return I.get();
300}
301
302yaml::MachineFunctionInfo *X86TargetMachine::createDefaultFuncInfoYAML() const {
303 return new yaml::X86MachineFunctionInfo();
304}
305
306yaml::MachineFunctionInfo *
307X86TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
308 const auto *MFI = MF.getInfo<X86MachineFunctionInfo>();
309 return new yaml::X86MachineFunctionInfo(*MFI);
310}
311
312bool X86TargetMachine::parseMachineFunctionInfo(
313 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
314 SMDiagnostic &Error, SMRange &SourceRange) const {
315 const auto &YamlMFI = static_cast<const yaml::X86MachineFunctionInfo &>(MFI);
316 PFS.MF.getInfo<X86MachineFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
317 return false;
318}
319
320bool X86TargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
321 unsigned DestAS) const {
322 assert(SrcAS != DestAS && "Expected different address spaces!");
323 if (getPointerSize(AS: SrcAS) != getPointerSize(AS: DestAS))
324 return false;
325 return SrcAS < 256 && DestAS < 256;
326}
327
328void X86TargetMachine::reset() { SubtargetMap.clear(); }
329
330ScheduleDAGInstrs *
331X86TargetMachine::createMachineScheduler(MachineSchedContext *C) const {
332 ScheduleDAGMILive *DAG = createSchedLive(C);
333 DAG->addMutation(Mutation: createX86MacroFusionDAGMutation());
334 return DAG;
335}
336
337ScheduleDAGInstrs *
338X86TargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
339 ScheduleDAGMI *DAG = createSchedPostRA(C);
340 DAG->addMutation(Mutation: createX86MacroFusionDAGMutation());
341 return DAG;
342}
343
344//===----------------------------------------------------------------------===//
345// X86 TTI query.
346//===----------------------------------------------------------------------===//
347
348TargetTransformInfo
349X86TargetMachine::getTargetTransformInfo(const Function &F) const {
350 return TargetTransformInfo(std::make_unique<X86TTIImpl>(args: this, args: F));
351}
352
353//===----------------------------------------------------------------------===//
354// Pass Pipeline Configuration
355//===----------------------------------------------------------------------===//
356
357namespace {
358
359/// X86 Code Generator Pass Configuration Options.
360class X86PassConfig : public TargetPassConfig {
361public:
362 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
363 : TargetPassConfig(TM, PM) {}
364
365 X86TargetMachine &getX86TargetMachine() const {
366 return getTM<X86TargetMachine>();
367 }
368
369 void addIRPasses() override;
370 bool addInstSelector() override;
371 bool addIRTranslator() override;
372 bool addLegalizeMachineIR() override;
373 void addPreRegBankSelect() override;
374 bool addRegBankSelect() override;
375 bool addGlobalInstructionSelect() override;
376 void addPreLegalizeMachineIR() override;
377 bool addILPOpts() override;
378 bool addPreISel() override;
379 void addMachineSSAOptimization() override;
380 void addPreRegAlloc() override;
381 bool addPostFastRegAllocRewrite() override;
382 void addPostRegAlloc() override;
383 void addPreEmitPass() override;
384 void addPreEmitPass2() override;
385 void addPreSched2() override;
386 bool addRegAssignAndRewriteOptimized() override;
387
388 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
389};
390
391class X86ExecutionDomainFix : public ExecutionDomainFix {
392public:
393 static char ID;
394 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
395 StringRef getPassName() const override {
396 return "X86 Execution Dependency Fix";
397 }
398};
399char X86ExecutionDomainFix::ID;
400
401} // end anonymous namespace
402
403INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
404 "X86 Execution Domain Fix", false, false)
405INITIALIZE_PASS_DEPENDENCY(ReachingDefInfoWrapperPass)
406INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
407 "X86 Execution Domain Fix", false, false)
408
409TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
410 return new X86PassConfig(*this, PM);
411}
412
413MachineFunctionInfo *X86TargetMachine::createMachineFunctionInfo(
414 BumpPtrAllocator &Allocator, const Function &F,
415 const TargetSubtargetInfo *STI) const {
416 return X86MachineFunctionInfo::create<X86MachineFunctionInfo>(Allocator, F,
417 STI);
418}
419
420void X86PassConfig::addIRPasses() {
421 addPass(P: createAtomicExpandLegacyPass());
422
423 // We add both pass anyway and when these two passes run, we skip the pass
424 // based on the option level and option attribute.
425 addPass(P: createX86LowerAMXIntrinsicsLegacyPass());
426 addPass(P: createX86LowerAMXTypeLegacyPass());
427
428 TargetPassConfig::addIRPasses();
429
430 if (TM->getOptLevel() != CodeGenOptLevel::None) {
431 addPass(P: createInterleavedAccessPass());
432 addPass(P: createX86PartialReductionLegacyPass());
433 }
434
435 // Add passes that handle indirect branch removal and insertion of a retpoline
436 // thunk. These will be a no-op unless a function subtarget has the retpoline
437 // feature enabled.
438 addPass(P: createIndirectBrExpandPass());
439
440 // Add Control Flow Guard checks.
441 const Triple &TT = TM->getTargetTriple();
442 if (TT.isOSWindows()) {
443 addPass(P: createCFGuardPass());
444 }
445
446 if (TM->Options.JMCInstrument)
447 addPass(P: createJMCInstrumenterPass());
448}
449
450bool X86PassConfig::addInstSelector() {
451 // Install an instruction selector.
452 addPass(P: createX86ISelDag(TM&: getX86TargetMachine(), OptLevel: getOptLevel()));
453
454 // For ELF, cleanup any local-dynamic TLS accesses.
455 if (TM->getTargetTriple().isOSBinFormatELF() &&
456 getOptLevel() != CodeGenOptLevel::None)
457 addPass(P: createCleanupLocalDynamicTLSLegacyPass());
458
459 addPass(P: createX86GlobalBaseRegLegacyPass());
460 addPass(P: createX86ArgumentStackSlotLegacyPass());
461 return false;
462}
463
464bool X86PassConfig::addIRTranslator() {
465 addPass(P: new IRTranslator(getOptLevel()));
466 return false;
467}
468
469void X86PassConfig::addPreRegBankSelect() {
470 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
471 if (!IsOptNone) {
472 addPass(P: createX86PostLegalizerCombinerLegacy());
473 }
474}
475bool X86PassConfig::addLegalizeMachineIR() {
476 addPass(P: new Legalizer());
477 return false;
478}
479
480bool X86PassConfig::addRegBankSelect() {
481 addPass(P: new RegBankSelect());
482 return false;
483}
484
485bool X86PassConfig::addGlobalInstructionSelect() {
486 addPass(P: new InstructionSelect(getOptLevel()));
487 // Add GlobalBaseReg in case there is no SelectionDAG passes afterwards
488 if (isGlobalISelAbortEnabled())
489 addPass(P: createX86GlobalBaseRegLegacyPass());
490 return false;
491}
492
493void X86PassConfig::addPreLegalizeMachineIR() {
494 if (getOptLevel() != CodeGenOptLevel::None) {
495 addPass(P: createX86PreLegalizerCombinerLegacy());
496 }
497}
498
499bool X86PassConfig::addILPOpts() {
500 addPass(PassID: &EarlyIfConverterLegacyID);
501 if (X86EnableMachineCombinerPass)
502 addPass(PassID: &MachineCombinerID);
503 addPass(P: createX86CmovConversionLegacyPass());
504 return true;
505}
506
507bool X86PassConfig::addPreISel() {
508 // Only add this pass for 32-bit x86 Windows.
509 const Triple &TT = TM->getTargetTriple();
510 if (TT.isOSWindows() && TT.isX86_32())
511 addPass(P: createX86WinEHStateLegacyPass());
512 return true;
513}
514
515void X86PassConfig::addPreRegAlloc() {
516 if (getOptLevel() != CodeGenOptLevel::None) {
517 addPass(PassID: &LiveRangeShrinkID);
518 addPass(P: createX86FixupSetCCLegacyPass());
519 addPass(P: createX86OptimizeLEAsLegacyPass());
520 addPass(P: createX86CallFrameOptimizationLegacyPass());
521 addPass(P: createX86AvoidStoreForwardingBlocksLegacyPass());
522 }
523
524 addPass(P: createX86SuppressAPXForRelocationLegacyPass());
525
526 addPass(P: createX86SpeculativeLoadHardeningLegacyPass());
527 addPass(P: createX86FlagsCopyLoweringLegacyPass());
528 addPass(P: createX86DynAllocaExpanderLegacyPass());
529
530 if (getOptLevel() != CodeGenOptLevel::None)
531 addPass(P: createX86PreTileConfigLegacyPass());
532 else
533 addPass(P: createX86FastPreTileConfigLegacyPass());
534}
535
536void X86PassConfig::addMachineSSAOptimization() {
537 addPass(P: createX86DomainReassignmentLegacyPass());
538 TargetPassConfig::addMachineSSAOptimization();
539}
540
541void X86PassConfig::addPostRegAlloc() {
542 addPass(P: createX86LowerTileCopyLegacyPass());
543 addPass(P: createX86FPStackifierLegacyPass());
544 // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
545 // to using the Speculative Execution Side Effect Suppression pass for
546 // mitigation. This is to prevent slow downs due to
547 // analyses needed by the LVIHardening pass when compiling at -O0.
548 if (getOptLevel() != CodeGenOptLevel::None)
549 addPass(P: createX86LoadValueInjectionLoadHardeningLegacyPass());
550}
551
552void X86PassConfig::addPreSched2() {
553 addPass(P: createX86ExpandPseudoLegacyPass());
554 addPass(P: createKCFIPass());
555}
556
557void X86PassConfig::addPreEmitPass() {
558 if (getOptLevel() != CodeGenOptLevel::None) {
559 addPass(P: new X86ExecutionDomainFix());
560 addPass(P: createBreakFalseDepsLegacyPass());
561 }
562
563 addPass(P: createX86IndirectBranchTrackingLegacyPass());
564
565 addPass(P: createX86InsertVZeroUpperLegacyPass());
566
567 if (getOptLevel() != CodeGenOptLevel::None) {
568 addPass(P: createX86FixupBWInstsLegacyPass());
569 addPass(P: createX86PadShortFunctions());
570 addPass(P: createX86FixupLEAsLegacyPass());
571 addPass(P: createX86FixupInstTuningLegacyPass());
572 addPass(P: createX86FixupVectorConstantsLegacyPass());
573 }
574 addPass(P: createX86CompressEVEXLegacyPass());
575 addPass(P: createX86InsertX87WaitLegacyPass());
576}
577
578void X86PassConfig::addPreEmitPass2() {
579 const Triple &TT = TM->getTargetTriple();
580 const MCAsmInfo &MAI = TM->getMCAsmInfo();
581
582 // The X86 Speculative Execution Pass must run after all control
583 // flow graph modifying passes. As a result it was listed to run right before
584 // the X86 Retpoline Thunks pass. The reason it must run after control flow
585 // graph modifications is that the model of LFENCE in LLVM has to be updated
586 // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
587 // placement of this pass was hand checked to ensure that the subsequent
588 // passes don't move the code around the LFENCEs in a way that will hurt the
589 // correctness of this pass. This placement has been shown to work based on
590 // hand inspection of the codegen output.
591 addPass(P: createX86SpeculativeExecutionSideEffectSuppressionLegacyPass());
592 addPass(P: createX86IndirectThunksPass());
593 addPass(P: createX86ReturnThunksLegacyPass());
594
595 // Insert extra int3 instructions after trailing call instructions to avoid
596 // issues in the unwinder.
597 if (TT.isOSWindows() && TT.isX86_64())
598 addPass(P: createX86AvoidTrailingCallLegacyPass());
599
600 // Verify basic block incoming and outgoing cfa offset and register values and
601 // correct CFA calculation rule where needed by inserting appropriate CFI
602 // instructions.
603 if (!TT.isOSDarwin() &&
604 (!TT.isOSWindows() ||
605 MAI.getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
606 addPass(P: createCFIInstrInserter());
607
608 if (TT.isOSWindows()) {
609 // Identify valid longjmp targets for Windows Control Flow Guard.
610 addPass(P: createCFGuardLongjmpPass());
611 // Identify valid eh continuation targets for Windows EHCont Guard.
612 addPass(P: createEHContGuardTargetsPass());
613 }
614 addPass(P: createX86LoadValueInjectionRetHardeningLegacyPass());
615
616 // Insert pseudo probe annotation for callsite profiling
617 addPass(P: createPseudoProbeInserter());
618
619 // KCFI indirect call checks are lowered to a bundle, and on Darwin platforms,
620 // also CALL_RVMARKER.
621 addPass(P: createUnpackMachineBundlesLegacy(Ftor: [&TT](const MachineFunction &MF) {
622 // Only run bundle expansion if the module uses kcfi, or there are relevant
623 // ObjC runtime functions present in the module.
624 const Function &F = MF.getFunction();
625 const Module *M = F.getParent();
626 return M->getModuleFlag(Key: "kcfi") ||
627 (TT.isOSDarwin() &&
628 (M->getFunction(Name: "objc_retainAutoreleasedReturnValue") ||
629 M->getFunction(Name: "objc_unsafeClaimAutoreleasedReturnValue")));
630 }));
631
632 // Analyzes and emits pseudos to support Win x64 Unwind V2. This pass must run
633 // after all real instructions have been added to the epilog.
634 if (TT.isOSWindows() && TT.isX86_64()) {
635 addPass(P: createX86WinEHUnwindV2LegacyPass());
636 addPass(P: createX86WinEHUnwindV3Pass());
637 }
638}
639
640bool X86PassConfig::addPostFastRegAllocRewrite() {
641 addPass(P: createX86FastTileConfigLegacyPass());
642 return true;
643}
644
645std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
646 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
647}
648
649static bool onlyAllocateTileRegisters(const TargetRegisterInfo &TRI,
650 const MachineRegisterInfo &MRI,
651 const Register Reg) {
652 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
653 return static_cast<const X86RegisterInfo &>(TRI).isTileRegisterClass(RC);
654}
655
656bool X86PassConfig::addRegAssignAndRewriteOptimized() {
657 // Don't support tile RA when RA is specified by command line "-regalloc".
658 if (!isCustomizedRegAlloc() && EnableTileRAPass) {
659 // Allocate tile register first.
660 addPass(P: createGreedyRegisterAllocator(F: onlyAllocateTileRegisters));
661 addPass(P: createX86TileConfigLegacyPass());
662 }
663 return TargetPassConfig::addRegAssignAndRewriteOptimized();
664}
665