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