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