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