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