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