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