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 <memory> 50 #include <string> 51 52 using namespace llvm; 53 54 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner", 55 cl::desc("Enable the machine combiner pass"), 56 cl::init(true), cl::Hidden); 57 58 static cl::opt<bool> EnableCondBrFoldingPass("x86-condbr-folding", 59 cl::desc("Enable the conditional branch " 60 "folding pass"), 61 cl::init(false), cl::Hidden); 62 63 extern "C" void LLVMInitializeX86Target() { 64 // Register the target. 65 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target()); 66 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target()); 67 68 PassRegistry &PR = *PassRegistry::getPassRegistry(); 69 initializeGlobalISel(PR); 70 initializeWinEHStatePassPass(PR); 71 initializeFixupBWInstPassPass(PR); 72 initializeEvexToVexInstPassPass(PR); 73 initializeFixupLEAPassPass(PR); 74 initializeX86CallFrameOptimizationPass(PR); 75 initializeX86CmovConverterPassPass(PR); 76 initializeX86ExpandPseudoPass(PR); 77 initializeX86ExecutionDomainFixPass(PR); 78 initializeX86DomainReassignmentPass(PR); 79 initializeX86AvoidSFBPassPass(PR); 80 initializeX86SpeculativeLoadHardeningPassPass(PR); 81 initializeX86FlagsCopyLoweringPassPass(PR); 82 initializeX86CondBrFoldingPassPass(PR); 83 } 84 85 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 86 if (TT.isOSBinFormatMachO()) { 87 if (TT.getArch() == Triple::x86_64) 88 return llvm::make_unique<X86_64MachoTargetObjectFile>(); 89 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 90 } 91 92 if (TT.isOSFreeBSD()) 93 return llvm::make_unique<X86FreeBSDTargetObjectFile>(); 94 if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU()) 95 return llvm::make_unique<X86LinuxNaClTargetObjectFile>(); 96 if (TT.isOSSolaris()) 97 return llvm::make_unique<X86SolarisTargetObjectFile>(); 98 if (TT.isOSFuchsia()) 99 return llvm::make_unique<X86FuchsiaTargetObjectFile>(); 100 if (TT.isOSBinFormatELF()) 101 return llvm::make_unique<X86ELFTargetObjectFile>(); 102 if (TT.isOSBinFormatCOFF()) 103 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 104 llvm_unreachable("unknown subtarget type"); 105 } 106 107 static std::string computeDataLayout(const Triple &TT) { 108 // X86 is little endian 109 std::string Ret = "e"; 110 111 Ret += DataLayout::getManglingComponent(TT); 112 // X86 and x32 have 32 bit pointers. 113 if ((TT.isArch64Bit() && 114 (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || 115 !TT.isArch64Bit()) 116 Ret += "-p:32:32"; 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())) { 220 // Windows stack unwinder gets confused when execution flow "falls through" 221 // after a call to 'noreturn' function. 222 // To prevent that, we emit a trap for 'unreachable' IR instructions. 223 // (which on X86, happens to be the 'ud2' instruction) 224 // On PS4, the "return address" of a 'noreturn' call must still be within 225 // the calling function, and TrapUnreachable is an easy way to get that. 226 // The check here for 64-bit windows is a bit icky, but as we're unlikely 227 // to ever want to mix 32 and 64-bit windows code in a single module 228 // this should be fine. 229 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4() || 230 TT.isOSBinFormatMachO()) { 231 this->Options.TrapUnreachable = true; 232 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO(); 233 } 234 235 // Outlining is available for x86-64. 236 if (TT.getArch() == Triple::x86_64) 237 setMachineOutliner(true); 238 239 initAsmInfo(); 240 } 241 242 X86TargetMachine::~X86TargetMachine() = default; 243 244 const X86Subtarget * 245 X86TargetMachine::getSubtargetImpl(const Function &F) const { 246 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 247 Attribute FSAttr = F.getFnAttribute("target-features"); 248 249 StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) 250 ? CPUAttr.getValueAsString() 251 : (StringRef)TargetCPU; 252 StringRef FS = !FSAttr.hasAttribute(Attribute::None) 253 ? FSAttr.getValueAsString() 254 : (StringRef)TargetFS; 255 256 SmallString<512> Key; 257 Key.reserve(CPU.size() + FS.size()); 258 Key += CPU; 259 Key += FS; 260 261 // FIXME: This is related to the code below to reset the target options, 262 // we need to know whether or not the soft float flag is set on the 263 // function before we can generate a subtarget. We also need to use 264 // it as a key for the subtarget since that can be the only difference 265 // between two functions. 266 bool SoftFloat = 267 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 268 // If the soft float attribute is set on the function turn on the soft float 269 // subtarget feature. 270 if (SoftFloat) 271 Key += FS.empty() ? "+soft-float" : ",+soft-float"; 272 273 // Keep track of the key width after all features are added so we can extract 274 // the feature string out later. 275 unsigned CPUFSWidth = Key.size(); 276 277 // Extract prefer-vector-width attribute. 278 unsigned PreferVectorWidthOverride = 0; 279 if (F.hasFnAttribute("prefer-vector-width")) { 280 StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString(); 281 unsigned Width; 282 if (!Val.getAsInteger(0, Width)) { 283 Key += ",prefer-vector-width="; 284 Key += Val; 285 PreferVectorWidthOverride = Width; 286 } 287 } 288 289 // Extract min-legal-vector-width attribute. 290 unsigned RequiredVectorWidth = UINT32_MAX; 291 if (F.hasFnAttribute("min-legal-vector-width")) { 292 StringRef Val = 293 F.getFnAttribute("min-legal-vector-width").getValueAsString(); 294 unsigned Width; 295 if (!Val.getAsInteger(0, Width)) { 296 Key += ",min-legal-vector-width="; 297 Key += Val; 298 RequiredVectorWidth = Width; 299 } 300 } 301 302 // Extracted here so that we make sure there is backing for the StringRef. If 303 // we assigned earlier, its possible the SmallString reallocated leaving a 304 // dangling StringRef. 305 FS = Key.slice(CPU.size(), CPUFSWidth); 306 307 auto &I = SubtargetMap[Key]; 308 if (!I) { 309 // This needs to be done before we create a new subtarget since any 310 // creation will depend on the TM and the code generation flags on the 311 // function that reside in TargetOptions. 312 resetTargetOptions(F); 313 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, 314 Options.StackAlignmentOverride, 315 PreferVectorWidthOverride, 316 RequiredVectorWidth); 317 } 318 return I.get(); 319 } 320 321 //===----------------------------------------------------------------------===// 322 // Command line options for x86 323 //===----------------------------------------------------------------------===// 324 static cl::opt<bool> 325 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, 326 cl::desc("Minimize AVX to SSE transition penalty"), 327 cl::init(true)); 328 329 //===----------------------------------------------------------------------===// 330 // X86 TTI query. 331 //===----------------------------------------------------------------------===// 332 333 TargetTransformInfo 334 X86TargetMachine::getTargetTransformInfo(const Function &F) { 335 return TargetTransformInfo(X86TTIImpl(this, F)); 336 } 337 338 //===----------------------------------------------------------------------===// 339 // Pass Pipeline Configuration 340 //===----------------------------------------------------------------------===// 341 342 namespace { 343 344 /// X86 Code Generator Pass Configuration Options. 345 class X86PassConfig : public TargetPassConfig { 346 public: 347 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM) 348 : TargetPassConfig(TM, PM) {} 349 350 X86TargetMachine &getX86TargetMachine() const { 351 return getTM<X86TargetMachine>(); 352 } 353 354 ScheduleDAGInstrs * 355 createMachineScheduler(MachineSchedContext *C) const override { 356 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 357 DAG->addMutation(createX86MacroFusionDAGMutation()); 358 return DAG; 359 } 360 361 ScheduleDAGInstrs * 362 createPostMachineScheduler(MachineSchedContext *C) const override { 363 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 364 DAG->addMutation(createX86MacroFusionDAGMutation()); 365 return DAG; 366 } 367 368 void addIRPasses() override; 369 bool addInstSelector() override; 370 bool addIRTranslator() override; 371 bool addLegalizeMachineIR() override; 372 bool addRegBankSelect() override; 373 bool addGlobalInstructionSelect() override; 374 bool addILPOpts() override; 375 bool addPreISel() override; 376 void addMachineSSAOptimization() override; 377 void addPreRegAlloc() override; 378 void addPostRegAlloc() override; 379 void addPreEmitPass() override; 380 void addPreEmitPass2() override; 381 void addPreSched2() override; 382 383 std::unique_ptr<CSEConfigBase> getCSEConfig() const override; 384 }; 385 386 class X86ExecutionDomainFix : public ExecutionDomainFix { 387 public: 388 static char ID; 389 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {} 390 StringRef getPassName() const override { 391 return "X86 Execution Dependency Fix"; 392 } 393 }; 394 char X86ExecutionDomainFix::ID; 395 396 } // end anonymous namespace 397 398 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix", 399 "X86 Execution Domain Fix", false, false) 400 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 401 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix", 402 "X86 Execution Domain Fix", false, false) 403 404 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { 405 return new X86PassConfig(*this, PM); 406 } 407 408 void X86PassConfig::addIRPasses() { 409 addPass(createAtomicExpandPass()); 410 411 TargetPassConfig::addIRPasses(); 412 413 if (TM->getOptLevel() != CodeGenOpt::None) 414 addPass(createInterleavedAccessPass()); 415 416 // Add passes that handle indirect branch removal and insertion of a retpoline 417 // thunk. These will be a no-op unless a function subtarget has the retpoline 418 // feature enabled. 419 addPass(createIndirectBrExpandPass()); 420 } 421 422 bool X86PassConfig::addInstSelector() { 423 // Install an instruction selector. 424 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); 425 426 // For ELF, cleanup any local-dynamic TLS accesses. 427 if (TM->getTargetTriple().isOSBinFormatELF() && 428 getOptLevel() != CodeGenOpt::None) 429 addPass(createCleanupLocalDynamicTLSPass()); 430 431 addPass(createX86GlobalBaseRegPass()); 432 return false; 433 } 434 435 bool X86PassConfig::addIRTranslator() { 436 addPass(new IRTranslator()); 437 return false; 438 } 439 440 bool X86PassConfig::addLegalizeMachineIR() { 441 addPass(new Legalizer()); 442 return false; 443 } 444 445 bool X86PassConfig::addRegBankSelect() { 446 addPass(new RegBankSelect()); 447 return false; 448 } 449 450 bool X86PassConfig::addGlobalInstructionSelect() { 451 addPass(new InstructionSelect()); 452 return false; 453 } 454 455 bool X86PassConfig::addILPOpts() { 456 if (EnableCondBrFoldingPass) 457 addPass(createX86CondBrFolding()); 458 addPass(&EarlyIfConverterID); 459 if (EnableMachineCombinerPass) 460 addPass(&MachineCombinerID); 461 addPass(createX86CmovConverterPass()); 462 return true; 463 } 464 465 bool X86PassConfig::addPreISel() { 466 // Only add this pass for 32-bit x86 Windows. 467 const Triple &TT = TM->getTargetTriple(); 468 if (TT.isOSWindows() && TT.getArch() == Triple::x86) 469 addPass(createX86WinEHStatePass()); 470 return true; 471 } 472 473 void X86PassConfig::addPreRegAlloc() { 474 if (getOptLevel() != CodeGenOpt::None) { 475 addPass(&LiveRangeShrinkID); 476 addPass(createX86FixupSetCC()); 477 addPass(createX86OptimizeLEAs()); 478 addPass(createX86CallFrameOptimization()); 479 addPass(createX86AvoidStoreForwardingBlocks()); 480 } 481 482 addPass(createX86SpeculativeLoadHardeningPass()); 483 addPass(createX86FlagsCopyLoweringPass()); 484 addPass(createX86WinAllocaExpander()); 485 } 486 void X86PassConfig::addMachineSSAOptimization() { 487 addPass(createX86DomainReassignmentPass()); 488 TargetPassConfig::addMachineSSAOptimization(); 489 } 490 491 void X86PassConfig::addPostRegAlloc() { 492 addPass(createX86FloatingPointStackifierPass()); 493 } 494 495 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } 496 497 void X86PassConfig::addPreEmitPass() { 498 if (getOptLevel() != CodeGenOpt::None) { 499 addPass(new X86ExecutionDomainFix()); 500 addPass(createBreakFalseDeps()); 501 } 502 503 addPass(createX86IndirectBranchTrackingPass()); 504 505 if (UseVZeroUpper) 506 addPass(createX86IssueVZeroUpperPass()); 507 508 if (getOptLevel() != CodeGenOpt::None) { 509 addPass(createX86FixupBWInsts()); 510 addPass(createX86PadShortFunctions()); 511 addPass(createX86FixupLEAs()); 512 addPass(createX86EvexToVexInsts()); 513 } 514 addPass(createX86DiscriminateMemOpsPass()); 515 addPass(createX86InsertPrefetchPass()); 516 } 517 518 void X86PassConfig::addPreEmitPass2() { 519 addPass(createX86RetpolineThunksPass()); 520 // Verify basic block incoming and outgoing cfa offset and register values and 521 // correct CFA calculation rule where needed by inserting appropriate CFI 522 // instructions. 523 const Triple &TT = TM->getTargetTriple(); 524 const MCAsmInfo *MAI = TM->getMCAsmInfo(); 525 if (!TT.isOSDarwin() && 526 (!TT.isOSWindows() || 527 MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI)) 528 addPass(createCFIInstrInserter()); 529 } 530 531 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const { 532 return getStandardCSEConfigForOpt(TM->getOptLevel()); 533 } 534