1 //===-- TargetMachine.cpp - General Target Information ---------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file describes the general parts of a Target machine.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/CodeGen/Analysis.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalAlias.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCCodeGenInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCTargetOptions.h"
30 #include "llvm/MC/SectionKind.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 using namespace llvm;
35 
36 //---------------------------------------------------------------------------
37 // TargetMachine Class
38 //
39 
40 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
41                              const Triple &TT, StringRef CPU, StringRef FS,
42                              const TargetOptions &Options)
43     : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
44       TargetFS(FS), CodeGenInfo(nullptr), AsmInfo(nullptr), MRI(nullptr),
45       MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
46       Options(Options) {}
47 
48 TargetMachine::~TargetMachine() {
49   delete CodeGenInfo;
50   delete AsmInfo;
51   delete MRI;
52   delete MII;
53   delete STI;
54 }
55 
56 bool TargetMachine::isPositionIndependent() const {
57   return getRelocationModel() == Reloc::PIC_;
58 }
59 
60 /// \brief Reset the target options based on the function's attributes.
61 // FIXME: This function needs to go away for a number of reasons:
62 // a) global state on the TargetMachine is terrible in general,
63 // b) there's no default state here to keep,
64 // c) these target options should be passed only on the function
65 //    and not on the TargetMachine (via TargetOptions) at all.
66 void TargetMachine::resetTargetOptions(const Function &F) const {
67 #define RESET_OPTION(X, Y)                                                     \
68   do {                                                                         \
69     if (F.hasFnAttribute(Y))                                                   \
70       Options.X = (F.getFnAttribute(Y).getValueAsString() == "true");          \
71   } while (0)
72 
73   RESET_OPTION(LessPreciseFPMADOption, "less-precise-fpmad");
74   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
75   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
76   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
77 }
78 
79 /// Returns the code generation relocation model. The choices are static, PIC,
80 /// and dynamic-no-pic.
81 Reloc::Model TargetMachine::getRelocationModel() const {
82   if (!CodeGenInfo)
83     return Reloc::Static; // FIXME
84   return CodeGenInfo->getRelocationModel();
85 }
86 
87 /// getCodeModel - Returns the code model. The choices are small, kernel,
88 /// medium, large, and target default.
89 CodeModel::Model TargetMachine::getCodeModel() const {
90   if (!CodeGenInfo)
91     return CodeModel::Default;
92   return CodeGenInfo->getCodeModel();
93 }
94 
95 /// Get the IR-specified TLS model for Var.
96 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
97   switch (GV->getThreadLocalMode()) {
98   case GlobalVariable::NotThreadLocal:
99     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
100     break;
101   case GlobalVariable::GeneralDynamicTLSModel:
102     return TLSModel::GeneralDynamic;
103   case GlobalVariable::LocalDynamicTLSModel:
104     return TLSModel::LocalDynamic;
105   case GlobalVariable::InitialExecTLSModel:
106     return TLSModel::InitialExec;
107   case GlobalVariable::LocalExecTLSModel:
108     return TLSModel::LocalExec;
109   }
110   llvm_unreachable("invalid TLS model");
111 }
112 
113 // FIXME: make this a proper option
114 static bool CanUseCopyRelocWithPIE = false;
115 
116 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
117                                          const GlobalValue *GV) const {
118   Reloc::Model RM = getRelocationModel();
119   const Triple &TT = getTargetTriple();
120 
121   // DLLImport explicitly marks the GV as external.
122   if (GV && GV->hasDLLImportStorageClass())
123     return false;
124 
125   // Every other GV is local on COFF
126   if (TT.isOSBinFormatCOFF())
127     return true;
128 
129   if (GV && (GV->hasLocalLinkage() || !GV->hasDefaultVisibility()))
130     return true;
131 
132   if (TT.isOSBinFormatMachO()) {
133     if (RM == Reloc::Static)
134       return true;
135     return GV && GV->isStrongDefinitionForLinker();
136   }
137 
138   assert(TT.isOSBinFormatELF());
139   assert(RM != Reloc::DynamicNoPIC);
140 
141   bool IsExecutable =
142       RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
143   if (IsExecutable) {
144     // If the symbol is defined, it cannot be preempted.
145     if (GV && !GV->isDeclarationForLinker())
146       return true;
147 
148     bool IsTLS = GV && GV->isThreadLocal();
149     // Check if we can use copy relocations.
150     if (!IsTLS && (RM == Reloc::Static || CanUseCopyRelocWithPIE))
151       return true;
152   }
153 
154   // ELF supports preemption of other symbols.
155   return false;
156 }
157 
158 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
159   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
160   Reloc::Model RM = getRelocationModel();
161   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
162   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
163 
164   TLSModel::Model Model;
165   if (IsSharedLibrary) {
166     if (IsLocal)
167       Model = TLSModel::LocalDynamic;
168     else
169       Model = TLSModel::GeneralDynamic;
170   } else {
171     if (IsLocal)
172       Model = TLSModel::LocalExec;
173     else
174       Model = TLSModel::InitialExec;
175   }
176 
177   // If the user specified a more specific model, use that.
178   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
179   if (SelectedModel > Model)
180     return SelectedModel;
181 
182   return Model;
183 }
184 
185 /// getOptLevel - Returns the optimization level: None, Less,
186 /// Default, or Aggressive.
187 CodeGenOpt::Level TargetMachine::getOptLevel() const {
188   if (!CodeGenInfo)
189     return CodeGenOpt::Default;
190   return CodeGenInfo->getOptLevel();
191 }
192 
193 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) const {
194   if (CodeGenInfo)
195     CodeGenInfo->setOptLevel(Level);
196 }
197 
198 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
199   return TargetIRAnalysis([this](const Function &F) {
200     return TargetTransformInfo(F.getParent()->getDataLayout());
201   });
202 }
203 
204 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
205                                       const GlobalValue *GV, Mangler &Mang,
206                                       bool MayAlwaysUsePrivate) const {
207   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
208     // Simple case: If GV is not private, it is not important to find out if
209     // private labels are legal in this case or not.
210     Mang.getNameWithPrefix(Name, GV, false);
211     return;
212   }
213   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
214   TLOF->getNameWithPrefix(Name, GV, Mang, *this);
215 }
216 
217 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV, Mangler &Mang) const {
218   SmallString<128> NameStr;
219   getNameWithPrefix(NameStr, GV, Mang);
220   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
221   return TLOF->getContext().getOrCreateSymbol(NameStr);
222 }
223