Bug Summary

File:lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
Warning:line 6748, column 14
Called C++ object pointer is null

Annotated Source Code

1//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SelectionDAGBuilder.h"
15#include "SDNodeDbgValue.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
22#include "llvm/Analysis/ConstantFolding.h"
23#include "llvm/Analysis/Loads.h"
24#include "llvm/Analysis/TargetLibraryInfo.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/Analysis/VectorUtils.h"
27#include "llvm/CodeGen/Analysis.h"
28#include "llvm/CodeGen/FastISel.h"
29#include "llvm/CodeGen/FunctionLoweringInfo.h"
30#include "llvm/CodeGen/GCMetadata.h"
31#include "llvm/CodeGen/GCStrategy.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/SelectionDAG.h"
39#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
40#include "llvm/CodeGen/StackMaps.h"
41#include "llvm/CodeGen/WinEHFuncInfo.h"
42#include "llvm/IR/CallingConv.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DebugInfo.h"
46#include "llvm/IR/DerivedTypes.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GetElementPtrTypeIterator.h"
49#include "llvm/IR/GlobalVariable.h"
50#include "llvm/IR/InlineAsm.h"
51#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Module.h"
56#include "llvm/IR/Statepoint.h"
57#include "llvm/MC/MCSymbol.h"
58#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/MathExtras.h"
62#include "llvm/Support/raw_ostream.h"
63#include "llvm/Target/TargetFrameLowering.h"
64#include "llvm/Target/TargetInstrInfo.h"
65#include "llvm/Target/TargetIntrinsicInfo.h"
66#include "llvm/Target/TargetLowering.h"
67#include "llvm/Target/TargetOptions.h"
68#include "llvm/Target/TargetSubtargetInfo.h"
69#include <algorithm>
70#include <utility>
71using namespace llvm;
72
73#define DEBUG_TYPE"isel" "isel"
74
75/// LimitFloatPrecision - Generate low-precision inline sequences for
76/// some float libcalls (6, 8 or 12 bits).
77static unsigned LimitFloatPrecision;
78
79static cl::opt<unsigned, true>
80LimitFPPrecision("limit-float-precision",
81 cl::desc("Generate low-precision inline sequences "
82 "for some float libcalls"),
83 cl::location(LimitFloatPrecision),
84 cl::init(0));
85
86static cl::opt<bool>
87EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden,
88 cl::desc("Enable fast-math-flags for DAG nodes"));
89
90/// Minimum jump table density for normal functions.
91static cl::opt<unsigned>
92JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
93 cl::desc("Minimum density for building a jump table in "
94 "a normal function"));
95
96/// Minimum jump table density for -Os or -Oz functions.
97static cl::opt<unsigned>
98OptsizeJumpTableDensity("optsize-jump-table-density", cl::init(40), cl::Hidden,
99 cl::desc("Minimum density for building a jump table in "
100 "an optsize function"));
101
102
103// Limit the width of DAG chains. This is important in general to prevent
104// DAG-based analysis from blowing up. For example, alias analysis and
105// load clustering may not complete in reasonable time. It is difficult to
106// recognize and avoid this situation within each individual analysis, and
107// future analyses are likely to have the same behavior. Limiting DAG width is
108// the safe approach and will be especially important with global DAGs.
109//
110// MaxParallelChains default is arbitrarily high to avoid affecting
111// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
112// sequence over this should have been converted to llvm.memcpy by the
113// frontend. It is easy to induce this behavior with .ll code such as:
114// %buffer = alloca [4096 x i8]
115// %data = load [4096 x i8]* %argPtr
116// store [4096 x i8] %data, [4096 x i8]* %buffer
117static const unsigned MaxParallelChains = 64;
118
119static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
120 const SDValue *Parts, unsigned NumParts,
121 MVT PartVT, EVT ValueVT, const Value *V);
122
123/// getCopyFromParts - Create a value that contains the specified legal parts
124/// combined into the value they represent. If the parts combine to a type
125/// larger than ValueVT then AssertOp can be used to specify whether the extra
126/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
127/// (ISD::AssertSext).
128static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
129 const SDValue *Parts, unsigned NumParts,
130 MVT PartVT, EVT ValueVT, const Value *V,
131 Optional<ISD::NodeType> AssertOp = None) {
132 if (ValueVT.isVector())
133 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
134 PartVT, ValueVT, V);
135
136 assert(NumParts > 0 && "No parts to assemble!")((NumParts > 0 && "No parts to assemble!") ? static_cast
<void> (0) : __assert_fail ("NumParts > 0 && \"No parts to assemble!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 136, __PRETTY_FUNCTION__))
;
137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
138 SDValue Val = Parts[0];
139
140 if (NumParts > 1) {
141 // Assemble the value from multiple parts.
142 if (ValueVT.isInteger()) {
143 unsigned PartBits = PartVT.getSizeInBits();
144 unsigned ValueBits = ValueVT.getSizeInBits();
145
146 // Assemble the power of 2 part.
147 unsigned RoundParts = NumParts & (NumParts - 1) ?
148 1 << Log2_32(NumParts) : NumParts;
149 unsigned RoundBits = PartBits * RoundParts;
150 EVT RoundVT = RoundBits == ValueBits ?
151 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
152 SDValue Lo, Hi;
153
154 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
155
156 if (RoundParts > 2) {
157 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
158 PartVT, HalfVT, V);
159 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
160 RoundParts / 2, PartVT, HalfVT, V);
161 } else {
162 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
163 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
164 }
165
166 if (DAG.getDataLayout().isBigEndian())
167 std::swap(Lo, Hi);
168
169 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
170
171 if (RoundParts < NumParts) {
172 // Assemble the trailing non-power-of-2 part.
173 unsigned OddParts = NumParts - RoundParts;
174 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
175 Hi = getCopyFromParts(DAG, DL,
176 Parts + RoundParts, OddParts, PartVT, OddVT, V);
177
178 // Combine the round and odd parts.
179 Lo = Val;
180 if (DAG.getDataLayout().isBigEndian())
181 std::swap(Lo, Hi);
182 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
183 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
184 Hi =
185 DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
186 DAG.getConstant(Lo.getValueSizeInBits(), DL,
187 TLI.getPointerTy(DAG.getDataLayout())));
188 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
189 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
190 }
191 } else if (PartVT.isFloatingPoint()) {
192 // FP split into multiple FP parts (for ppcf128)
193 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&((ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
"Unexpected split") ? static_cast<void> (0) : __assert_fail
("ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && \"Unexpected split\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 194, __PRETTY_FUNCTION__))
194 "Unexpected split")((ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
"Unexpected split") ? static_cast<void> (0) : __assert_fail
("ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && \"Unexpected split\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 194, __PRETTY_FUNCTION__))
;
195 SDValue Lo, Hi;
196 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
197 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
198 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
199 std::swap(Lo, Hi);
200 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
201 } else {
202 // FP split into integer parts (soft fp)
203 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&((ValueVT.isFloatingPoint() && PartVT.isInteger() &&
!PartVT.isVector() && "Unexpected split") ? static_cast
<void> (0) : __assert_fail ("ValueVT.isFloatingPoint() && PartVT.isInteger() && !PartVT.isVector() && \"Unexpected split\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 204, __PRETTY_FUNCTION__))
204 !PartVT.isVector() && "Unexpected split")((ValueVT.isFloatingPoint() && PartVT.isInteger() &&
!PartVT.isVector() && "Unexpected split") ? static_cast
<void> (0) : __assert_fail ("ValueVT.isFloatingPoint() && PartVT.isInteger() && !PartVT.isVector() && \"Unexpected split\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 204, __PRETTY_FUNCTION__))
;
205 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
206 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
207 }
208 }
209
210 // There is now one part, held in Val. Correct it to match ValueVT.
211 // PartEVT is the type of the register class that holds the value.
212 // ValueVT is the type of the inline asm operation.
213 EVT PartEVT = Val.getValueType();
214
215 if (PartEVT == ValueVT)
216 return Val;
217
218 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
219 ValueVT.bitsLT(PartEVT)) {
220 // For an FP value in an integer part, we need to truncate to the right
221 // width first.
222 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
223 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
224 }
225
226 // Handle types that have the same size.
227 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
228 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
229
230 // Handle types with different sizes.
231 if (PartEVT.isInteger() && ValueVT.isInteger()) {
232 if (ValueVT.bitsLT(PartEVT)) {
233 // For a truncate, see if we have any information to
234 // indicate whether the truncated bits will always be
235 // zero or sign-extension.
236 if (AssertOp.hasValue())
237 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
238 DAG.getValueType(ValueVT));
239 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
240 }
241 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
242 }
243
244 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
245 // FP_ROUND's are always exact here.
246 if (ValueVT.bitsLT(Val.getValueType()))
247 return DAG.getNode(
248 ISD::FP_ROUND, DL, ValueVT, Val,
249 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
250
251 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
252 }
253
254 llvm_unreachable("Unknown mismatch!")::llvm::llvm_unreachable_internal("Unknown mismatch!", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 254)
;
255}
256
257static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
258 const Twine &ErrMsg) {
259 const Instruction *I = dyn_cast_or_null<Instruction>(V);
260 if (!V)
261 return Ctx.emitError(ErrMsg);
262
263 const char *AsmError = ", possible invalid constraint for vector type";
264 if (const CallInst *CI = dyn_cast<CallInst>(I))
265 if (isa<InlineAsm>(CI->getCalledValue()))
266 return Ctx.emitError(I, ErrMsg + AsmError);
267
268 return Ctx.emitError(I, ErrMsg);
269}
270
271/// getCopyFromPartsVector - Create a value that contains the specified legal
272/// parts combined into the value they represent. If the parts combine to a
273/// type larger than ValueVT then AssertOp can be used to specify whether the
274/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
275/// ValueVT (ISD::AssertSext).
276static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
277 const SDValue *Parts, unsigned NumParts,
278 MVT PartVT, EVT ValueVT, const Value *V) {
279 assert(ValueVT.isVector() && "Not a vector value")((ValueVT.isVector() && "Not a vector value") ? static_cast
<void> (0) : __assert_fail ("ValueVT.isVector() && \"Not a vector value\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 279, __PRETTY_FUNCTION__))
;
280 assert(NumParts > 0 && "No parts to assemble!")((NumParts > 0 && "No parts to assemble!") ? static_cast
<void> (0) : __assert_fail ("NumParts > 0 && \"No parts to assemble!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 280, __PRETTY_FUNCTION__))
;
281 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
282 SDValue Val = Parts[0];
283
284 // Handle a multi-element vector.
285 if (NumParts > 1) {
286 EVT IntermediateVT;
287 MVT RegisterVT;
288 unsigned NumIntermediates;
289 unsigned NumRegs =
290 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
291 NumIntermediates, RegisterVT);
292 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!")((NumRegs == NumParts && "Part count doesn't match vector breakdown!"
) ? static_cast<void> (0) : __assert_fail ("NumRegs == NumParts && \"Part count doesn't match vector breakdown!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 292, __PRETTY_FUNCTION__))
;
293 NumParts = NumRegs; // Silence a compiler warning.
294 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!")((RegisterVT == PartVT && "Part type doesn't match vector breakdown!"
) ? static_cast<void> (0) : __assert_fail ("RegisterVT == PartVT && \"Part type doesn't match vector breakdown!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 294, __PRETTY_FUNCTION__))
;
295 assert(RegisterVT.getSizeInBits() ==((RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType()
.getSizeInBits() && "Part type sizes don't match!") ?
static_cast<void> (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 297, __PRETTY_FUNCTION__))
296 Parts[0].getSimpleValueType().getSizeInBits() &&((RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType()
.getSizeInBits() && "Part type sizes don't match!") ?
static_cast<void> (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 297, __PRETTY_FUNCTION__))
297 "Part type sizes don't match!")((RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType()
.getSizeInBits() && "Part type sizes don't match!") ?
static_cast<void> (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 297, __PRETTY_FUNCTION__))
;
298
299 // Assemble the parts into intermediate operands.
300 SmallVector<SDValue, 8> Ops(NumIntermediates);
301 if (NumIntermediates == NumParts) {
302 // If the register was not expanded, truncate or copy the value,
303 // as appropriate.
304 for (unsigned i = 0; i != NumParts; ++i)
305 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
306 PartVT, IntermediateVT, V);
307 } else if (NumParts > 0) {
308 // If the intermediate type was expanded, build the intermediate
309 // operands from the parts.
310 assert(NumParts % NumIntermediates == 0 &&((NumParts % NumIntermediates == 0 && "Must expand into a divisible number of parts!"
) ? static_cast<void> (0) : __assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 311, __PRETTY_FUNCTION__))
311 "Must expand into a divisible number of parts!")((NumParts % NumIntermediates == 0 && "Must expand into a divisible number of parts!"
) ? static_cast<void> (0) : __assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 311, __PRETTY_FUNCTION__))
;
312 unsigned Factor = NumParts / NumIntermediates;
313 for (unsigned i = 0; i != NumIntermediates; ++i)
314 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
315 PartVT, IntermediateVT, V);
316 }
317
318 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
319 // intermediate operands.
320 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
321 : ISD::BUILD_VECTOR,
322 DL, ValueVT, Ops);
323 }
324
325 // There is now one part, held in Val. Correct it to match ValueVT.
326 EVT PartEVT = Val.getValueType();
327
328 if (PartEVT == ValueVT)
329 return Val;
330
331 if (PartEVT.isVector()) {
332 // If the element type of the source/dest vectors are the same, but the
333 // parts vector has more elements than the value vector, then we have a
334 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
335 // elements we want.
336 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
337 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&((PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements
() && "Cannot narrow, it would be a lossy transformation"
) ? static_cast<void> (0) : __assert_fail ("PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && \"Cannot narrow, it would be a lossy transformation\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 338, __PRETTY_FUNCTION__))
338 "Cannot narrow, it would be a lossy transformation")((PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements
() && "Cannot narrow, it would be a lossy transformation"
) ? static_cast<void> (0) : __assert_fail ("PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && \"Cannot narrow, it would be a lossy transformation\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 338, __PRETTY_FUNCTION__))
;
339 return DAG.getNode(
340 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
341 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
342 }
343
344 // Vector/Vector bitcast.
345 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
346 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
347
348 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&((PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements
() && "Cannot handle this kind of promotion") ? static_cast
<void> (0) : __assert_fail ("PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && \"Cannot handle this kind of promotion\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 349, __PRETTY_FUNCTION__))
349 "Cannot handle this kind of promotion")((PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements
() && "Cannot handle this kind of promotion") ? static_cast
<void> (0) : __assert_fail ("PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && \"Cannot handle this kind of promotion\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 349, __PRETTY_FUNCTION__))
;
350 // Promoted vector extract
351 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
352
353 }
354
355 // Trivial bitcast if the types are the same size and the destination
356 // vector type is legal.
357 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
358 TLI.isTypeLegal(ValueVT))
359 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
360
361 // Handle cases such as i8 -> <1 x i1>
362 if (ValueVT.getVectorNumElements() != 1) {
363 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
364 "non-trivial scalar-to-vector conversion");
365 return DAG.getUNDEF(ValueVT);
366 }
367
368 if (ValueVT.getVectorNumElements() == 1 &&
369 ValueVT.getVectorElementType() != PartEVT)
370 Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType());
371
372 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
373}
374
375static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
376 SDValue Val, SDValue *Parts, unsigned NumParts,
377 MVT PartVT, const Value *V);
378
379/// getCopyToParts - Create a series of nodes that contain the specified value
380/// split into legal parts. If the parts contain more bits than Val, then, for
381/// integers, ExtendKind can be used to specify how to generate the extra bits.
382static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
383 SDValue *Parts, unsigned NumParts, MVT PartVT,
384 const Value *V,
385 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
386 EVT ValueVT = Val.getValueType();
387
388 // Handle the vector case separately.
389 if (ValueVT.isVector())
390 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
391
392 unsigned PartBits = PartVT.getSizeInBits();
393 unsigned OrigNumParts = NumParts;
394 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&((DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && "Copying to an illegal type!"
) ? static_cast<void> (0) : __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && \"Copying to an illegal type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 395, __PRETTY_FUNCTION__))
395 "Copying to an illegal type!")((DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && "Copying to an illegal type!"
) ? static_cast<void> (0) : __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && \"Copying to an illegal type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 395, __PRETTY_FUNCTION__))
;
396
397 if (NumParts == 0)
398 return;
399
400 assert(!ValueVT.isVector() && "Vector case handled elsewhere")((!ValueVT.isVector() && "Vector case handled elsewhere"
) ? static_cast<void> (0) : __assert_fail ("!ValueVT.isVector() && \"Vector case handled elsewhere\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 400, __PRETTY_FUNCTION__))
;
401 EVT PartEVT = PartVT;
402 if (PartEVT == ValueVT) {
403 assert(NumParts == 1 && "No-op copy with multiple parts!")((NumParts == 1 && "No-op copy with multiple parts!")
? static_cast<void> (0) : __assert_fail ("NumParts == 1 && \"No-op copy with multiple parts!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 403, __PRETTY_FUNCTION__))
;
404 Parts[0] = Val;
405 return;
406 }
407
408 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
409 // If the parts cover more bits than the value has, promote the value.
410 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
411 assert(NumParts == 1 && "Do not know what to promote to!")((NumParts == 1 && "Do not know what to promote to!")
? static_cast<void> (0) : __assert_fail ("NumParts == 1 && \"Do not know what to promote to!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 411, __PRETTY_FUNCTION__))
;
412 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
413 } else {
414 if (ValueVT.isFloatingPoint()) {
415 // FP values need to be bitcast, then extended if they are being put
416 // into a larger container.
417 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
418 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 }
420 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 422, __PRETTY_FUNCTION__))
421 ValueVT.isInteger() &&(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 422, __PRETTY_FUNCTION__))
422 "Unknown mismatch!")(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
424 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
425 if (PartVT == MVT::x86mmx)
426 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
427 }
428 } else if (PartBits == ValueVT.getSizeInBits()) {
429 // Different types of the same size.
430 assert(NumParts == 1 && PartEVT != ValueVT)((NumParts == 1 && PartEVT != ValueVT) ? static_cast<
void> (0) : __assert_fail ("NumParts == 1 && PartEVT != ValueVT"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 430, __PRETTY_FUNCTION__))
;
431 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
432 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
433 // If the parts cover less bits than value has, truncate the value.
434 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 436, __PRETTY_FUNCTION__))
435 ValueVT.isInteger() &&(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 436, __PRETTY_FUNCTION__))
436 "Unknown mismatch!")(((PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT
.isInteger() && "Unknown mismatch!") ? static_cast<
void> (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 436, __PRETTY_FUNCTION__))
;
437 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
438 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
439 if (PartVT == MVT::x86mmx)
440 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
441 }
442
443 // The value may have changed - recompute ValueVT.
444 ValueVT = Val.getValueType();
445 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&((NumParts * PartBits == ValueVT.getSizeInBits() && "Failed to tile the value with PartVT!"
) ? static_cast<void> (0) : __assert_fail ("NumParts * PartBits == ValueVT.getSizeInBits() && \"Failed to tile the value with PartVT!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 446, __PRETTY_FUNCTION__))
446 "Failed to tile the value with PartVT!")((NumParts * PartBits == ValueVT.getSizeInBits() && "Failed to tile the value with PartVT!"
) ? static_cast<void> (0) : __assert_fail ("NumParts * PartBits == ValueVT.getSizeInBits() && \"Failed to tile the value with PartVT!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 446, __PRETTY_FUNCTION__))
;
447
448 if (NumParts == 1) {
449 if (PartEVT != ValueVT) {
450 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
451 "scalar-to-vector conversion failed");
452 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
453 }
454
455 Parts[0] = Val;
456 return;
457 }
458
459 // Expand the value into multiple parts.
460 if (NumParts & (NumParts - 1)) {
461 // The number of parts is not a power of 2. Split off and copy the tail.
462 assert(PartVT.isInteger() && ValueVT.isInteger() &&((PartVT.isInteger() && ValueVT.isInteger() &&
"Do not know what to expand to!") ? static_cast<void> (
0) : __assert_fail ("PartVT.isInteger() && ValueVT.isInteger() && \"Do not know what to expand to!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 463, __PRETTY_FUNCTION__))
463 "Do not know what to expand to!")((PartVT.isInteger() && ValueVT.isInteger() &&
"Do not know what to expand to!") ? static_cast<void> (
0) : __assert_fail ("PartVT.isInteger() && ValueVT.isInteger() && \"Do not know what to expand to!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 463, __PRETTY_FUNCTION__))
;
464 unsigned RoundParts = 1 << Log2_32(NumParts);
465 unsigned RoundBits = RoundParts * PartBits;
466 unsigned OddParts = NumParts - RoundParts;
467 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
468 DAG.getIntPtrConstant(RoundBits, DL));
469 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
470
471 if (DAG.getDataLayout().isBigEndian())
472 // The odd parts were reversed by getCopyToParts - unreverse them.
473 std::reverse(Parts + RoundParts, Parts + NumParts);
474
475 NumParts = RoundParts;
476 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
477 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
478 }
479
480 // The number of parts is a power of 2. Repeatedly bisect the value using
481 // EXTRACT_ELEMENT.
482 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
483 EVT::getIntegerVT(*DAG.getContext(),
484 ValueVT.getSizeInBits()),
485 Val);
486
487 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
488 for (unsigned i = 0; i < NumParts; i += StepSize) {
489 unsigned ThisBits = StepSize * PartBits / 2;
490 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
491 SDValue &Part0 = Parts[i];
492 SDValue &Part1 = Parts[i+StepSize/2];
493
494 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
495 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
496 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
497 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
498
499 if (ThisBits == PartBits && ThisVT != PartVT) {
500 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
501 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
502 }
503 }
504 }
505
506 if (DAG.getDataLayout().isBigEndian())
507 std::reverse(Parts, Parts + OrigNumParts);
508}
509
510
511/// getCopyToPartsVector - Create a series of nodes that contain the specified
512/// value split into legal parts.
513static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
514 SDValue Val, SDValue *Parts, unsigned NumParts,
515 MVT PartVT, const Value *V) {
516 EVT ValueVT = Val.getValueType();
517 assert(ValueVT.isVector() && "Not a vector")((ValueVT.isVector() && "Not a vector") ? static_cast
<void> (0) : __assert_fail ("ValueVT.isVector() && \"Not a vector\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 517, __PRETTY_FUNCTION__))
;
518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
519
520 if (NumParts == 1) {
521 EVT PartEVT = PartVT;
522 if (PartEVT == ValueVT) {
523 // Nothing to do.
524 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
525 // Bitconvert vector->vector case.
526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
527 } else if (PartVT.isVector() &&
528 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
529 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
530 EVT ElementVT = PartVT.getVectorElementType();
531 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
532 // undef elements.
533 SmallVector<SDValue, 16> Ops;
534 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
535 Ops.push_back(DAG.getNode(
536 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
537 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
538
539 for (unsigned i = ValueVT.getVectorNumElements(),
540 e = PartVT.getVectorNumElements(); i != e; ++i)
541 Ops.push_back(DAG.getUNDEF(ElementVT));
542
543 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
544
545 // FIXME: Use CONCAT for 2x -> 4x.
546
547 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
548 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
549 } else if (PartVT.isVector() &&
550 PartEVT.getVectorElementType().bitsGE(
551 ValueVT.getVectorElementType()) &&
552 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
553
554 // Promoted vector extract
555 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
556 } else{
557 // Vector -> scalar conversion.
558 assert(ValueVT.getVectorNumElements() == 1 &&((ValueVT.getVectorNumElements() == 1 && "Only trivial vector-to-scalar conversions should get here!"
) ? static_cast<void> (0) : __assert_fail ("ValueVT.getVectorNumElements() == 1 && \"Only trivial vector-to-scalar conversions should get here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 559, __PRETTY_FUNCTION__))
559 "Only trivial vector-to-scalar conversions should get here!")((ValueVT.getVectorNumElements() == 1 && "Only trivial vector-to-scalar conversions should get here!"
) ? static_cast<void> (0) : __assert_fail ("ValueVT.getVectorNumElements() == 1 && \"Only trivial vector-to-scalar conversions should get here!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 559, __PRETTY_FUNCTION__))
;
560 Val = DAG.getNode(
561 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
562 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
563
564 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
565 }
566
567 Parts[0] = Val;
568 return;
569 }
570
571 // Handle a multi-element vector.
572 EVT IntermediateVT;
573 MVT RegisterVT;
574 unsigned NumIntermediates;
575 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
576 IntermediateVT,
577 NumIntermediates, RegisterVT);
578 unsigned NumElements = ValueVT.getVectorNumElements();
579
580 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!")((NumRegs == NumParts && "Part count doesn't match vector breakdown!"
) ? static_cast<void> (0) : __assert_fail ("NumRegs == NumParts && \"Part count doesn't match vector breakdown!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 580, __PRETTY_FUNCTION__))
;
581 NumParts = NumRegs; // Silence a compiler warning.
582 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!")((RegisterVT == PartVT && "Part type doesn't match vector breakdown!"
) ? static_cast<void> (0) : __assert_fail ("RegisterVT == PartVT && \"Part type doesn't match vector breakdown!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 582, __PRETTY_FUNCTION__))
;
583
584 // Split the vector into intermediate operands.
585 SmallVector<SDValue, 8> Ops(NumIntermediates);
586 for (unsigned i = 0; i != NumIntermediates; ++i) {
587 if (IntermediateVT.isVector())
588 Ops[i] =
589 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
590 DAG.getConstant(i * (NumElements / NumIntermediates), DL,
591 TLI.getVectorIdxTy(DAG.getDataLayout())));
592 else
593 Ops[i] = DAG.getNode(
594 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
595 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
596 }
597
598 // Split the intermediate operands into legal parts.
599 if (NumParts == NumIntermediates) {
600 // If the register was not expanded, promote or copy the value,
601 // as appropriate.
602 for (unsigned i = 0; i != NumParts; ++i)
603 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
604 } else if (NumParts > 0) {
605 // If the intermediate type was expanded, split each the value into
606 // legal parts.
607 assert(NumIntermediates != 0 && "division by zero")((NumIntermediates != 0 && "division by zero") ? static_cast
<void> (0) : __assert_fail ("NumIntermediates != 0 && \"division by zero\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 607, __PRETTY_FUNCTION__))
;
608 assert(NumParts % NumIntermediates == 0 &&((NumParts % NumIntermediates == 0 && "Must expand into a divisible number of parts!"
) ? static_cast<void> (0) : __assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 609, __PRETTY_FUNCTION__))
609 "Must expand into a divisible number of parts!")((NumParts % NumIntermediates == 0 && "Must expand into a divisible number of parts!"
) ? static_cast<void> (0) : __assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 609, __PRETTY_FUNCTION__))
;
610 unsigned Factor = NumParts / NumIntermediates;
611 for (unsigned i = 0; i != NumIntermediates; ++i)
612 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
613 }
614}
615
616RegsForValue::RegsForValue() {}
617
618RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
619 EVT valuevt)
620 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
621
622RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
623 const DataLayout &DL, unsigned Reg, Type *Ty) {
624 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
625
626 for (EVT ValueVT : ValueVTs) {
627 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
628 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
629 for (unsigned i = 0; i != NumRegs; ++i)
630 Regs.push_back(Reg + i);
631 RegVTs.push_back(RegisterVT);
632 Reg += NumRegs;
633 }
634}
635
636/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
637/// this value and returns the result as a ValueVT value. This uses
638/// Chain/Flag as the input and updates them for the output Chain/Flag.
639/// If the Flag pointer is NULL, no flag is used.
640SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
641 FunctionLoweringInfo &FuncInfo,
642 const SDLoc &dl, SDValue &Chain,
643 SDValue *Flag, const Value *V) const {
644 // A Value with type {} or [0 x %t] needs no registers.
645 if (ValueVTs.empty())
646 return SDValue();
647
648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
649
650 // Assemble the legal parts into the final values.
651 SmallVector<SDValue, 4> Values(ValueVTs.size());
652 SmallVector<SDValue, 8> Parts;
653 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
654 // Copy the legal parts from the registers.
655 EVT ValueVT = ValueVTs[Value];
656 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
657 MVT RegisterVT = RegVTs[Value];
658
659 Parts.resize(NumRegs);
660 for (unsigned i = 0; i != NumRegs; ++i) {
661 SDValue P;
662 if (!Flag) {
663 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
664 } else {
665 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
666 *Flag = P.getValue(2);
667 }
668
669 Chain = P.getValue(1);
670 Parts[i] = P;
671
672 // If the source register was virtual and if we know something about it,
673 // add an assert node.
674 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
675 !RegisterVT.isInteger() || RegisterVT.isVector())
676 continue;
677
678 const FunctionLoweringInfo::LiveOutInfo *LOI =
679 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
680 if (!LOI)
681 continue;
682
683 unsigned RegSize = RegisterVT.getSizeInBits();
684 unsigned NumSignBits = LOI->NumSignBits;
685 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
686
687 if (NumZeroBits == RegSize) {
688 // The current value is a zero.
689 // Explicitly express that as it would be easier for
690 // optimizations to kick in.
691 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
692 continue;
693 }
694
695 // FIXME: We capture more information than the dag can represent. For
696 // now, just use the tightest assertzext/assertsext possible.
697 bool isSExt = true;
698 EVT FromVT(MVT::Other);
699 if (NumSignBits == RegSize) {
700 isSExt = true; // ASSERT SEXT 1
701 FromVT = MVT::i1;
702 } else if (NumZeroBits >= RegSize - 1) {
703 isSExt = false; // ASSERT ZEXT 1
704 FromVT = MVT::i1;
705 } else if (NumSignBits > RegSize - 8) {
706 isSExt = true; // ASSERT SEXT 8
707 FromVT = MVT::i8;
708 } else if (NumZeroBits >= RegSize - 8) {
709 isSExt = false; // ASSERT ZEXT 8
710 FromVT = MVT::i8;
711 } else if (NumSignBits > RegSize - 16) {
712 isSExt = true; // ASSERT SEXT 16
713 FromVT = MVT::i16;
714 } else if (NumZeroBits >= RegSize - 16) {
715 isSExt = false; // ASSERT ZEXT 16
716 FromVT = MVT::i16;
717 } else if (NumSignBits > RegSize - 32) {
718 isSExt = true; // ASSERT SEXT 32
719 FromVT = MVT::i32;
720 } else if (NumZeroBits >= RegSize - 32) {
721 isSExt = false; // ASSERT ZEXT 32
722 FromVT = MVT::i32;
723 } else {
724 continue;
725 }
726 // Add an assertion node.
727 assert(FromVT != MVT::Other)((FromVT != MVT::Other) ? static_cast<void> (0) : __assert_fail
("FromVT != MVT::Other", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 727, __PRETTY_FUNCTION__))
;
728 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
729 RegisterVT, P, DAG.getValueType(FromVT));
730 }
731
732 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
733 NumRegs, RegisterVT, ValueVT, V);
734 Part += NumRegs;
735 Parts.clear();
736 }
737
738 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
739}
740
741/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
742/// specified value into the registers specified by this object. This uses
743/// Chain/Flag as the input and updates them for the output Chain/Flag.
744/// If the Flag pointer is NULL, no flag is used.
745void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
746 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
747 const Value *V,
748 ISD::NodeType PreferredExtendType) const {
749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
750 ISD::NodeType ExtendKind = PreferredExtendType;
751
752 // Get the list of the values's legal parts.
753 unsigned NumRegs = Regs.size();
754 SmallVector<SDValue, 8> Parts(NumRegs);
755 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
756 EVT ValueVT = ValueVTs[Value];
757 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
758 MVT RegisterVT = RegVTs[Value];
759
760 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
761 ExtendKind = ISD::ZERO_EXTEND;
762
763 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
764 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
765 Part += NumParts;
766 }
767
768 // Copy the parts into the registers.
769 SmallVector<SDValue, 8> Chains(NumRegs);
770 for (unsigned i = 0; i != NumRegs; ++i) {
771 SDValue Part;
772 if (!Flag) {
773 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
774 } else {
775 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
776 *Flag = Part.getValue(1);
777 }
778
779 Chains[i] = Part.getValue(0);
780 }
781
782 if (NumRegs == 1 || Flag)
783 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
784 // flagged to it. That is the CopyToReg nodes and the user are considered
785 // a single scheduling unit. If we create a TokenFactor and return it as
786 // chain, then the TokenFactor is both a predecessor (operand) of the
787 // user as well as a successor (the TF operands are flagged to the user).
788 // c1, f1 = CopyToReg
789 // c2, f2 = CopyToReg
790 // c3 = TokenFactor c1, c2
791 // ...
792 // = op c3, ..., f2
793 Chain = Chains[NumRegs-1];
794 else
795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
796}
797
798/// AddInlineAsmOperands - Add this value to the specified inlineasm node
799/// operand list. This adds the code marker and includes the number of
800/// values added into it.
801void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
802 unsigned MatchingIdx, const SDLoc &dl,
803 SelectionDAG &DAG,
804 std::vector<SDValue> &Ops) const {
805 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
806
807 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
808 if (HasMatching)
809 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
810 else if (!Regs.empty() &&
811 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
812 // Put the register class of the virtual registers in the flag word. That
813 // way, later passes can recompute register class constraints for inline
814 // assembly as well as normal instructions.
815 // Don't do this for tied operands that can use the regclass information
816 // from the def.
817 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
818 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
819 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
820 }
821
822 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
823 Ops.push_back(Res);
824
825 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
826 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
827 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
828 MVT RegisterVT = RegVTs[Value];
829 for (unsigned i = 0; i != NumRegs; ++i) {
830 assert(Reg < Regs.size() && "Mismatch in # registers expected")((Reg < Regs.size() && "Mismatch in # registers expected"
) ? static_cast<void> (0) : __assert_fail ("Reg < Regs.size() && \"Mismatch in # registers expected\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 830, __PRETTY_FUNCTION__))
;
831 unsigned TheReg = Regs[Reg++];
832 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
833
834 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
835 // If we clobbered the stack pointer, MFI should know about it.
836 assert(DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment())((DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment
()) ? static_cast<void> (0) : __assert_fail ("DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 836, __PRETTY_FUNCTION__))
;
837 }
838 }
839 }
840}
841
842void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
843 const TargetLibraryInfo *li) {
844 AA = &aa;
845 GFI = gfi;
846 LibInfo = li;
847 DL = &DAG.getDataLayout();
848 Context = DAG.getContext();
849 LPadToCallSiteMap.clear();
850}
851
852/// clear - Clear out the current SelectionDAG and the associated
853/// state and prepare this SelectionDAGBuilder object to be used
854/// for a new block. This doesn't clear out information about
855/// additional blocks that are needed to complete switch lowering
856/// or PHI node updating; that information is cleared out as it is
857/// consumed.
858void SelectionDAGBuilder::clear() {
859 NodeMap.clear();
860 UnusedArgNodeMap.clear();
861 PendingLoads.clear();
862 PendingExports.clear();
863 CurInst = nullptr;
864 HasTailCall = false;
865 SDNodeOrder = LowestSDNodeOrder;
866 StatepointLowering.clear();
867}
868
869/// clearDanglingDebugInfo - Clear the dangling debug information
870/// map. This function is separated from the clear so that debug
871/// information that is dangling in a basic block can be properly
872/// resolved in a different basic block. This allows the
873/// SelectionDAG to resolve dangling debug information attached
874/// to PHI nodes.
875void SelectionDAGBuilder::clearDanglingDebugInfo() {
876 DanglingDebugInfoMap.clear();
877}
878
879/// getRoot - Return the current virtual root of the Selection DAG,
880/// flushing any PendingLoad items. This must be done before emitting
881/// a store or any other node that may need to be ordered after any
882/// prior load instructions.
883///
884SDValue SelectionDAGBuilder::getRoot() {
885 if (PendingLoads.empty())
886 return DAG.getRoot();
887
888 if (PendingLoads.size() == 1) {
889 SDValue Root = PendingLoads[0];
890 DAG.setRoot(Root);
891 PendingLoads.clear();
892 return Root;
893 }
894
895 // Otherwise, we have to make a token factor node.
896 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
897 PendingLoads);
898 PendingLoads.clear();
899 DAG.setRoot(Root);
900 return Root;
901}
902
903/// getControlRoot - Similar to getRoot, but instead of flushing all the
904/// PendingLoad items, flush all the PendingExports items. It is necessary
905/// to do this before emitting a terminator instruction.
906///
907SDValue SelectionDAGBuilder::getControlRoot() {
908 SDValue Root = DAG.getRoot();
909
910 if (PendingExports.empty())
911 return Root;
912
913 // Turn all of the CopyToReg chains into one factored node.
914 if (Root.getOpcode() != ISD::EntryToken) {
915 unsigned i = 0, e = PendingExports.size();
916 for (; i != e; ++i) {
917 assert(PendingExports[i].getNode()->getNumOperands() > 1)((PendingExports[i].getNode()->getNumOperands() > 1) ? static_cast
<void> (0) : __assert_fail ("PendingExports[i].getNode()->getNumOperands() > 1"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 917, __PRETTY_FUNCTION__))
;
918 if (PendingExports[i].getNode()->getOperand(0) == Root)
919 break; // Don't add the root if we already indirectly depend on it.
920 }
921
922 if (i == e)
923 PendingExports.push_back(Root);
924 }
925
926 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
927 PendingExports);
928 PendingExports.clear();
929 DAG.setRoot(Root);
930 return Root;
931}
932
933void SelectionDAGBuilder::visit(const Instruction &I) {
934 // Set up outgoing PHI node register values before emitting the terminator.
935 if (isa<TerminatorInst>(&I)) {
936 HandlePHINodesInSuccessorBlocks(I.getParent());
937 }
938
939 ++SDNodeOrder;
940
941 CurInst = &I;
942
943 visit(I.getOpcode(), I);
944
945 if (!isa<TerminatorInst>(&I) && !HasTailCall &&
946 !isStatepoint(&I)) // statepoints handle their exports internally
947 CopyToExportRegsIfNeeded(&I);
948
949 CurInst = nullptr;
950}
951
952void SelectionDAGBuilder::visitPHI(const PHINode &) {
953 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!")::llvm::llvm_unreachable_internal("SelectionDAGBuilder shouldn't visit PHI nodes!"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 953)
;
954}
955
956void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
957 // Note: this doesn't use InstVisitor, because it has to work with
958 // ConstantExpr's in addition to instructions.
959 switch (Opcode) {
960 default: llvm_unreachable("Unknown instruction type encountered!")::llvm::llvm_unreachable_internal("Unknown instruction type encountered!"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 960)
;
961 // Build the switch statement using the Instruction.def file.
962#define HANDLE_INST(NUM, OPCODE, CLASS) \
963 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
964#include "llvm/IR/Instruction.def"
965 }
966}
967
968// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
969// generate the debug data structures now that we've seen its definition.
970void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
971 SDValue Val) {
972 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
973 if (DDI.getDI()) {
974 const DbgValueInst *DI = DDI.getDI();
975 DebugLoc dl = DDI.getdl();
976 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
977 DILocalVariable *Variable = DI->getVariable();
978 DIExpression *Expr = DI->getExpression();
979 assert(Variable->isValidLocationForIntrinsic(dl) &&((Variable->isValidLocationForIntrinsic(dl) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Variable->isValidLocationForIntrinsic(dl) && \"Expected inlined-at fields to agree\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 980, __PRETTY_FUNCTION__))
980 "Expected inlined-at fields to agree")((Variable->isValidLocationForIntrinsic(dl) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Variable->isValidLocationForIntrinsic(dl) && \"Expected inlined-at fields to agree\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 980, __PRETTY_FUNCTION__))
;
981 uint64_t Offset = DI->getOffset();
982 SDDbgValue *SDV;
983 if (Val.getNode()) {
984 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false,
985 Val)) {
986 SDV = getDbgValue(Val, Variable, Expr, Offset, dl, DbgSDNodeOrder);
987 DAG.AddDbgValue(SDV, Val.getNode(), false);
988 }
989 } else
990 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
*DI << "\n"; } } while (false)
;
991 DanglingDebugInfoMap[V] = DanglingDebugInfo();
992 }
993}
994
995/// getCopyFromRegs - If there was virtual register allocated for the value V
996/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
997SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
998 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
999 SDValue Result;
1000
1001 if (It != FuncInfo.ValueMap.end()) {
1002 unsigned InReg = It->second;
1003 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1004 DAG.getDataLayout(), InReg, Ty);
1005 SDValue Chain = DAG.getEntryNode();
1006 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1007 resolveDanglingDebugInfo(V, Result);
1008 }
1009
1010 return Result;
1011}
1012
1013/// getValue - Return an SDValue for the given Value.
1014SDValue SelectionDAGBuilder::getValue(const Value *V) {
1015 // If we already have an SDValue for this value, use it. It's important
1016 // to do this first, so that we don't create a CopyFromReg if we already
1017 // have a regular SDValue.
1018 SDValue &N = NodeMap[V];
1019 if (N.getNode()) return N;
1020
1021 // If there's a virtual register allocated and initialized for this
1022 // value, use it.
1023 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1024 return copyFromReg;
1025
1026 // Otherwise create a new SDValue and remember it.
1027 SDValue Val = getValueImpl(V);
1028 NodeMap[V] = Val;
1029 resolveDanglingDebugInfo(V, Val);
1030 return Val;
1031}
1032
1033// Return true if SDValue exists for the given Value
1034bool SelectionDAGBuilder::findValue(const Value *V) const {
1035 return (NodeMap.find(V) != NodeMap.end()) ||
1036 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1037}
1038
1039/// getNonRegisterValue - Return an SDValue for the given Value, but
1040/// don't look in FuncInfo.ValueMap for a virtual register.
1041SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1042 // If we already have an SDValue for this value, use it.
1043 SDValue &N = NodeMap[V];
1044 if (N.getNode()) {
1045 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1046 // Remove the debug location from the node as the node is about to be used
1047 // in a location which may differ from the original debug location. This
1048 // is relevant to Constant and ConstantFP nodes because they can appear
1049 // as constant expressions inside PHI nodes.
1050 N->setDebugLoc(DebugLoc());
1051 }
1052 return N;
1053 }
1054
1055 // Otherwise create a new SDValue and remember it.
1056 SDValue Val = getValueImpl(V);
1057 NodeMap[V] = Val;
1058 resolveDanglingDebugInfo(V, Val);
1059 return Val;
1060}
1061
1062/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1063/// Create an SDValue for the given value.
1064SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1066
1067 if (const Constant *C = dyn_cast<Constant>(V)) {
1068 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1069
1070 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1071 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1072
1073 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1074 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1075
1076 if (isa<ConstantPointerNull>(C)) {
1077 unsigned AS = V->getType()->getPointerAddressSpace();
1078 return DAG.getConstant(0, getCurSDLoc(),
1079 TLI.getPointerTy(DAG.getDataLayout(), AS));
1080 }
1081
1082 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1083 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1084
1085 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1086 return DAG.getUNDEF(VT);
1087
1088 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1089 visit(CE->getOpcode(), *CE);
1090 SDValue N1 = NodeMap[V];
1091 assert(N1.getNode() && "visit didn't populate the NodeMap!")((N1.getNode() && "visit didn't populate the NodeMap!"
) ? static_cast<void> (0) : __assert_fail ("N1.getNode() && \"visit didn't populate the NodeMap!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1091, __PRETTY_FUNCTION__))
;
1092 return N1;
1093 }
1094
1095 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1096 SmallVector<SDValue, 4> Constants;
1097 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1098 OI != OE; ++OI) {
1099 SDNode *Val = getValue(*OI).getNode();
1100 // If the operand is an empty aggregate, there are no values.
1101 if (!Val) continue;
1102 // Add each leaf value from the operand to the Constants list
1103 // to form a flattened list of all the values.
1104 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1105 Constants.push_back(SDValue(Val, i));
1106 }
1107
1108 return DAG.getMergeValues(Constants, getCurSDLoc());
1109 }
1110
1111 if (const ConstantDataSequential *CDS =
1112 dyn_cast<ConstantDataSequential>(C)) {
1113 SmallVector<SDValue, 4> Ops;
1114 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1115 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1116 // Add each leaf value from the operand to the Constants list
1117 // to form a flattened list of all the values.
1118 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1119 Ops.push_back(SDValue(Val, i));
1120 }
1121
1122 if (isa<ArrayType>(CDS->getType()))
1123 return DAG.getMergeValues(Ops, getCurSDLoc());
1124 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1125 VT, Ops);
1126 }
1127
1128 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1129 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&(((isa<ConstantAggregateZero>(C) || isa<UndefValue>
(C)) && "Unknown struct or array constant!") ? static_cast
<void> (0) : __assert_fail ("(isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && \"Unknown struct or array constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1130, __PRETTY_FUNCTION__))
1130 "Unknown struct or array constant!")(((isa<ConstantAggregateZero>(C) || isa<UndefValue>
(C)) && "Unknown struct or array constant!") ? static_cast
<void> (0) : __assert_fail ("(isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && \"Unknown struct or array constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1130, __PRETTY_FUNCTION__))
;
1131
1132 SmallVector<EVT, 4> ValueVTs;
1133 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1134 unsigned NumElts = ValueVTs.size();
1135 if (NumElts == 0)
1136 return SDValue(); // empty struct
1137 SmallVector<SDValue, 4> Constants(NumElts);
1138 for (unsigned i = 0; i != NumElts; ++i) {
1139 EVT EltVT = ValueVTs[i];
1140 if (isa<UndefValue>(C))
1141 Constants[i] = DAG.getUNDEF(EltVT);
1142 else if (EltVT.isFloatingPoint())
1143 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1144 else
1145 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1146 }
1147
1148 return DAG.getMergeValues(Constants, getCurSDLoc());
1149 }
1150
1151 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1152 return DAG.getBlockAddress(BA, VT);
1153
1154 VectorType *VecTy = cast<VectorType>(V->getType());
1155 unsigned NumElements = VecTy->getNumElements();
1156
1157 // Now that we know the number and type of the elements, get that number of
1158 // elements into the Ops array based on what kind of constant it is.
1159 SmallVector<SDValue, 16> Ops;
1160 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1161 for (unsigned i = 0; i != NumElements; ++i)
1162 Ops.push_back(getValue(CV->getOperand(i)));
1163 } else {
1164 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!")((isa<ConstantAggregateZero>(C) && "Unknown vector constant!"
) ? static_cast<void> (0) : __assert_fail ("isa<ConstantAggregateZero>(C) && \"Unknown vector constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1164, __PRETTY_FUNCTION__))
;
1165 EVT EltVT =
1166 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1167
1168 SDValue Op;
1169 if (EltVT.isFloatingPoint())
1170 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1171 else
1172 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1173 Ops.assign(NumElements, Op);
1174 }
1175
1176 // Create a BUILD_VECTOR node.
1177 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1178 }
1179
1180 // If this is a static alloca, generate it as the frameindex instead of
1181 // computation.
1182 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1183 DenseMap<const AllocaInst*, int>::iterator SI =
1184 FuncInfo.StaticAllocaMap.find(AI);
1185 if (SI != FuncInfo.StaticAllocaMap.end())
1186 return DAG.getFrameIndex(SI->second,
1187 TLI.getPointerTy(DAG.getDataLayout()));
1188 }
1189
1190 // If this is an instruction which fast-isel has deferred, select it now.
1191 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1192 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1193 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1194 Inst->getType());
1195 SDValue Chain = DAG.getEntryNode();
1196 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1197 }
1198
1199 llvm_unreachable("Can't get register for value!")::llvm::llvm_unreachable_internal("Can't get register for value!"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1199)
;
1200}
1201
1202void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1203 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1204 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1205 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1206 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1207 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1208 if (IsMSVCCXX || IsCoreCLR)
1209 CatchPadMBB->setIsEHFuncletEntry();
1210
1211 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1212}
1213
1214void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1215 // Update machine-CFG edge.
1216 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1217 FuncInfo.MBB->addSuccessor(TargetMBB);
1218
1219 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1220 bool IsSEH = isAsynchronousEHPersonality(Pers);
1221 if (IsSEH) {
1222 // If this is not a fall-through branch or optimizations are switched off,
1223 // emit the branch.
1224 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1225 TM.getOptLevel() == CodeGenOpt::None)
1226 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1227 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1228 return;
1229 }
1230
1231 // Figure out the funclet membership for the catchret's successor.
1232 // This will be used by the FuncletLayout pass to determine how to order the
1233 // BB's.
1234 // A 'catchret' returns to the outer scope's color.
1235 Value *ParentPad = I.getCatchSwitchParentPad();
1236 const BasicBlock *SuccessorColor;
1237 if (isa<ConstantTokenNone>(ParentPad))
1238 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1239 else
1240 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1241 assert(SuccessorColor && "No parent funclet for catchret!")((SuccessorColor && "No parent funclet for catchret!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorColor && \"No parent funclet for catchret!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1241, __PRETTY_FUNCTION__))
;
1242 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1243 assert(SuccessorColorMBB && "No MBB for SuccessorColor!")((SuccessorColorMBB && "No MBB for SuccessorColor!") ?
static_cast<void> (0) : __assert_fail ("SuccessorColorMBB && \"No MBB for SuccessorColor!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1243, __PRETTY_FUNCTION__))
;
1244
1245 // Create the terminator node.
1246 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1247 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1248 DAG.getBasicBlock(SuccessorColorMBB));
1249 DAG.setRoot(Ret);
1250}
1251
1252void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1253 // Don't emit any special code for the cleanuppad instruction. It just marks
1254 // the start of a funclet.
1255 FuncInfo.MBB->setIsEHFuncletEntry();
1256 FuncInfo.MBB->setIsCleanupFuncletEntry();
1257}
1258
1259/// When an invoke or a cleanupret unwinds to the next EH pad, there are
1260/// many places it could ultimately go. In the IR, we have a single unwind
1261/// destination, but in the machine CFG, we enumerate all the possible blocks.
1262/// This function skips over imaginary basic blocks that hold catchswitch
1263/// instructions, and finds all the "real" machine
1264/// basic block destinations. As those destinations may not be successors of
1265/// EHPadBB, here we also calculate the edge probability to those destinations.
1266/// The passed-in Prob is the edge probability to EHPadBB.
1267static void findUnwindDestinations(
1268 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1269 BranchProbability Prob,
1270 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1271 &UnwindDests) {
1272 EHPersonality Personality =
1273 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1274 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1275 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1276
1277 while (EHPadBB) {
1278 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1279 BasicBlock *NewEHPadBB = nullptr;
1280 if (isa<LandingPadInst>(Pad)) {
1281 // Stop on landingpads. They are not funclets.
1282 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1283 break;
1284 } else if (isa<CleanupPadInst>(Pad)) {
1285 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1286 // personalities.
1287 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1288 UnwindDests.back().first->setIsEHFuncletEntry();
1289 break;
1290 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1291 // Add the catchpad handlers to the possible destinations.
1292 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1293 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1294 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1295 if (IsMSVCCXX || IsCoreCLR)
1296 UnwindDests.back().first->setIsEHFuncletEntry();
1297 }
1298 NewEHPadBB = CatchSwitch->getUnwindDest();
1299 } else {
1300 continue;
1301 }
1302
1303 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1304 if (BPI && NewEHPadBB)
1305 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1306 EHPadBB = NewEHPadBB;
1307 }
1308}
1309
1310void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1311 // Update successor info.
1312 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1313 auto UnwindDest = I.getUnwindDest();
1314 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1315 BranchProbability UnwindDestProb =
1316 (BPI && UnwindDest)
1317 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1318 : BranchProbability::getZero();
1319 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1320 for (auto &UnwindDest : UnwindDests) {
1321 UnwindDest.first->setIsEHPad();
1322 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1323 }
1324 FuncInfo.MBB->normalizeSuccProbs();
1325
1326 // Create the terminator node.
1327 SDValue Ret =
1328 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1329 DAG.setRoot(Ret);
1330}
1331
1332void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1333 report_fatal_error("visitCatchSwitch not yet implemented!");
1334}
1335
1336void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1338 auto &DL = DAG.getDataLayout();
1339 SDValue Chain = getControlRoot();
1340 SmallVector<ISD::OutputArg, 8> Outs;
1341 SmallVector<SDValue, 8> OutVals;
1342
1343 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1344 // lower
1345 //
1346 // %val = call <ty> @llvm.experimental.deoptimize()
1347 // ret <ty> %val
1348 //
1349 // differently.
1350 if (I.getParent()->getTerminatingDeoptimizeCall()) {
1351 LowerDeoptimizingReturn();
1352 return;
1353 }
1354
1355 if (!FuncInfo.CanLowerReturn) {
1356 unsigned DemoteReg = FuncInfo.DemoteRegister;
1357 const Function *F = I.getParent()->getParent();
1358
1359 // Emit a store of the return value through the virtual register.
1360 // Leave Outs empty so that LowerReturn won't try to load return
1361 // registers the usual way.
1362 SmallVector<EVT, 1> PtrValueVTs;
1363 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1364 PtrValueVTs);
1365
1366 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1367 DemoteReg, PtrValueVTs[0]);
1368 SDValue RetOp = getValue(I.getOperand(0));
1369
1370 SmallVector<EVT, 4> ValueVTs;
1371 SmallVector<uint64_t, 4> Offsets;
1372 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1373 unsigned NumValues = ValueVTs.size();
1374
1375 // An aggregate return value cannot wrap around the address space, so
1376 // offsets to its parts don't wrap either.
1377 SDNodeFlags Flags;
1378 Flags.setNoUnsignedWrap(true);
1379
1380 SmallVector<SDValue, 4> Chains(NumValues);
1381 for (unsigned i = 0; i != NumValues; ++i) {
1382 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1383 RetPtr.getValueType(), RetPtr,
1384 DAG.getIntPtrConstant(Offsets[i],
1385 getCurSDLoc()),
1386 &Flags);
1387 Chains[i] = DAG.getStore(Chain, getCurSDLoc(),
1388 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1389 // FIXME: better loc info would be nice.
1390 Add, MachinePointerInfo());
1391 }
1392
1393 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1394 MVT::Other, Chains);
1395 } else if (I.getNumOperands() != 0) {
1396 SmallVector<EVT, 4> ValueVTs;
1397 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1398 unsigned NumValues = ValueVTs.size();
1399 if (NumValues) {
1400 SDValue RetOp = getValue(I.getOperand(0));
1401
1402 const Function *F = I.getParent()->getParent();
1403
1404 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1405 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1406 Attribute::SExt))
1407 ExtendKind = ISD::SIGN_EXTEND;
1408 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1409 Attribute::ZExt))
1410 ExtendKind = ISD::ZERO_EXTEND;
1411
1412 LLVMContext &Context = F->getContext();
1413 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1414 Attribute::InReg);
1415
1416 for (unsigned j = 0; j != NumValues; ++j) {
1417 EVT VT = ValueVTs[j];
1418
1419 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1420 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1421
1422 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1423 MVT PartVT = TLI.getRegisterType(Context, VT);
1424 SmallVector<SDValue, 4> Parts(NumParts);
1425 getCopyToParts(DAG, getCurSDLoc(),
1426 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1427 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1428
1429 // 'inreg' on function refers to return value
1430 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1431 if (RetInReg)
1432 Flags.setInReg();
1433
1434 // Propagate extension type if any
1435 if (ExtendKind == ISD::SIGN_EXTEND)
1436 Flags.setSExt();
1437 else if (ExtendKind == ISD::ZERO_EXTEND)
1438 Flags.setZExt();
1439
1440 for (unsigned i = 0; i < NumParts; ++i) {
1441 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1442 VT, /*isfixed=*/true, 0, 0));
1443 OutVals.push_back(Parts[i]);
1444 }
1445 }
1446 }
1447 }
1448
1449 // Push in swifterror virtual register as the last element of Outs. This makes
1450 // sure swifterror virtual register will be returned in the swifterror
1451 // physical register.
1452 const Function *F = I.getParent()->getParent();
1453 if (TLI.supportSwiftError() &&
1454 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1455 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument")((FuncInfo.SwiftErrorArg && "Need a swift error argument"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.SwiftErrorArg && \"Need a swift error argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1455, __PRETTY_FUNCTION__))
;
1456 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1457 Flags.setSwiftError();
1458 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1459 EVT(TLI.getPointerTy(DL)) /*argvt*/,
1460 true /*isfixed*/, 1 /*origidx*/,
1461 0 /*partOffs*/));
1462 // Create SDNode for the swifterror virtual register.
1463 OutVals.push_back(DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVReg(
1464 FuncInfo.MBB, FuncInfo.SwiftErrorArg),
1465 EVT(TLI.getPointerTy(DL))));
1466 }
1467
1468 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1469 CallingConv::ID CallConv =
1470 DAG.getMachineFunction().getFunction()->getCallingConv();
1471 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1472 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1473
1474 // Verify that the target's LowerReturn behaved as expected.
1475 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&((Chain.getNode() && Chain.getValueType() == MVT::Other
&& "LowerReturn didn't return a valid chain!") ? static_cast
<void> (0) : __assert_fail ("Chain.getNode() && Chain.getValueType() == MVT::Other && \"LowerReturn didn't return a valid chain!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1476, __PRETTY_FUNCTION__))
1476 "LowerReturn didn't return a valid chain!")((Chain.getNode() && Chain.getValueType() == MVT::Other
&& "LowerReturn didn't return a valid chain!") ? static_cast
<void> (0) : __assert_fail ("Chain.getNode() && Chain.getValueType() == MVT::Other && \"LowerReturn didn't return a valid chain!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1476, __PRETTY_FUNCTION__))
;
1477
1478 // Update the DAG with the new chain value resulting from return lowering.
1479 DAG.setRoot(Chain);
1480}
1481
1482/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1483/// created for it, emit nodes to copy the value into the virtual
1484/// registers.
1485void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1486 // Skip empty types
1487 if (V->getType()->isEmptyTy())
1488 return;
1489
1490 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1491 if (VMI != FuncInfo.ValueMap.end()) {
1492 assert(!V->use_empty() && "Unused value assigned virtual registers!")((!V->use_empty() && "Unused value assigned virtual registers!"
) ? static_cast<void> (0) : __assert_fail ("!V->use_empty() && \"Unused value assigned virtual registers!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1492, __PRETTY_FUNCTION__))
;
1493 CopyValueToVirtualRegister(V, VMI->second);
1494 }
1495}
1496
1497/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1498/// the current basic block, add it to ValueMap now so that we'll get a
1499/// CopyTo/FromReg.
1500void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1501 // No need to export constants.
1502 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1503
1504 // Already exported?
1505 if (FuncInfo.isExportedInst(V)) return;
1506
1507 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1508 CopyValueToVirtualRegister(V, Reg);
1509}
1510
1511bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1512 const BasicBlock *FromBB) {
1513 // The operands of the setcc have to be in this block. We don't know
1514 // how to export them from some other block.
1515 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1516 // Can export from current BB.
1517 if (VI->getParent() == FromBB)
1518 return true;
1519
1520 // Is already exported, noop.
1521 return FuncInfo.isExportedInst(V);
1522 }
1523
1524 // If this is an argument, we can export it if the BB is the entry block or
1525 // if it is already exported.
1526 if (isa<Argument>(V)) {
1527 if (FromBB == &FromBB->getParent()->getEntryBlock())
1528 return true;
1529
1530 // Otherwise, can only export this if it is already exported.
1531 return FuncInfo.isExportedInst(V);
1532 }
1533
1534 // Otherwise, constants can always be exported.
1535 return true;
1536}
1537
1538/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1539BranchProbability
1540SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1541 const MachineBasicBlock *Dst) const {
1542 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1543 const BasicBlock *SrcBB = Src->getBasicBlock();
1544 const BasicBlock *DstBB = Dst->getBasicBlock();
1545 if (!BPI) {
1546 // If BPI is not available, set the default probability as 1 / N, where N is
1547 // the number of successors.
1548 auto SuccSize = std::max<uint32_t>(
1549 std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1550 return BranchProbability(1, SuccSize);
1551 }
1552 return BPI->getEdgeProbability(SrcBB, DstBB);
1553}
1554
1555void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1556 MachineBasicBlock *Dst,
1557 BranchProbability Prob) {
1558 if (!FuncInfo.BPI)
1559 Src->addSuccessorWithoutProb(Dst);
1560 else {
1561 if (Prob.isUnknown())
1562 Prob = getEdgeProbability(Src, Dst);
1563 Src->addSuccessor(Dst, Prob);
1564 }
1565}
1566
1567static bool InBlock(const Value *V, const BasicBlock *BB) {
1568 if (const Instruction *I = dyn_cast<Instruction>(V))
1569 return I->getParent() == BB;
1570 return true;
1571}
1572
1573/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1574/// This function emits a branch and is used at the leaves of an OR or an
1575/// AND operator tree.
1576///
1577void
1578SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1579 MachineBasicBlock *TBB,
1580 MachineBasicBlock *FBB,
1581 MachineBasicBlock *CurBB,
1582 MachineBasicBlock *SwitchBB,
1583 BranchProbability TProb,
1584 BranchProbability FProb) {
1585 const BasicBlock *BB = CurBB->getBasicBlock();
1586
1587 // If the leaf of the tree is a comparison, merge the condition into
1588 // the caseblock.
1589 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1590 // The operands of the cmp have to be in this block. We don't know
1591 // how to export them from some other block. If this is the first block
1592 // of the sequence, no exporting is needed.
1593 if (CurBB == SwitchBB ||
1594 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1595 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1596 ISD::CondCode Condition;
1597 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1598 Condition = getICmpCondCode(IC->getPredicate());
1599 } else {
1600 const FCmpInst *FC = cast<FCmpInst>(Cond);
1601 Condition = getFCmpCondCode(FC->getPredicate());
1602 if (TM.Options.NoNaNsFPMath)
1603 Condition = getFCmpCodeWithoutNaN(Condition);
1604 }
1605
1606 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1607 TBB, FBB, CurBB, TProb, FProb);
1608 SwitchCases.push_back(CB);
1609 return;
1610 }
1611 }
1612
1613 // Create a CaseBlock record representing this branch.
1614 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1615 nullptr, TBB, FBB, CurBB, TProb, FProb);
1616 SwitchCases.push_back(CB);
1617}
1618
1619/// FindMergedConditions - If Cond is an expression like
1620void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1621 MachineBasicBlock *TBB,
1622 MachineBasicBlock *FBB,
1623 MachineBasicBlock *CurBB,
1624 MachineBasicBlock *SwitchBB,
1625 Instruction::BinaryOps Opc,
1626 BranchProbability TProb,
1627 BranchProbability FProb) {
1628 // If this node is not part of the or/and tree, emit it as a branch.
1629 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1630 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1631 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1632 BOp->getParent() != CurBB->getBasicBlock() ||
1633 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1634 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1635 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1636 TProb, FProb);
1637 return;
1638 }
1639
1640 // Create TmpBB after CurBB.
1641 MachineFunction::iterator BBI(CurBB);
1642 MachineFunction &MF = DAG.getMachineFunction();
1643 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1644 CurBB->getParent()->insert(++BBI, TmpBB);
1645
1646 if (Opc == Instruction::Or) {
1647 // Codegen X | Y as:
1648 // BB1:
1649 // jmp_if_X TBB
1650 // jmp TmpBB
1651 // TmpBB:
1652 // jmp_if_Y TBB
1653 // jmp FBB
1654 //
1655
1656 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1657 // The requirement is that
1658 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1659 // = TrueProb for original BB.
1660 // Assuming the original probabilities are A and B, one choice is to set
1661 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1662 // A/(1+B) and 2B/(1+B). This choice assumes that
1663 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1664 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1665 // TmpBB, but the math is more complicated.
1666
1667 auto NewTrueProb = TProb / 2;
1668 auto NewFalseProb = TProb / 2 + FProb;
1669 // Emit the LHS condition.
1670 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1671 NewTrueProb, NewFalseProb);
1672
1673 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1674 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1675 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1676 // Emit the RHS condition into TmpBB.
1677 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1678 Probs[0], Probs[1]);
1679 } else {
1680 assert(Opc == Instruction::And && "Unknown merge op!")((Opc == Instruction::And && "Unknown merge op!") ? static_cast
<void> (0) : __assert_fail ("Opc == Instruction::And && \"Unknown merge op!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1680, __PRETTY_FUNCTION__))
;
1681 // Codegen X & Y as:
1682 // BB1:
1683 // jmp_if_X TmpBB
1684 // jmp FBB
1685 // TmpBB:
1686 // jmp_if_Y TBB
1687 // jmp FBB
1688 //
1689 // This requires creation of TmpBB after CurBB.
1690
1691 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1692 // The requirement is that
1693 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1694 // = FalseProb for original BB.
1695 // Assuming the original probabilities are A and B, one choice is to set
1696 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1697 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1698 // TrueProb for BB1 * FalseProb for TmpBB.
1699
1700 auto NewTrueProb = TProb + FProb / 2;
1701 auto NewFalseProb = FProb / 2;
1702 // Emit the LHS condition.
1703 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1704 NewTrueProb, NewFalseProb);
1705
1706 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1707 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1708 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1709 // Emit the RHS condition into TmpBB.
1710 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1711 Probs[0], Probs[1]);
1712 }
1713}
1714
1715/// If the set of cases should be emitted as a series of branches, return true.
1716/// If we should emit this as a bunch of and/or'd together conditions, return
1717/// false.
1718bool
1719SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1720 if (Cases.size() != 2) return true;
1721
1722 // If this is two comparisons of the same values or'd or and'd together, they
1723 // will get folded into a single comparison, so don't emit two blocks.
1724 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1725 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1726 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1727 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1728 return false;
1729 }
1730
1731 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1732 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1733 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1734 Cases[0].CC == Cases[1].CC &&
1735 isa<Constant>(Cases[0].CmpRHS) &&
1736 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1737 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1738 return false;
1739 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1740 return false;
1741 }
1742
1743 return true;
1744}
1745
1746void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1747 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1748
1749 // Update machine-CFG edges.
1750 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1751
1752 if (I.isUnconditional()) {
1753 // Update machine-CFG edges.
1754 BrMBB->addSuccessor(Succ0MBB);
1755
1756 // If this is not a fall-through branch or optimizations are switched off,
1757 // emit the branch.
1758 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1759 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1760 MVT::Other, getControlRoot(),
1761 DAG.getBasicBlock(Succ0MBB)));
1762
1763 return;
1764 }
1765
1766 // If this condition is one of the special cases we handle, do special stuff
1767 // now.
1768 const Value *CondVal = I.getCondition();
1769 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1770
1771 // If this is a series of conditions that are or'd or and'd together, emit
1772 // this as a sequence of branches instead of setcc's with and/or operations.
1773 // As long as jumps are not expensive, this should improve performance.
1774 // For example, instead of something like:
1775 // cmp A, B
1776 // C = seteq
1777 // cmp D, E
1778 // F = setle
1779 // or C, F
1780 // jnz foo
1781 // Emit:
1782 // cmp A, B
1783 // je foo
1784 // cmp D, E
1785 // jle foo
1786 //
1787 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1788 Instruction::BinaryOps Opcode = BOp->getOpcode();
1789 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1790 !I.getMetadata(LLVMContext::MD_unpredictable) &&
1791 (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1792 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1793 Opcode,
1794 getEdgeProbability(BrMBB, Succ0MBB),
1795 getEdgeProbability(BrMBB, Succ1MBB));
1796 // If the compares in later blocks need to use values not currently
1797 // exported from this block, export them now. This block should always
1798 // be the first entry.
1799 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!")((SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"
) ? static_cast<void> (0) : __assert_fail ("SwitchCases[0].ThisBB == BrMBB && \"Unexpected lowering!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1799, __PRETTY_FUNCTION__))
;
1800
1801 // Allow some cases to be rejected.
1802 if (ShouldEmitAsBranches(SwitchCases)) {
1803 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1804 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1805 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1806 }
1807
1808 // Emit the branch for this block.
1809 visitSwitchCase(SwitchCases[0], BrMBB);
1810 SwitchCases.erase(SwitchCases.begin());
1811 return;
1812 }
1813
1814 // Okay, we decided not to do this, remove any inserted MBB's and clear
1815 // SwitchCases.
1816 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1817 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1818
1819 SwitchCases.clear();
1820 }
1821 }
1822
1823 // Create a CaseBlock record representing this branch.
1824 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1825 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1826
1827 // Use visitSwitchCase to actually insert the fast branch sequence for this
1828 // cond branch.
1829 visitSwitchCase(CB, BrMBB);
1830}
1831
1832/// visitSwitchCase - Emits the necessary code to represent a single node in
1833/// the binary search tree resulting from lowering a switch instruction.
1834void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1835 MachineBasicBlock *SwitchBB) {
1836 SDValue Cond;
1837 SDValue CondLHS = getValue(CB.CmpLHS);
1838 SDLoc dl = getCurSDLoc();
1839
1840 // Build the setcc now.
1841 if (!CB.CmpMHS) {
1842 // Fold "(X == true)" to X and "(X == false)" to !X to
1843 // handle common cases produced by branch lowering.
1844 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1845 CB.CC == ISD::SETEQ)
1846 Cond = CondLHS;
1847 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1848 CB.CC == ISD::SETEQ) {
1849 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1850 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1851 } else
1852 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1853 } else {
1854 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now")((CB.CC == ISD::SETLE && "Can handle only LE ranges now"
) ? static_cast<void> (0) : __assert_fail ("CB.CC == ISD::SETLE && \"Can handle only LE ranges now\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1854, __PRETTY_FUNCTION__))
;
1855
1856 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1857 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1858
1859 SDValue CmpOp = getValue(CB.CmpMHS);
1860 EVT VT = CmpOp.getValueType();
1861
1862 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1863 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1864 ISD::SETLE);
1865 } else {
1866 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1867 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1868 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1869 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1870 }
1871 }
1872
1873 // Update successor info
1874 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
1875 // TrueBB and FalseBB are always different unless the incoming IR is
1876 // degenerate. This only happens when running llc on weird IR.
1877 if (CB.TrueBB != CB.FalseBB)
1878 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
1879 SwitchBB->normalizeSuccProbs();
1880
1881 // If the lhs block is the next block, invert the condition so that we can
1882 // fall through to the lhs instead of the rhs block.
1883 if (CB.TrueBB == NextBlock(SwitchBB)) {
1884 std::swap(CB.TrueBB, CB.FalseBB);
1885 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1886 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1887 }
1888
1889 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1890 MVT::Other, getControlRoot(), Cond,
1891 DAG.getBasicBlock(CB.TrueBB));
1892
1893 // Insert the false branch. Do this even if it's a fall through branch,
1894 // this makes it easier to do DAG optimizations which require inverting
1895 // the branch condition.
1896 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1897 DAG.getBasicBlock(CB.FalseBB));
1898
1899 DAG.setRoot(BrCond);
1900}
1901
1902/// visitJumpTable - Emit JumpTable node in the current MBB
1903void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1904 // Emit the code for the jump table
1905 assert(JT.Reg != -1U && "Should lower JT Header first!")((JT.Reg != -1U && "Should lower JT Header first!") ?
static_cast<void> (0) : __assert_fail ("JT.Reg != -1U && \"Should lower JT Header first!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1905, __PRETTY_FUNCTION__))
;
1906 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1907 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1908 JT.Reg, PTy);
1909 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1910 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1911 MVT::Other, Index.getValue(1),
1912 Table, Index);
1913 DAG.setRoot(BrJumpTable);
1914}
1915
1916/// visitJumpTableHeader - This function emits necessary code to produce index
1917/// in the JumpTable from switch case.
1918void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1919 JumpTableHeader &JTH,
1920 MachineBasicBlock *SwitchBB) {
1921 SDLoc dl = getCurSDLoc();
1922
1923 // Subtract the lowest switch case value from the value being switched on and
1924 // conditional branch to default mbb if the result is greater than the
1925 // difference between smallest and largest cases.
1926 SDValue SwitchOp = getValue(JTH.SValue);
1927 EVT VT = SwitchOp.getValueType();
1928 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1929 DAG.getConstant(JTH.First, dl, VT));
1930
1931 // The SDNode we just created, which holds the value being switched on minus
1932 // the smallest case value, needs to be copied to a virtual register so it
1933 // can be used as an index into the jump table in a subsequent basic block.
1934 // This value may be smaller or larger than the target's pointer type, and
1935 // therefore require extension or truncating.
1936 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1937 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
1938
1939 unsigned JumpTableReg =
1940 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
1941 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1942 JumpTableReg, SwitchOp);
1943 JT.Reg = JumpTableReg;
1944
1945 // Emit the range check for the jump table, and branch to the default block
1946 // for the switch statement if the value being switched on exceeds the largest
1947 // case in the switch.
1948 SDValue CMP = DAG.getSetCC(
1949 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1950 Sub.getValueType()),
1951 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
1952
1953 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1954 MVT::Other, CopyTo, CMP,
1955 DAG.getBasicBlock(JT.Default));
1956
1957 // Avoid emitting unnecessary branches to the next block.
1958 if (JT.MBB != NextBlock(SwitchBB))
1959 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1960 DAG.getBasicBlock(JT.MBB));
1961
1962 DAG.setRoot(BrCond);
1963}
1964
1965/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
1966/// variable if there exists one.
1967static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
1968 SDValue &Chain) {
1969 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1970 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent());
1973 MachineSDNode *Node =
1974 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
1975 if (Global) {
1976 MachinePointerInfo MPInfo(Global);
1977 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
1978 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1979 MachineMemOperand::MODereferenceable;
1980 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
1981 DAG.getEVTAlignment(PtrTy));
1982 Node->setMemRefs(MemRefs, MemRefs + 1);
1983 }
1984 return SDValue(Node, 0);
1985}
1986
1987/// Codegen a new tail for a stack protector check ParentMBB which has had its
1988/// tail spliced into a stack protector check success bb.
1989///
1990/// For a high level explanation of how this fits into the stack protector
1991/// generation see the comment on the declaration of class
1992/// StackProtectorDescriptor.
1993void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1994 MachineBasicBlock *ParentBB) {
1995
1996 // First create the loads to the guard/stack slot for the comparison.
1997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1998 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
1999
2000 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2001 int FI = MFI.getStackProtectorIndex();
2002
2003 SDValue Guard;
2004 SDLoc dl = getCurSDLoc();
2005 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2006 const Module &M = *ParentBB->getParent()->getFunction()->getParent();
2007 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2008
2009 // Generate code to load the content of the guard slot.
2010 SDValue StackSlot = DAG.getLoad(
2011 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2012 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2013 MachineMemOperand::MOVolatile);
2014
2015 // Retrieve guard check function, nullptr if instrumentation is inlined.
2016 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2017 // The target provides a guard check function to validate the guard value.
2018 // Generate a call to that function with the content of the guard slot as
2019 // argument.
2020 auto *Fn = cast<Function>(GuardCheck);
2021 FunctionType *FnTy = Fn->getFunctionType();
2022 assert(FnTy->getNumParams() == 1 && "Invalid function signature")((FnTy->getNumParams() == 1 && "Invalid function signature"
) ? static_cast<void> (0) : __assert_fail ("FnTy->getNumParams() == 1 && \"Invalid function signature\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2022, __PRETTY_FUNCTION__))
;
2023
2024 TargetLowering::ArgListTy Args;
2025 TargetLowering::ArgListEntry Entry;
2026 Entry.Node = StackSlot;
2027 Entry.Ty = FnTy->getParamType(0);
2028 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2029 Entry.isInReg = true;
2030 Args.push_back(Entry);
2031
2032 TargetLowering::CallLoweringInfo CLI(DAG);
2033 CLI.setDebugLoc(getCurSDLoc())
2034 .setChain(DAG.getEntryNode())
2035 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2036 getValue(GuardCheck), std::move(Args));
2037
2038 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2039 DAG.setRoot(Result.second);
2040 return;
2041 }
2042
2043 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2044 // Otherwise, emit a volatile load to retrieve the stack guard value.
2045 SDValue Chain = DAG.getEntryNode();
2046 if (TLI.useLoadStackGuardNode()) {
2047 Guard = getLoadStackGuard(DAG, dl, Chain);
2048 } else {
2049 const Value *IRGuard = TLI.getSDagStackGuard(M);
2050 SDValue GuardPtr = getValue(IRGuard);
2051
2052 Guard =
2053 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2054 Align, MachineMemOperand::MOVolatile);
2055 }
2056
2057 // Perform the comparison via a subtract/getsetcc.
2058 EVT VT = Guard.getValueType();
2059 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
2060
2061 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2062 *DAG.getContext(),
2063 Sub.getValueType()),
2064 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2065
2066 // If the sub is not 0, then we know the guard/stackslot do not equal, so
2067 // branch to failure MBB.
2068 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2069 MVT::Other, StackSlot.getOperand(0),
2070 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2071 // Otherwise branch to success MBB.
2072 SDValue Br = DAG.getNode(ISD::BR, dl,
2073 MVT::Other, BrCond,
2074 DAG.getBasicBlock(SPD.getSuccessMBB()));
2075
2076 DAG.setRoot(Br);
2077}
2078
2079/// Codegen the failure basic block for a stack protector check.
2080///
2081/// A failure stack protector machine basic block consists simply of a call to
2082/// __stack_chk_fail().
2083///
2084/// For a high level explanation of how this fits into the stack protector
2085/// generation see the comment on the declaration of class
2086/// StackProtectorDescriptor.
2087void
2088SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2090 SDValue Chain =
2091 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2092 None, false, getCurSDLoc(), false, false).second;
2093 DAG.setRoot(Chain);
2094}
2095
2096/// visitBitTestHeader - This function emits necessary code to produce value
2097/// suitable for "bit tests"
2098void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2099 MachineBasicBlock *SwitchBB) {
2100 SDLoc dl = getCurSDLoc();
2101
2102 // Subtract the minimum value
2103 SDValue SwitchOp = getValue(B.SValue);
2104 EVT VT = SwitchOp.getValueType();
2105 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2106 DAG.getConstant(B.First, dl, VT));
2107
2108 // Check range
2109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2110 SDValue RangeCmp = DAG.getSetCC(
2111 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2112 Sub.getValueType()),
2113 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2114
2115 // Determine the type of the test operands.
2116 bool UsePtrType = false;
2117 if (!TLI.isTypeLegal(VT))
2118 UsePtrType = true;
2119 else {
2120 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2121 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2122 // Switch table case range are encoded into series of masks.
2123 // Just use pointer type, it's guaranteed to fit.
2124 UsePtrType = true;
2125 break;
2126 }
2127 }
2128 if (UsePtrType) {
2129 VT = TLI.getPointerTy(DAG.getDataLayout());
2130 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2131 }
2132
2133 B.RegVT = VT.getSimpleVT();
2134 B.Reg = FuncInfo.CreateReg(B.RegVT);
2135 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2136
2137 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2138
2139 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2140 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2141 SwitchBB->normalizeSuccProbs();
2142
2143 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2144 MVT::Other, CopyTo, RangeCmp,
2145 DAG.getBasicBlock(B.Default));
2146
2147 // Avoid emitting unnecessary branches to the next block.
2148 if (MBB != NextBlock(SwitchBB))
2149 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2150 DAG.getBasicBlock(MBB));
2151
2152 DAG.setRoot(BrRange);
2153}
2154
2155/// visitBitTestCase - this function produces one "bit test"
2156void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2157 MachineBasicBlock* NextMBB,
2158 BranchProbability BranchProbToNext,
2159 unsigned Reg,
2160 BitTestCase &B,
2161 MachineBasicBlock *SwitchBB) {
2162 SDLoc dl = getCurSDLoc();
2163 MVT VT = BB.RegVT;
2164 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2165 SDValue Cmp;
2166 unsigned PopCount = countPopulation(B.Mask);
2167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2168 if (PopCount == 1) {
2169 // Testing for a single bit; just compare the shift count with what it
2170 // would need to be to shift a 1 bit in that position.
2171 Cmp = DAG.getSetCC(
2172 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2173 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2174 ISD::SETEQ);
2175 } else if (PopCount == BB.Range) {
2176 // There is only one zero bit in the range, test for it directly.
2177 Cmp = DAG.getSetCC(
2178 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2179 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2180 ISD::SETNE);
2181 } else {
2182 // Make desired shift
2183 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2184 DAG.getConstant(1, dl, VT), ShiftOp);
2185
2186 // Emit bit tests and jumps
2187 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2188 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2189 Cmp = DAG.getSetCC(
2190 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2191 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2192 }
2193
2194 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2195 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2196 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2197 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2198 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2199 // one as they are relative probabilities (and thus work more like weights),
2200 // and hence we need to normalize them to let the sum of them become one.
2201 SwitchBB->normalizeSuccProbs();
2202
2203 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2204 MVT::Other, getControlRoot(),
2205 Cmp, DAG.getBasicBlock(B.TargetBB));
2206
2207 // Avoid emitting unnecessary branches to the next block.
2208 if (NextMBB != NextBlock(SwitchBB))
2209 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2210 DAG.getBasicBlock(NextMBB));
2211
2212 DAG.setRoot(BrAnd);
2213}
2214
2215void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2216 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2217
2218 // Retrieve successors. Look through artificial IR level blocks like
2219 // catchswitch for successors.
2220 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2221 const BasicBlock *EHPadBB = I.getSuccessor(1);
2222
2223 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2224 // have to do anything here to lower funclet bundles.
2225 assert(!I.hasOperandBundlesOtherThan(((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2227, __PRETTY_FUNCTION__))
2226 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2227, __PRETTY_FUNCTION__))
2227 "Cannot lower invokes with arbitrary operand bundles yet!")((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2227, __PRETTY_FUNCTION__))
;
2228
2229 const Value *Callee(I.getCalledValue());
2230 const Function *Fn = dyn_cast<Function>(Callee);
2231 if (isa<InlineAsm>(Callee))
2232 visitInlineAsm(&I);
2233 else if (Fn && Fn->isIntrinsic()) {
2234 switch (Fn->getIntrinsicID()) {
2235 default:
2236 llvm_unreachable("Cannot invoke this intrinsic")::llvm::llvm_unreachable_internal("Cannot invoke this intrinsic"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2236)
;
2237 case Intrinsic::donothing:
2238 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2239 break;
2240 case Intrinsic::experimental_patchpoint_void:
2241 case Intrinsic::experimental_patchpoint_i64:
2242 visitPatchpoint(&I, EHPadBB);
2243 break;
2244 case Intrinsic::experimental_gc_statepoint:
2245 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2246 break;
2247 }
2248 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2249 // Currently we do not lower any intrinsic calls with deopt operand bundles.
2250 // Eventually we will support lowering the @llvm.experimental.deoptimize
2251 // intrinsic, and right now there are no plans to support other intrinsics
2252 // with deopt state.
2253 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2254 } else {
2255 LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2256 }
2257
2258 // If the value of the invoke is used outside of its defining block, make it
2259 // available as a virtual register.
2260 // We already took care of the exported value for the statepoint instruction
2261 // during call to the LowerStatepoint.
2262 if (!isStatepoint(I)) {
2263 CopyToExportRegsIfNeeded(&I);
2264 }
2265
2266 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2267 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2268 BranchProbability EHPadBBProb =
2269 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2270 : BranchProbability::getZero();
2271 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2272
2273 // Update successor info.
2274 addSuccessorWithProb(InvokeMBB, Return);
2275 for (auto &UnwindDest : UnwindDests) {
2276 UnwindDest.first->setIsEHPad();
2277 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2278 }
2279 InvokeMBB->normalizeSuccProbs();
2280
2281 // Drop into normal successor.
2282 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2283 MVT::Other, getControlRoot(),
2284 DAG.getBasicBlock(Return)));
2285}
2286
2287void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2288 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!")::llvm::llvm_unreachable_internal("SelectionDAGBuilder shouldn't visit resume instructions!"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2288)
;
2289}
2290
2291void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2292 assert(FuncInfo.MBB->isEHPad() &&((FuncInfo.MBB->isEHPad() && "Call to landingpad not in landing pad!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.MBB->isEHPad() && \"Call to landingpad not in landing pad!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2293, __PRETTY_FUNCTION__))
2293 "Call to landingpad not in landing pad!")((FuncInfo.MBB->isEHPad() && "Call to landingpad not in landing pad!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.MBB->isEHPad() && \"Call to landingpad not in landing pad!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2293, __PRETTY_FUNCTION__))
;
2294
2295 MachineBasicBlock *MBB = FuncInfo.MBB;
2296 addLandingPadInfo(LP, *MBB);
2297
2298 // If there aren't registers to copy the values into (e.g., during SjLj
2299 // exceptions), then don't bother to create these DAG nodes.
2300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2301 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2302 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2303 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2304 return;
2305
2306 // If landingpad's return type is token type, we don't create DAG nodes
2307 // for its exception pointer and selector value. The extraction of exception
2308 // pointer or selector value from token type landingpads is not currently
2309 // supported.
2310 if (LP.getType()->isTokenTy())
2311 return;
2312
2313 SmallVector<EVT, 2> ValueVTs;
2314 SDLoc dl = getCurSDLoc();
2315 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2316 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported")((ValueVTs.size() == 2 && "Only two-valued landingpads are supported"
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 2 && \"Only two-valued landingpads are supported\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2316, __PRETTY_FUNCTION__))
;
2317
2318 // Get the two live-in registers as SDValues. The physregs have already been
2319 // copied into virtual registers.
2320 SDValue Ops[2];
2321 if (FuncInfo.ExceptionPointerVirtReg) {
2322 Ops[0] = DAG.getZExtOrTrunc(
2323 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2324 FuncInfo.ExceptionPointerVirtReg,
2325 TLI.getPointerTy(DAG.getDataLayout())),
2326 dl, ValueVTs[0]);
2327 } else {
2328 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2329 }
2330 Ops[1] = DAG.getZExtOrTrunc(
2331 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2332 FuncInfo.ExceptionSelectorVirtReg,
2333 TLI.getPointerTy(DAG.getDataLayout())),
2334 dl, ValueVTs[1]);
2335
2336 // Merge into one.
2337 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2338 DAG.getVTList(ValueVTs), Ops);
2339 setValue(&LP, Res);
2340}
2341
2342void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2343#ifndef NDEBUG
2344 for (const CaseCluster &CC : Clusters)
2345 assert(CC.Low == CC.High && "Input clusters must be single-case")((CC.Low == CC.High && "Input clusters must be single-case"
) ? static_cast<void> (0) : __assert_fail ("CC.Low == CC.High && \"Input clusters must be single-case\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2345, __PRETTY_FUNCTION__))
;
2346#endif
2347
2348 std::sort(Clusters.begin(), Clusters.end(),
2349 [](const CaseCluster &a, const CaseCluster &b) {
2350 return a.Low->getValue().slt(b.Low->getValue());
2351 });
2352
2353 // Merge adjacent clusters with the same destination.
2354 const unsigned N = Clusters.size();
2355 unsigned DstIndex = 0;
2356 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2357 CaseCluster &CC = Clusters[SrcIndex];
2358 const ConstantInt *CaseVal = CC.Low;
2359 MachineBasicBlock *Succ = CC.MBB;
2360
2361 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2362 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2363 // If this case has the same successor and is a neighbour, merge it into
2364 // the previous cluster.
2365 Clusters[DstIndex - 1].High = CaseVal;
2366 Clusters[DstIndex - 1].Prob += CC.Prob;
2367 } else {
2368 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2369 sizeof(Clusters[SrcIndex]));
2370 }
2371 }
2372 Clusters.resize(DstIndex);
2373}
2374
2375void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2376 MachineBasicBlock *Last) {
2377 // Update JTCases.
2378 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2379 if (JTCases[i].first.HeaderBB == First)
2380 JTCases[i].first.HeaderBB = Last;
2381
2382 // Update BitTestCases.
2383 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2384 if (BitTestCases[i].Parent == First)
2385 BitTestCases[i].Parent = Last;
2386}
2387
2388void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2389 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2390
2391 // Update machine-CFG edges with unique successors.
2392 SmallSet<BasicBlock*, 32> Done;
2393 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2394 BasicBlock *BB = I.getSuccessor(i);
2395 bool Inserted = Done.insert(BB).second;
2396 if (!Inserted)
2397 continue;
2398
2399 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2400 addSuccessorWithProb(IndirectBrMBB, Succ);
2401 }
2402 IndirectBrMBB->normalizeSuccProbs();
2403
2404 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2405 MVT::Other, getControlRoot(),
2406 getValue(I.getAddress())));
2407}
2408
2409void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2410 if (DAG.getTarget().Options.TrapUnreachable)
2411 DAG.setRoot(
2412 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2413}
2414
2415void SelectionDAGBuilder::visitFSub(const User &I) {
2416 // -0.0 - X --> fneg
2417 Type *Ty = I.getType();
2418 if (isa<Constant>(I.getOperand(0)) &&
2419 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2420 SDValue Op2 = getValue(I.getOperand(1));
2421 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2422 Op2.getValueType(), Op2));
2423 return;
2424 }
2425
2426 visitBinary(I, ISD::FSUB);
2427}
2428
2429/// Checks if the given instruction performs a vector reduction, in which case
2430/// we have the freedom to alter the elements in the result as long as the
2431/// reduction of them stays unchanged.
2432static bool isVectorReductionOp(const User *I) {
2433 const Instruction *Inst = dyn_cast<Instruction>(I);
2434 if (!Inst || !Inst->getType()->isVectorTy())
2435 return false;
2436
2437 auto OpCode = Inst->getOpcode();
2438 switch (OpCode) {
2439 case Instruction::Add:
2440 case Instruction::Mul:
2441 case Instruction::And:
2442 case Instruction::Or:
2443 case Instruction::Xor:
2444 break;
2445 case Instruction::FAdd:
2446 case Instruction::FMul:
2447 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2448 if (FPOp->getFastMathFlags().unsafeAlgebra())
2449 break;
2450 LLVM_FALLTHROUGH[[clang::fallthrough]];
2451 default:
2452 return false;
2453 }
2454
2455 unsigned ElemNum = Inst->getType()->getVectorNumElements();
2456 unsigned ElemNumToReduce = ElemNum;
2457
2458 // Do DFS search on the def-use chain from the given instruction. We only
2459 // allow four kinds of operations during the search until we reach the
2460 // instruction that extracts the first element from the vector:
2461 //
2462 // 1. The reduction operation of the same opcode as the given instruction.
2463 //
2464 // 2. PHI node.
2465 //
2466 // 3. ShuffleVector instruction together with a reduction operation that
2467 // does a partial reduction.
2468 //
2469 // 4. ExtractElement that extracts the first element from the vector, and we
2470 // stop searching the def-use chain here.
2471 //
2472 // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2473 // from 1-3 to the stack to continue the DFS. The given instruction is not
2474 // a reduction operation if we meet any other instructions other than those
2475 // listed above.
2476
2477 SmallVector<const User *, 16> UsersToVisit{Inst};
2478 SmallPtrSet<const User *, 16> Visited;
2479 bool ReduxExtracted = false;
2480
2481 while (!UsersToVisit.empty()) {
2482 auto User = UsersToVisit.back();
2483 UsersToVisit.pop_back();
2484 if (!Visited.insert(User).second)
2485 continue;
2486
2487 for (const auto &U : User->users()) {
2488 auto Inst = dyn_cast<Instruction>(U);
2489 if (!Inst)
2490 return false;
2491
2492 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2493 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2494 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
2495 return false;
2496 UsersToVisit.push_back(U);
2497 } else if (const ShuffleVectorInst *ShufInst =
2498 dyn_cast<ShuffleVectorInst>(U)) {
2499 // Detect the following pattern: A ShuffleVector instruction together
2500 // with a reduction that do partial reduction on the first and second
2501 // ElemNumToReduce / 2 elements, and store the result in
2502 // ElemNumToReduce / 2 elements in another vector.
2503
2504 unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2505 if (ResultElements < ElemNum)
2506 return false;
2507
2508 if (ElemNumToReduce == 1)
2509 return false;
2510 if (!isa<UndefValue>(U->getOperand(1)))
2511 return false;
2512 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2513 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2514 return false;
2515 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2516 if (ShufInst->getMaskValue(i) != -1)
2517 return false;
2518
2519 // There is only one user of this ShuffleVector instruction, which
2520 // must be a reduction operation.
2521 if (!U->hasOneUse())
2522 return false;
2523
2524 auto U2 = dyn_cast<Instruction>(*U->user_begin());
2525 if (!U2 || U2->getOpcode() != OpCode)
2526 return false;
2527
2528 // Check operands of the reduction operation.
2529 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2530 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2531 UsersToVisit.push_back(U2);
2532 ElemNumToReduce /= 2;
2533 } else
2534 return false;
2535 } else if (isa<ExtractElementInst>(U)) {
2536 // At this moment we should have reduced all elements in the vector.
2537 if (ElemNumToReduce != 1)
2538 return false;
2539
2540 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2541 if (!Val || Val->getZExtValue() != 0)
2542 return false;
2543
2544 ReduxExtracted = true;
2545 } else
2546 return false;
2547 }
2548 }
2549 return ReduxExtracted;
2550}
2551
2552void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2553 SDValue Op1 = getValue(I.getOperand(0));
2554 SDValue Op2 = getValue(I.getOperand(1));
2555
2556 bool nuw = false;
2557 bool nsw = false;
2558 bool exact = false;
2559 bool vec_redux = false;
2560 FastMathFlags FMF;
2561
2562 if (const OverflowingBinaryOperator *OFBinOp =
2563 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2564 nuw = OFBinOp->hasNoUnsignedWrap();
2565 nsw = OFBinOp->hasNoSignedWrap();
2566 }
2567 if (const PossiblyExactOperator *ExactOp =
2568 dyn_cast<const PossiblyExactOperator>(&I))
2569 exact = ExactOp->isExact();
2570 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2571 FMF = FPOp->getFastMathFlags();
2572
2573 if (isVectorReductionOp(&I)) {
2574 vec_redux = true;
2575 DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Detected a reduction operation:"
<< I << "\n"; } } while (false)
;
2576 }
2577
2578 SDNodeFlags Flags;
2579 Flags.setExact(exact);
2580 Flags.setNoSignedWrap(nsw);
2581 Flags.setNoUnsignedWrap(nuw);
2582 Flags.setVectorReduction(vec_redux);
2583 if (EnableFMFInDAG) {
2584 Flags.setAllowReciprocal(FMF.allowReciprocal());
2585 Flags.setNoInfs(FMF.noInfs());
2586 Flags.setNoNaNs(FMF.noNaNs());
2587 Flags.setNoSignedZeros(FMF.noSignedZeros());
2588 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2589 }
2590 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2591 Op1, Op2, &Flags);
2592 setValue(&I, BinNodeValue);
2593}
2594
2595void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2596 SDValue Op1 = getValue(I.getOperand(0));
2597 SDValue Op2 = getValue(I.getOperand(1));
2598
2599 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2600 Op2.getValueType(), DAG.getDataLayout());
2601
2602 // Coerce the shift amount to the right type if we can.
2603 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2604 unsigned ShiftSize = ShiftTy.getSizeInBits();
2605 unsigned Op2Size = Op2.getValueSizeInBits();
2606 SDLoc DL = getCurSDLoc();
2607
2608 // If the operand is smaller than the shift count type, promote it.
2609 if (ShiftSize > Op2Size)
2610 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2611
2612 // If the operand is larger than the shift count type but the shift
2613 // count type has enough bits to represent any shift value, truncate
2614 // it now. This is a common case and it exposes the truncate to
2615 // optimization early.
2616 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2617 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2618 // Otherwise we'll need to temporarily settle for some other convenient
2619 // type. Type legalization will make adjustments once the shiftee is split.
2620 else
2621 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2622 }
2623
2624 bool nuw = false;
2625 bool nsw = false;
2626 bool exact = false;
2627
2628 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2629
2630 if (const OverflowingBinaryOperator *OFBinOp =
2631 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2632 nuw = OFBinOp->hasNoUnsignedWrap();
2633 nsw = OFBinOp->hasNoSignedWrap();
2634 }
2635 if (const PossiblyExactOperator *ExactOp =
2636 dyn_cast<const PossiblyExactOperator>(&I))
2637 exact = ExactOp->isExact();
2638 }
2639 SDNodeFlags Flags;
2640 Flags.setExact(exact);
2641 Flags.setNoSignedWrap(nsw);
2642 Flags.setNoUnsignedWrap(nuw);
2643 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2644 &Flags);
2645 setValue(&I, Res);
2646}
2647
2648void SelectionDAGBuilder::visitSDiv(const User &I) {
2649 SDValue Op1 = getValue(I.getOperand(0));
2650 SDValue Op2 = getValue(I.getOperand(1));
2651
2652 SDNodeFlags Flags;
2653 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2654 cast<PossiblyExactOperator>(&I)->isExact());
2655 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2656 Op2, &Flags));
2657}
2658
2659void SelectionDAGBuilder::visitICmp(const User &I) {
2660 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2661 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2662 predicate = IC->getPredicate();
2663 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2664 predicate = ICmpInst::Predicate(IC->getPredicate());
2665 SDValue Op1 = getValue(I.getOperand(0));
2666 SDValue Op2 = getValue(I.getOperand(1));
2667 ISD::CondCode Opcode = getICmpCondCode(predicate);
2668
2669 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2670 I.getType());
2671 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2672}
2673
2674void SelectionDAGBuilder::visitFCmp(const User &I) {
2675 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2676 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2677 predicate = FC->getPredicate();
2678 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2679 predicate = FCmpInst::Predicate(FC->getPredicate());
2680 SDValue Op1 = getValue(I.getOperand(0));
2681 SDValue Op2 = getValue(I.getOperand(1));
2682 ISD::CondCode Condition = getFCmpCondCode(predicate);
2683
2684 // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2685 // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2686 // further optimization, but currently FMF is only applicable to binary nodes.
2687 if (TM.Options.NoNaNsFPMath)
2688 Condition = getFCmpCodeWithoutNaN(Condition);
2689 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2690 I.getType());
2691 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2692}
2693
2694// Check if the condition of the select has one use or two users that are both
2695// selects with the same condition.
2696static bool hasOnlySelectUsers(const Value *Cond) {
2697 return all_of(Cond->users(), [](const Value *V) {
2698 return isa<SelectInst>(V);
2699 });
2700}
2701
2702void SelectionDAGBuilder::visitSelect(const User &I) {
2703 SmallVector<EVT, 4> ValueVTs;
2704 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2705 ValueVTs);
2706 unsigned NumValues = ValueVTs.size();
2707 if (NumValues == 0) return;
2708
2709 SmallVector<SDValue, 4> Values(NumValues);
2710 SDValue Cond = getValue(I.getOperand(0));
2711 SDValue LHSVal = getValue(I.getOperand(1));
2712 SDValue RHSVal = getValue(I.getOperand(2));
2713 auto BaseOps = {Cond};
2714 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2715 ISD::VSELECT : ISD::SELECT;
2716
2717 // Min/max matching is only viable if all output VTs are the same.
2718 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2719 EVT VT = ValueVTs[0];
2720 LLVMContext &Ctx = *DAG.getContext();
2721 auto &TLI = DAG.getTargetLoweringInfo();
2722
2723 // We care about the legality of the operation after it has been type
2724 // legalized.
2725 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2726 VT != TLI.getTypeToTransformTo(Ctx, VT))
2727 VT = TLI.getTypeToTransformTo(Ctx, VT);
2728
2729 // If the vselect is legal, assume we want to leave this as a vector setcc +
2730 // vselect. Otherwise, if this is going to be scalarized, we want to see if
2731 // min/max is legal on the scalar type.
2732 bool UseScalarMinMax = VT.isVector() &&
2733 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2734
2735 Value *LHS, *RHS;
2736 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2737 ISD::NodeType Opc = ISD::DELETED_NODE;
2738 switch (SPR.Flavor) {
2739 case SPF_UMAX: Opc = ISD::UMAX; break;
2740 case SPF_UMIN: Opc = ISD::UMIN; break;
2741 case SPF_SMAX: Opc = ISD::SMAX; break;
2742 case SPF_SMIN: Opc = ISD::SMIN; break;
2743 case SPF_FMINNUM:
2744 switch (SPR.NaNBehavior) {
2745 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?")::llvm::llvm_unreachable_internal("No NaN behavior for FP op?"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2745)
;
2746 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
2747 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2748 case SPNB_RETURNS_ANY: {
2749 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2750 Opc = ISD::FMINNUM;
2751 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2752 Opc = ISD::FMINNAN;
2753 else if (UseScalarMinMax)
2754 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2755 ISD::FMINNUM : ISD::FMINNAN;
2756 break;
2757 }
2758 }
2759 break;
2760 case SPF_FMAXNUM:
2761 switch (SPR.NaNBehavior) {
2762 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?")::llvm::llvm_unreachable_internal("No NaN behavior for FP op?"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 2762)
;
2763 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
2764 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2765 case SPNB_RETURNS_ANY:
2766
2767 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2768 Opc = ISD::FMAXNUM;
2769 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2770 Opc = ISD::FMAXNAN;
2771 else if (UseScalarMinMax)
2772 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2773 ISD::FMAXNUM : ISD::FMAXNAN;
2774 break;
2775 }
2776 break;
2777 default: break;
2778 }
2779
2780 if (Opc != ISD::DELETED_NODE &&
2781 (TLI.isOperationLegalOrCustom(Opc, VT) ||
2782 (UseScalarMinMax &&
2783 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2784 // If the underlying comparison instruction is used by any other
2785 // instruction, the consumed instructions won't be destroyed, so it is
2786 // not profitable to convert to a min/max.
2787 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2788 OpCode = Opc;
2789 LHSVal = getValue(LHS);
2790 RHSVal = getValue(RHS);
2791 BaseOps = {};
2792 }
2793 }
2794
2795 for (unsigned i = 0; i != NumValues; ++i) {
2796 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2797 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2798 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2799 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2800 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2801 Ops);
2802 }
2803
2804 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2805 DAG.getVTList(ValueVTs), Values));
2806}
2807
2808void SelectionDAGBuilder::visitTrunc(const User &I) {
2809 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2810 SDValue N = getValue(I.getOperand(0));
2811 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2812 I.getType());
2813 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2814}
2815
2816void SelectionDAGBuilder::visitZExt(const User &I) {
2817 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2818 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2819 SDValue N = getValue(I.getOperand(0));
2820 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2821 I.getType());
2822 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2823}
2824
2825void SelectionDAGBuilder::visitSExt(const User &I) {
2826 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2827 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2828 SDValue N = getValue(I.getOperand(0));
2829 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2830 I.getType());
2831 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2832}
2833
2834void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2835 // FPTrunc is never a no-op cast, no need to check
2836 SDValue N = getValue(I.getOperand(0));
2837 SDLoc dl = getCurSDLoc();
2838 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2840 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2841 DAG.getTargetConstant(
2842 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2843}
2844
2845void SelectionDAGBuilder::visitFPExt(const User &I) {
2846 // FPExt is never a no-op cast, no need to check
2847 SDValue N = getValue(I.getOperand(0));
2848 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2849 I.getType());
2850 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2851}
2852
2853void SelectionDAGBuilder::visitFPToUI(const User &I) {
2854 // FPToUI is never a no-op cast, no need to check
2855 SDValue N = getValue(I.getOperand(0));
2856 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2857 I.getType());
2858 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2859}
2860
2861void SelectionDAGBuilder::visitFPToSI(const User &I) {
2862 // FPToSI is never a no-op cast, no need to check
2863 SDValue N = getValue(I.getOperand(0));
2864 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2865 I.getType());
2866 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2867}
2868
2869void SelectionDAGBuilder::visitUIToFP(const User &I) {
2870 // UIToFP is never a no-op cast, no need to check
2871 SDValue N = getValue(I.getOperand(0));
2872 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2873 I.getType());
2874 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2875}
2876
2877void SelectionDAGBuilder::visitSIToFP(const User &I) {
2878 // SIToFP is never a no-op cast, no need to check
2879 SDValue N = getValue(I.getOperand(0));
2880 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2881 I.getType());
2882 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2883}
2884
2885void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2886 // What to do depends on the size of the integer and the size of the pointer.
2887 // We can either truncate, zero extend, or no-op, accordingly.
2888 SDValue N = getValue(I.getOperand(0));
2889 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2890 I.getType());
2891 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2892}
2893
2894void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2895 // What to do depends on the size of the integer and the size of the pointer.
2896 // We can either truncate, zero extend, or no-op, accordingly.
2897 SDValue N = getValue(I.getOperand(0));
2898 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2899 I.getType());
2900 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2901}
2902
2903void SelectionDAGBuilder::visitBitCast(const User &I) {
2904 SDValue N = getValue(I.getOperand(0));
2905 SDLoc dl = getCurSDLoc();
2906 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2907 I.getType());
2908
2909 // BitCast assures us that source and destination are the same size so this is
2910 // either a BITCAST or a no-op.
2911 if (DestVT != N.getValueType())
2912 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2913 DestVT, N)); // convert types.
2914 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2915 // might fold any kind of constant expression to an integer constant and that
2916 // is not what we are looking for. Only regcognize a bitcast of a genuine
2917 // constant integer as an opaque constant.
2918 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2919 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2920 /*isOpaque*/true));
2921 else
2922 setValue(&I, N); // noop cast.
2923}
2924
2925void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2927 const Value *SV = I.getOperand(0);
2928 SDValue N = getValue(SV);
2929 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2930
2931 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2932 unsigned DestAS = I.getType()->getPointerAddressSpace();
2933
2934 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2935 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2936
2937 setValue(&I, N);
2938}
2939
2940void SelectionDAGBuilder::visitInsertElement(const User &I) {
2941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2942 SDValue InVec = getValue(I.getOperand(0));
2943 SDValue InVal = getValue(I.getOperand(1));
2944 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
2945 TLI.getVectorIdxTy(DAG.getDataLayout()));
2946 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2947 TLI.getValueType(DAG.getDataLayout(), I.getType()),
2948 InVec, InVal, InIdx));
2949}
2950
2951void SelectionDAGBuilder::visitExtractElement(const User &I) {
2952 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2953 SDValue InVec = getValue(I.getOperand(0));
2954 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
2955 TLI.getVectorIdxTy(DAG.getDataLayout()));
2956 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2957 TLI.getValueType(DAG.getDataLayout(), I.getType()),
2958 InVec, InIdx));
2959}
2960
2961void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2962 SDValue Src1 = getValue(I.getOperand(0));
2963 SDValue Src2 = getValue(I.getOperand(1));
2964 SDLoc DL = getCurSDLoc();
2965
2966 SmallVector<int, 8> Mask;
2967 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2968 unsigned MaskNumElts = Mask.size();
2969
2970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2971 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2972 EVT SrcVT = Src1.getValueType();
2973 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2974
2975 if (SrcNumElts == MaskNumElts) {
2976 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
2977 return;
2978 }
2979
2980 // Normalize the shuffle vector since mask and vector length don't match.
2981 if (SrcNumElts < MaskNumElts) {
2982 // Mask is longer than the source vectors. We can use concatenate vector to
2983 // make the mask and vectors lengths match.
2984
2985 if (MaskNumElts % SrcNumElts == 0) {
2986 // Mask length is a multiple of the source vector length.
2987 // Check if the shuffle is some kind of concatenation of the input
2988 // vectors.
2989 unsigned NumConcat = MaskNumElts / SrcNumElts;
2990 bool IsConcat = true;
2991 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
2992 for (unsigned i = 0; i != MaskNumElts; ++i) {
2993 int Idx = Mask[i];
2994 if (Idx < 0)
2995 continue;
2996 // Ensure the indices in each SrcVT sized piece are sequential and that
2997 // the same source is used for the whole piece.
2998 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
2999 (ConcatSrcs[i / SrcNumElts] >= 0 &&
3000 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3001 IsConcat = false;
3002 break;
3003 }
3004 // Remember which source this index came from.
3005 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3006 }
3007
3008 // The shuffle is concatenating multiple vectors together. Just emit
3009 // a CONCAT_VECTORS operation.
3010 if (IsConcat) {
3011 SmallVector<SDValue, 8> ConcatOps;
3012 for (auto Src : ConcatSrcs) {
3013 if (Src < 0)
3014 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3015 else if (Src == 0)
3016 ConcatOps.push_back(Src1);
3017 else
3018 ConcatOps.push_back(Src2);
3019 }
3020 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3021 return;
3022 }
3023 }
3024
3025 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3026 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3027 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3028 PaddedMaskNumElts);
3029
3030 // Pad both vectors with undefs to make them the same length as the mask.
3031 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3032
3033 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3034 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3035 MOps1[0] = Src1;
3036 MOps2[0] = Src2;
3037
3038 Src1 = Src1.isUndef()
3039 ? DAG.getUNDEF(PaddedVT)
3040 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3041 Src2 = Src2.isUndef()
3042 ? DAG.getUNDEF(PaddedVT)
3043 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3044
3045 // Readjust mask for new input vector length.
3046 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3047 for (unsigned i = 0; i != MaskNumElts; ++i) {
3048 int Idx = Mask[i];
3049 if (Idx >= (int)SrcNumElts)
3050 Idx -= SrcNumElts - PaddedMaskNumElts;
3051 MappedOps[i] = Idx;
3052 }
3053
3054 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3055
3056 // If the concatenated vector was padded, extract a subvector with the
3057 // correct number of elements.
3058 if (MaskNumElts != PaddedMaskNumElts)
3059 Result = DAG.getNode(
3060 ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3061 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3062
3063 setValue(&I, Result);
3064 return;
3065 }
3066
3067 if (SrcNumElts > MaskNumElts) {
3068 // Analyze the access pattern of the vector to see if we can extract
3069 // two subvectors and do the shuffle. The analysis is done by calculating
3070 // the range of elements the mask access on both vectors.
3071 int MinRange[2] = { static_cast<int>(SrcNumElts),
3072 static_cast<int>(SrcNumElts)};
3073 int MaxRange[2] = {-1, -1};
3074
3075 for (unsigned i = 0; i != MaskNumElts; ++i) {
3076 int Idx = Mask[i];
3077 unsigned Input = 0;
3078 if (Idx < 0)
3079 continue;
3080
3081 if (Idx >= (int)SrcNumElts) {
3082 Input = 1;
3083 Idx -= SrcNumElts;
3084 }
3085 if (Idx > MaxRange[Input])
3086 MaxRange[Input] = Idx;
3087 if (Idx < MinRange[Input])
3088 MinRange[Input] = Idx;
3089 }
3090
3091 // Check if the access is smaller than the vector size and can we find
3092 // a reasonable extract index.
3093 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3094 // Extract.
3095 int StartIdx[2]; // StartIdx to extract from
3096 for (unsigned Input = 0; Input < 2; ++Input) {
3097 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3098 RangeUse[Input] = 0; // Unused
3099 StartIdx[Input] = 0;
3100 continue;
3101 }
3102
3103 // Find a good start index that is a multiple of the mask length. Then
3104 // see if the rest of the elements are in range.
3105 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3106 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3107 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3108 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3109 }
3110
3111 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3112 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3113 return;
3114 }
3115 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3116 // Extract appropriate subvector and generate a vector shuffle
3117 for (unsigned Input = 0; Input < 2; ++Input) {
3118 SDValue &Src = Input == 0 ? Src1 : Src2;
3119 if (RangeUse[Input] == 0)
3120 Src = DAG.getUNDEF(VT);
3121 else {
3122 Src = DAG.getNode(
3123 ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3124 DAG.getConstant(StartIdx[Input], DL,
3125 TLI.getVectorIdxTy(DAG.getDataLayout())));
3126 }
3127 }
3128
3129 // Calculate new mask.
3130 SmallVector<int, 8> MappedOps;
3131 for (unsigned i = 0; i != MaskNumElts; ++i) {
3132 int Idx = Mask[i];
3133 if (Idx >= 0) {
3134 if (Idx < (int)SrcNumElts)
3135 Idx -= StartIdx[0];
3136 else
3137 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3138 }
3139 MappedOps.push_back(Idx);
3140 }
3141
3142 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3143 return;
3144 }
3145 }
3146
3147 // We can't use either concat vectors or extract subvectors so fall back to
3148 // replacing the shuffle with extract and build vector.
3149 // to insert and build vector.
3150 EVT EltVT = VT.getVectorElementType();
3151 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3152 SmallVector<SDValue,8> Ops;
3153 for (unsigned i = 0; i != MaskNumElts; ++i) {
3154 int Idx = Mask[i];
3155 SDValue Res;
3156
3157 if (Idx < 0) {
3158 Res = DAG.getUNDEF(EltVT);
3159 } else {
3160 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3161 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3162
3163 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3164 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3165 }
3166
3167 Ops.push_back(Res);
3168 }
3169
3170 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops));
3171}
3172
3173void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3174 const Value *Op0 = I.getOperand(0);
3175 const Value *Op1 = I.getOperand(1);
3176 Type *AggTy = I.getType();
3177 Type *ValTy = Op1->getType();
3178 bool IntoUndef = isa<UndefValue>(Op0);
3179 bool FromUndef = isa<UndefValue>(Op1);
3180
3181 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3182
3183 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3184 SmallVector<EVT, 4> AggValueVTs;
3185 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3186 SmallVector<EVT, 4> ValValueVTs;
3187 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3188
3189 unsigned NumAggValues = AggValueVTs.size();
3190 unsigned NumValValues = ValValueVTs.size();
3191 SmallVector<SDValue, 4> Values(NumAggValues);
3192
3193 // Ignore an insertvalue that produces an empty object
3194 if (!NumAggValues) {
3195 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3196 return;
3197 }
3198
3199 SDValue Agg = getValue(Op0);
3200 unsigned i = 0;
3201 // Copy the beginning value(s) from the original aggregate.
3202 for (; i != LinearIndex; ++i)
3203 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3204 SDValue(Agg.getNode(), Agg.getResNo() + i);
3205 // Copy values from the inserted value(s).
3206 if (NumValValues) {
3207 SDValue Val = getValue(Op1);
3208 for (; i != LinearIndex + NumValValues; ++i)
3209 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3210 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3211 }
3212 // Copy remaining value(s) from the original aggregate.
3213 for (; i != NumAggValues; ++i)
3214 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3215 SDValue(Agg.getNode(), Agg.getResNo() + i);
3216
3217 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3218 DAG.getVTList(AggValueVTs), Values));
3219}
3220
3221void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3222 const Value *Op0 = I.getOperand(0);
3223 Type *AggTy = Op0->getType();
3224 Type *ValTy = I.getType();
3225 bool OutOfUndef = isa<UndefValue>(Op0);
3226
3227 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3228
3229 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3230 SmallVector<EVT, 4> ValValueVTs;
3231 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3232
3233 unsigned NumValValues = ValValueVTs.size();
3234
3235 // Ignore a extractvalue that produces an empty object
3236 if (!NumValValues) {
3237 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3238 return;
3239 }
3240
3241 SmallVector<SDValue, 4> Values(NumValValues);
3242
3243 SDValue Agg = getValue(Op0);
3244 // Copy out the selected value(s).
3245 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3246 Values[i - LinearIndex] =
3247 OutOfUndef ?
3248 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3249 SDValue(Agg.getNode(), Agg.getResNo() + i);
3250
3251 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3252 DAG.getVTList(ValValueVTs), Values));
3253}
3254
3255void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3256 Value *Op0 = I.getOperand(0);
3257 // Note that the pointer operand may be a vector of pointers. Take the scalar
3258 // element which holds a pointer.
3259 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3260 SDValue N = getValue(Op0);
3261 SDLoc dl = getCurSDLoc();
3262
3263 // Normalize Vector GEP - all scalar operands should be converted to the
3264 // splat vector.
3265 unsigned VectorWidth = I.getType()->isVectorTy() ?
3266 cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3267
3268 if (VectorWidth && !N.getValueType().isVector()) {
3269 LLVMContext &Context = *DAG.getContext();
3270 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3271 N = DAG.getSplatBuildVector(VT, dl, N);
3272 }
3273
3274 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3275 GTI != E; ++GTI) {
3276 const Value *Idx = GTI.getOperand();
3277 if (StructType *StTy = GTI.getStructTypeOrNull()) {
3278 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3279 if (Field) {
3280 // N = N + Offset
3281 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3282
3283 // In an inbouds GEP with an offset that is nonnegative even when
3284 // interpreted as signed, assume there is no unsigned overflow.
3285 SDNodeFlags Flags;
3286 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3287 Flags.setNoUnsignedWrap(true);
3288
3289 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3290 DAG.getConstant(Offset, dl, N.getValueType()), &Flags);
3291 }
3292 } else {
3293 MVT PtrTy =
3294 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
3295 unsigned PtrSize = PtrTy.getSizeInBits();
3296 APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3297
3298 // If this is a scalar constant or a splat vector of constants,
3299 // handle it quickly.
3300 const auto *CI = dyn_cast<ConstantInt>(Idx);
3301 if (!CI && isa<ConstantDataVector>(Idx) &&
3302 cast<ConstantDataVector>(Idx)->getSplatValue())
3303 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3304
3305 if (CI) {
3306 if (CI->isZero())
3307 continue;
3308 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
3309 LLVMContext &Context = *DAG.getContext();
3310 SDValue OffsVal = VectorWidth ?
3311 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
3312 DAG.getConstant(Offs, dl, PtrTy);
3313
3314 // In an inbouds GEP with an offset that is nonnegative even when
3315 // interpreted as signed, assume there is no unsigned overflow.
3316 SDNodeFlags Flags;
3317 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3318 Flags.setNoUnsignedWrap(true);
3319
3320 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, &Flags);
3321 continue;
3322 }
3323
3324 // N = N + Idx * ElementSize;
3325 SDValue IdxN = getValue(Idx);
3326
3327 if (!IdxN.getValueType().isVector() && VectorWidth) {
3328 MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
3329 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3330 }
3331
3332 // If the index is smaller or larger than intptr_t, truncate or extend
3333 // it.
3334 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3335
3336 // If this is a multiply by a power of two, turn it into a shl
3337 // immediately. This is a very common case.
3338 if (ElementSize != 1) {
3339 if (ElementSize.isPowerOf2()) {
3340 unsigned Amt = ElementSize.logBase2();
3341 IdxN = DAG.getNode(ISD::SHL, dl,
3342 N.getValueType(), IdxN,
3343 DAG.getConstant(Amt, dl, IdxN.getValueType()));
3344 } else {
3345 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3346 IdxN = DAG.getNode(ISD::MUL, dl,
3347 N.getValueType(), IdxN, Scale);
3348 }
3349 }
3350
3351 N = DAG.getNode(ISD::ADD, dl,
3352 N.getValueType(), N, IdxN);
3353 }
3354 }
3355
3356 setValue(&I, N);
3357}
3358
3359void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3360 // If this is a fixed sized alloca in the entry block of the function,
3361 // allocate it statically on the stack.
3362 if (FuncInfo.StaticAllocaMap.count(&I))
3363 return; // getValue will auto-populate this.
3364
3365 SDLoc dl = getCurSDLoc();
3366 Type *Ty = I.getAllocatedType();
3367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3368 auto &DL = DAG.getDataLayout();
3369 uint64_t TySize = DL.getTypeAllocSize(Ty);
3370 unsigned Align =
3371 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3372
3373 SDValue AllocSize = getValue(I.getArraySize());
3374
3375 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
3376 if (AllocSize.getValueType() != IntPtr)
3377 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3378
3379 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3380 AllocSize,
3381 DAG.getConstant(TySize, dl, IntPtr));
3382
3383 // Handle alignment. If the requested alignment is less than or equal to
3384 // the stack alignment, ignore it. If the size is greater than or equal to
3385 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3386 unsigned StackAlign =
3387 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3388 if (Align <= StackAlign)
3389 Align = 0;
3390
3391 // Round the size of the allocation up to the stack alignment size
3392 // by add SA-1 to the size. This doesn't overflow because we're computing
3393 // an address inside an alloca.
3394 SDNodeFlags Flags;
3395 Flags.setNoUnsignedWrap(true);
3396 AllocSize = DAG.getNode(ISD::ADD, dl,
3397 AllocSize.getValueType(), AllocSize,
3398 DAG.getIntPtrConstant(StackAlign - 1, dl), &Flags);
3399
3400 // Mask out the low bits for alignment purposes.
3401 AllocSize = DAG.getNode(ISD::AND, dl,
3402 AllocSize.getValueType(), AllocSize,
3403 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
3404 dl));
3405
3406 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
3407 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3408 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3409 setValue(&I, DSA);
3410 DAG.setRoot(DSA.getValue(1));
3411
3412 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects())((FuncInfo.MF->getFrameInfo().hasVarSizedObjects()) ? static_cast
<void> (0) : __assert_fail ("FuncInfo.MF->getFrameInfo().hasVarSizedObjects()"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3412, __PRETTY_FUNCTION__))
;
3413}
3414
3415void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3416 if (I.isAtomic())
3417 return visitAtomicLoad(I);
3418
3419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3420 const Value *SV = I.getOperand(0);
3421 if (TLI.supportSwiftError()) {
3422 // Swifterror values can come from either a function parameter with
3423 // swifterror attribute or an alloca with swifterror attribute.
3424 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3425 if (Arg->hasSwiftErrorAttr())
3426 return visitLoadFromSwiftError(I);
3427 }
3428
3429 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3430 if (Alloca->isSwiftError())
3431 return visitLoadFromSwiftError(I);
3432 }
3433 }
3434
3435 SDValue Ptr = getValue(SV);
3436
3437 Type *Ty = I.getType();
3438
3439 bool isVolatile = I.isVolatile();
3440 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3441 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3442 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3443 unsigned Alignment = I.getAlignment();
3444
3445 AAMDNodes AAInfo;
3446 I.getAAMetadata(AAInfo);
3447 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3448
3449 SmallVector<EVT, 4> ValueVTs;
3450 SmallVector<uint64_t, 4> Offsets;
3451 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3452 unsigned NumValues = ValueVTs.size();
3453 if (NumValues == 0)
3454 return;
3455
3456 SDValue Root;
3457 bool ConstantMemory = false;
3458 if (isVolatile || NumValues > MaxParallelChains)
3459 // Serialize volatile loads with other side effects.
3460 Root = getRoot();
3461 else if (AA->pointsToConstantMemory(MemoryLocation(
3462 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3463 // Do not serialize (non-volatile) loads of constant memory with anything.
3464 Root = DAG.getEntryNode();
3465 ConstantMemory = true;
3466 } else {
3467 // Do not serialize non-volatile loads against each other.
3468 Root = DAG.getRoot();
3469 }
3470
3471 SDLoc dl = getCurSDLoc();
3472
3473 if (isVolatile)
3474 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3475
3476 // An aggregate load cannot wrap around the address space, so offsets to its
3477 // parts don't wrap either.
3478 SDNodeFlags Flags;
3479 Flags.setNoUnsignedWrap(true);
3480
3481 SmallVector<SDValue, 4> Values(NumValues);
3482 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3483 EVT PtrVT = Ptr.getValueType();
3484 unsigned ChainI = 0;
3485 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3486 // Serializing loads here may result in excessive register pressure, and
3487 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3488 // could recover a bit by hoisting nodes upward in the chain by recognizing
3489 // they are side-effect free or do not alias. The optimizer should really
3490 // avoid this case by converting large object/array copies to llvm.memcpy
3491 // (MaxParallelChains should always remain as failsafe).
3492 if (ChainI == MaxParallelChains) {
3493 assert(PendingLoads.empty() && "PendingLoads must be serialized first")((PendingLoads.empty() && "PendingLoads must be serialized first"
) ? static_cast<void> (0) : __assert_fail ("PendingLoads.empty() && \"PendingLoads must be serialized first\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3493, __PRETTY_FUNCTION__))
;
3494 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3495 makeArrayRef(Chains.data(), ChainI));
3496 Root = Chain;
3497 ChainI = 0;
3498 }
3499 SDValue A = DAG.getNode(ISD::ADD, dl,
3500 PtrVT, Ptr,
3501 DAG.getConstant(Offsets[i], dl, PtrVT),
3502 &Flags);
3503 auto MMOFlags = MachineMemOperand::MONone;
3504 if (isVolatile)
3505 MMOFlags |= MachineMemOperand::MOVolatile;
3506 if (isNonTemporal)
3507 MMOFlags |= MachineMemOperand::MONonTemporal;
3508 if (isInvariant)
3509 MMOFlags |= MachineMemOperand::MOInvariant;
3510 if (isDereferenceable)
3511 MMOFlags |= MachineMemOperand::MODereferenceable;
3512
3513 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3514 MachinePointerInfo(SV, Offsets[i]), Alignment,
3515 MMOFlags, AAInfo, Ranges);
3516
3517 Values[i] = L;
3518 Chains[ChainI] = L.getValue(1);
3519 }
3520
3521 if (!ConstantMemory) {
3522 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3523 makeArrayRef(Chains.data(), ChainI));
3524 if (isVolatile)
3525 DAG.setRoot(Chain);
3526 else
3527 PendingLoads.push_back(Chain);
3528 }
3529
3530 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3531 DAG.getVTList(ValueVTs), Values));
3532}
3533
3534void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3535 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3536 assert(TLI.supportSwiftError() &&((TLI.supportSwiftError() && "call visitStoreToSwiftError when backend supports swifterror"
) ? static_cast<void> (0) : __assert_fail ("TLI.supportSwiftError() && \"call visitStoreToSwiftError when backend supports swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3537, __PRETTY_FUNCTION__))
3537 "call visitStoreToSwiftError when backend supports swifterror")((TLI.supportSwiftError() && "call visitStoreToSwiftError when backend supports swifterror"
) ? static_cast<void> (0) : __assert_fail ("TLI.supportSwiftError() && \"call visitStoreToSwiftError when backend supports swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3537, __PRETTY_FUNCTION__))
;
3538
3539 SmallVector<EVT, 4> ValueVTs;
3540 SmallVector<uint64_t, 4> Offsets;
3541 const Value *SrcV = I.getOperand(0);
3542 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3543 SrcV->getType(), ValueVTs, &Offsets);
3544 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&((ValueVTs.size() == 1 && Offsets[0] == 0 && "expect a single EVT for swifterror"
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3545, __PRETTY_FUNCTION__))
3545 "expect a single EVT for swifterror")((ValueVTs.size() == 1 && Offsets[0] == 0 && "expect a single EVT for swifterror"
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3545, __PRETTY_FUNCTION__))
;
3546
3547 SDValue Src = getValue(SrcV);
3548 // Create a virtual register, then update the virtual register.
3549 auto &DL = DAG.getDataLayout();
3550 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3551 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
3552 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3553 // Chain can be getRoot or getControlRoot.
3554 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3555 SDValue(Src.getNode(), Src.getResNo()));
3556 DAG.setRoot(CopyNode);
3557 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3558}
3559
3560void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3561 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&((DAG.getTargetLoweringInfo().supportSwiftError() && "call visitLoadFromSwiftError when backend supports swifterror"
) ? static_cast<void> (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitLoadFromSwiftError when backend supports swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3562, __PRETTY_FUNCTION__))
3562 "call visitLoadFromSwiftError when backend supports swifterror")((DAG.getTargetLoweringInfo().supportSwiftError() && "call visitLoadFromSwiftError when backend supports swifterror"
) ? static_cast<void> (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitLoadFromSwiftError when backend supports swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3562, __PRETTY_FUNCTION__))
;
3563
3564 assert(!I.isVolatile() &&((!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal
) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load
) == nullptr && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? static_cast<void> (0) : __assert_fail ("!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3567, __PRETTY_FUNCTION__))
3565 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&((!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal
) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load
) == nullptr && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? static_cast<void> (0) : __assert_fail ("!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3567, __PRETTY_FUNCTION__))
3566 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&((!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal
) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load
) == nullptr && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? static_cast<void> (0) : __assert_fail ("!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3567, __PRETTY_FUNCTION__))
3567 "Support volatile, non temporal, invariant for load_from_swift_error")((!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal
) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load
) == nullptr && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? static_cast<void> (0) : __assert_fail ("!I.isVolatile() && I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3567, __PRETTY_FUNCTION__))
;
3568
3569 const Value *SV = I.getOperand(0);
3570 Type *Ty = I.getType();
3571 AAMDNodes AAInfo;
3572 I.getAAMetadata(AAInfo);
3573 assert(!AA->pointsToConstantMemory(MemoryLocation(((!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout
().getTypeStoreSize(Ty), AAInfo)) && "load_from_swift_error should not be constant memory"
) ? static_cast<void> (0) : __assert_fail ("!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) && \"load_from_swift_error should not be constant memory\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3575, __PRETTY_FUNCTION__))
3574 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) &&((!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout
().getTypeStoreSize(Ty), AAInfo)) && "load_from_swift_error should not be constant memory"
) ? static_cast<void> (0) : __assert_fail ("!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) && \"load_from_swift_error should not be constant memory\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3575, __PRETTY_FUNCTION__))
3575 "load_from_swift_error should not be constant memory")((!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout
().getTypeStoreSize(Ty), AAInfo)) && "load_from_swift_error should not be constant memory"
) ? static_cast<void> (0) : __assert_fail ("!AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) && \"load_from_swift_error should not be constant memory\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3575, __PRETTY_FUNCTION__))
;
3576
3577 SmallVector<EVT, 4> ValueVTs;
3578 SmallVector<uint64_t, 4> Offsets;
3579 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3580 ValueVTs, &Offsets);
3581 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&((ValueVTs.size() == 1 && Offsets[0] == 0 && "expect a single EVT for swifterror"
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3582, __PRETTY_FUNCTION__))
3582 "expect a single EVT for swifterror")((ValueVTs.size() == 1 && Offsets[0] == 0 && "expect a single EVT for swifterror"
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3582, __PRETTY_FUNCTION__))
;
3583
3584 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3585 SDValue L = DAG.getCopyFromReg(
3586 getRoot(), getCurSDLoc(),
3587 FuncInfo.getOrCreateSwiftErrorVReg(FuncInfo.MBB, SV), ValueVTs[0]);
3588
3589 setValue(&I, L);
3590}
3591
3592void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3593 if (I.isAtomic())
3594 return visitAtomicStore(I);
3595
3596 const Value *SrcV = I.getOperand(0);
3597 const Value *PtrV = I.getOperand(1);
3598
3599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3600 if (TLI.supportSwiftError()) {
3601 // Swifterror values can come from either a function parameter with
3602 // swifterror attribute or an alloca with swifterror attribute.
3603 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3604 if (Arg->hasSwiftErrorAttr())
3605 return visitStoreToSwiftError(I);
3606 }
3607
3608 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3609 if (Alloca->isSwiftError())
3610 return visitStoreToSwiftError(I);
3611 }
3612 }
3613
3614 SmallVector<EVT, 4> ValueVTs;
3615 SmallVector<uint64_t, 4> Offsets;
3616 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3617 SrcV->getType(), ValueVTs, &Offsets);
3618 unsigned NumValues = ValueVTs.size();
3619 if (NumValues == 0)
3620 return;
3621
3622 // Get the lowered operands. Note that we do this after
3623 // checking if NumResults is zero, because with zero results
3624 // the operands won't have values in the map.
3625 SDValue Src = getValue(SrcV);
3626 SDValue Ptr = getValue(PtrV);
3627
3628 SDValue Root = getRoot();
3629 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3630 SDLoc dl = getCurSDLoc();
3631 EVT PtrVT = Ptr.getValueType();
3632 unsigned Alignment = I.getAlignment();
3633 AAMDNodes AAInfo;
3634 I.getAAMetadata(AAInfo);
3635
3636 auto MMOFlags = MachineMemOperand::MONone;
3637 if (I.isVolatile())
3638 MMOFlags |= MachineMemOperand::MOVolatile;
3639 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3640 MMOFlags |= MachineMemOperand::MONonTemporal;
3641
3642 // An aggregate load cannot wrap around the address space, so offsets to its
3643 // parts don't wrap either.
3644 SDNodeFlags Flags;
3645 Flags.setNoUnsignedWrap(true);
3646
3647 unsigned ChainI = 0;
3648 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3649 // See visitLoad comments.
3650 if (ChainI == MaxParallelChains) {
3651 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3652 makeArrayRef(Chains.data(), ChainI));
3653 Root = Chain;
3654 ChainI = 0;
3655 }
3656 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3657 DAG.getConstant(Offsets[i], dl, PtrVT), &Flags);
3658 SDValue St = DAG.getStore(
3659 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3660 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3661 Chains[ChainI] = St;
3662 }
3663
3664 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3665 makeArrayRef(Chains.data(), ChainI));
3666 DAG.setRoot(StoreNode);
3667}
3668
3669void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3670 bool IsCompressing) {
3671 SDLoc sdl = getCurSDLoc();
3672
3673 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3674 unsigned& Alignment) {
3675 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3676 Src0 = I.getArgOperand(0);
3677 Ptr = I.getArgOperand(1);
3678 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3679 Mask = I.getArgOperand(3);
3680 };
3681 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3682 unsigned& Alignment) {
3683 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3684 Src0 = I.getArgOperand(0);
3685 Ptr = I.getArgOperand(1);
3686 Mask = I.getArgOperand(2);
3687 Alignment = 0;
3688 };
3689
3690 Value *PtrOperand, *MaskOperand, *Src0Operand;
3691 unsigned Alignment;
3692 if (IsCompressing)
3693 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3694 else
3695 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3696
3697 SDValue Ptr = getValue(PtrOperand);
3698 SDValue Src0 = getValue(Src0Operand);
3699 SDValue Mask = getValue(MaskOperand);
3700
3701 EVT VT = Src0.getValueType();
3702 if (!Alignment)
3703 Alignment = DAG.getEVTAlignment(VT);
3704
3705 AAMDNodes AAInfo;
3706 I.getAAMetadata(AAInfo);
3707
3708 MachineMemOperand *MMO =
3709 DAG.getMachineFunction().
3710 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3711 MachineMemOperand::MOStore, VT.getStoreSize(),
3712 Alignment, AAInfo);
3713 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3714 MMO, false /* Truncating */,
3715 IsCompressing);
3716 DAG.setRoot(StoreNode);
3717 setValue(&I, StoreNode);
3718}
3719
3720// Get a uniform base for the Gather/Scatter intrinsic.
3721// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3722// We try to represent it as a base pointer + vector of indices.
3723// Usually, the vector of pointers comes from a 'getelementptr' instruction.
3724// The first operand of the GEP may be a single pointer or a vector of pointers
3725// Example:
3726// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3727// or
3728// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
3729// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3730//
3731// When the first GEP operand is a single pointer - it is the uniform base we
3732// are looking for. If first operand of the GEP is a splat vector - we
3733// extract the spalt value and use it as a uniform base.
3734// In all other cases the function returns 'false'.
3735//
3736static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3737 SelectionDAGBuilder* SDB) {
3738
3739 SelectionDAG& DAG = SDB->DAG;
3740 LLVMContext &Context = *DAG.getContext();
3741
3742 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type")((Ptr->getType()->isVectorTy() && "Uexpected pointer type"
) ? static_cast<void> (0) : __assert_fail ("Ptr->getType()->isVectorTy() && \"Uexpected pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3742, __PRETTY_FUNCTION__))
;
3743 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3744 if (!GEP || GEP->getNumOperands() > 2)
3745 return false;
3746
3747 const Value *GEPPtr = GEP->getPointerOperand();
3748 if (!GEPPtr->getType()->isVectorTy())
3749 Ptr = GEPPtr;
3750 else if (!(Ptr = getSplatValue(GEPPtr)))
3751 return false;
3752
3753 Value *IndexVal = GEP->getOperand(1);
3754
3755 // The operands of the GEP may be defined in another basic block.
3756 // In this case we'll not find nodes for the operands.
3757 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3758 return false;
3759
3760 Base = SDB->getValue(Ptr);
3761 Index = SDB->getValue(IndexVal);
3762
3763 // Suppress sign extension.
3764 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3765 if (SDB->findValue(Sext->getOperand(0))) {
3766 IndexVal = Sext->getOperand(0);
3767 Index = SDB->getValue(IndexVal);
3768 }
3769 }
3770 if (!Index.getValueType().isVector()) {
3771 unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3772 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3773 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3774 }
3775 return true;
3776}
3777
3778void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3779 SDLoc sdl = getCurSDLoc();
3780
3781 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3782 const Value *Ptr = I.getArgOperand(1);
3783 SDValue Src0 = getValue(I.getArgOperand(0));
3784 SDValue Mask = getValue(I.getArgOperand(3));
3785 EVT VT = Src0.getValueType();
3786 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3787 if (!Alignment)
3788 Alignment = DAG.getEVTAlignment(VT);
3789 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3790
3791 AAMDNodes AAInfo;
3792 I.getAAMetadata(AAInfo);
3793
3794 SDValue Base;
3795 SDValue Index;
3796 const Value *BasePtr = Ptr;
3797 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3798
3799 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3800 MachineMemOperand *MMO = DAG.getMachineFunction().
3801 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3802 MachineMemOperand::MOStore, VT.getStoreSize(),
3803 Alignment, AAInfo);
3804 if (!UniformBase) {
3805 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3806 Index = getValue(Ptr);
3807 }
3808 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3809 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3810 Ops, MMO);
3811 DAG.setRoot(Scatter);
3812 setValue(&I, Scatter);
3813}
3814
3815void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
3816 SDLoc sdl = getCurSDLoc();
3817
3818 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3819 unsigned& Alignment) {
3820 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3821 Ptr = I.getArgOperand(0);
3822 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
3823 Mask = I.getArgOperand(2);
3824 Src0 = I.getArgOperand(3);
3825 };
3826 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3827 unsigned& Alignment) {
3828 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
3829 Ptr = I.getArgOperand(0);
3830 Alignment = 0;
3831 Mask = I.getArgOperand(1);
3832 Src0 = I.getArgOperand(2);
3833 };
3834
3835 Value *PtrOperand, *MaskOperand, *Src0Operand;
3836 unsigned Alignment;
3837 if (IsExpanding)
3838 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3839 else
3840 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3841
3842 SDValue Ptr = getValue(PtrOperand);
3843 SDValue Src0 = getValue(Src0Operand);
3844 SDValue Mask = getValue(MaskOperand);
3845
3846 EVT VT = Src0.getValueType();
3847 if (!Alignment)
3848 Alignment = DAG.getEVTAlignment(VT);
3849
3850 AAMDNodes AAInfo;
3851 I.getAAMetadata(AAInfo);
3852 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3853
3854 // Do not serialize masked loads of constant memory with anything.
3855 bool AddToChain = !AA->pointsToConstantMemory(MemoryLocation(
3856 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
3857 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
3858
3859 MachineMemOperand *MMO =
3860 DAG.getMachineFunction().
3861 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3862 MachineMemOperand::MOLoad, VT.getStoreSize(),
3863 Alignment, AAInfo, Ranges);
3864
3865 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3866 ISD::NON_EXTLOAD, IsExpanding);
3867 if (AddToChain) {
3868 SDValue OutChain = Load.getValue(1);
3869 DAG.setRoot(OutChain);
3870 }
3871 setValue(&I, Load);
3872}
3873
3874void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3875 SDLoc sdl = getCurSDLoc();
3876
3877 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3878 const Value *Ptr = I.getArgOperand(0);
3879 SDValue Src0 = getValue(I.getArgOperand(3));
3880 SDValue Mask = getValue(I.getArgOperand(2));
3881
3882 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3883 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3884 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3885 if (!Alignment)
3886 Alignment = DAG.getEVTAlignment(VT);
3887
3888 AAMDNodes AAInfo;
3889 I.getAAMetadata(AAInfo);
3890 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3891
3892 SDValue Root = DAG.getRoot();
3893 SDValue Base;
3894 SDValue Index;
3895 const Value *BasePtr = Ptr;
3896 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3897 bool ConstantMemory = false;
3898 if (UniformBase &&
3899 AA->pointsToConstantMemory(MemoryLocation(
3900 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3901 AAInfo))) {
3902 // Do not serialize (non-volatile) loads of constant memory with anything.
3903 Root = DAG.getEntryNode();
3904 ConstantMemory = true;
3905 }
3906
3907 MachineMemOperand *MMO =
3908 DAG.getMachineFunction().
3909 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3910 MachineMemOperand::MOLoad, VT.getStoreSize(),
3911 Alignment, AAInfo, Ranges);
3912
3913 if (!UniformBase) {
3914 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3915 Index = getValue(Ptr);
3916 }
3917 SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3918 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3919 Ops, MMO);
3920
3921 SDValue OutChain = Gather.getValue(1);
3922 if (!ConstantMemory)
3923 PendingLoads.push_back(OutChain);
3924 setValue(&I, Gather);
3925}
3926
3927void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3928 SDLoc dl = getCurSDLoc();
3929 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3930 AtomicOrdering FailureOrder = I.getFailureOrdering();
3931 SynchronizationScope Scope = I.getSynchScope();
3932
3933 SDValue InChain = getRoot();
3934
3935 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3936 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3937 SDValue L = DAG.getAtomicCmpSwap(
3938 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3939 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3940 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3941 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3942
3943 SDValue OutChain = L.getValue(2);
3944
3945 setValue(&I, L);
3946 DAG.setRoot(OutChain);
3947}
3948
3949void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3950 SDLoc dl = getCurSDLoc();
3951 ISD::NodeType NT;
3952 switch (I.getOperation()) {
3953 default: llvm_unreachable("Unknown atomicrmw operation")::llvm::llvm_unreachable_internal("Unknown atomicrmw operation"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 3953)
;
3954 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3955 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3956 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3957 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3958 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3959 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3960 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3961 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3962 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3963 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3964 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3965 }
3966 AtomicOrdering Order = I.getOrdering();
3967 SynchronizationScope Scope = I.getSynchScope();
3968
3969 SDValue InChain = getRoot();
3970
3971 SDValue L =
3972 DAG.getAtomic(NT, dl,
3973 getValue(I.getValOperand()).getSimpleValueType(),
3974 InChain,
3975 getValue(I.getPointerOperand()),
3976 getValue(I.getValOperand()),
3977 I.getPointerOperand(),
3978 /* Alignment=*/ 0, Order, Scope);
3979
3980 SDValue OutChain = L.getValue(1);
3981
3982 setValue(&I, L);
3983 DAG.setRoot(OutChain);
3984}
3985
3986void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3987 SDLoc dl = getCurSDLoc();
3988 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3989 SDValue Ops[3];
3990 Ops[0] = getRoot();
3991 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
3992 TLI.getPointerTy(DAG.getDataLayout()));
3993 Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
3994 TLI.getPointerTy(DAG.getDataLayout()));
3995 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3996}
3997
3998void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3999 SDLoc dl = getCurSDLoc();
4000 AtomicOrdering Order = I.getOrdering();
4001 SynchronizationScope Scope = I.getSynchScope();
4002
4003 SDValue InChain = getRoot();
4004
4005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4006 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4007
4008 if (I.getAlignment() < VT.getSizeInBits() / 8)
4009 report_fatal_error("Cannot generate unaligned atomic load");
4010
4011 MachineMemOperand *MMO =
4012 DAG.getMachineFunction().
4013 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4014 MachineMemOperand::MOVolatile |
4015 MachineMemOperand::MOLoad,
4016 VT.getStoreSize(),
4017 I.getAlignment() ? I.getAlignment() :
4018 DAG.getEVTAlignment(VT),
4019 AAMDNodes(), nullptr, Scope, Order);
4020
4021 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4022 SDValue L =
4023 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4024 getValue(I.getPointerOperand()), MMO);
4025
4026 SDValue OutChain = L.getValue(1);
4027
4028 setValue(&I, L);
4029 DAG.setRoot(OutChain);
4030}
4031
4032void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4033 SDLoc dl = getCurSDLoc();
4034
4035 AtomicOrdering Order = I.getOrdering();
4036 SynchronizationScope Scope = I.getSynchScope();
4037
4038 SDValue InChain = getRoot();
4039
4040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4041 EVT VT =
4042 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4043
4044 if (I.getAlignment() < VT.getSizeInBits() / 8)
4045 report_fatal_error("Cannot generate unaligned atomic store");
4046
4047 SDValue OutChain =
4048 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4049 InChain,
4050 getValue(I.getPointerOperand()),
4051 getValue(I.getValueOperand()),
4052 I.getPointerOperand(), I.getAlignment(),
4053 Order, Scope);
4054
4055 DAG.setRoot(OutChain);
4056}
4057
4058/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4059/// node.
4060void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4061 unsigned Intrinsic) {
4062 // Ignore the callsite's attributes. A specific call site may be marked with
4063 // readnone, but the lowering code will expect the chain based on the
4064 // definition.
4065 const Function *F = I.getCalledFunction();
4066 bool HasChain = !F->doesNotAccessMemory();
4067 bool OnlyLoad = HasChain && F->onlyReadsMemory();
4068
4069 // Build the operand list.
4070 SmallVector<SDValue, 8> Ops;
4071 if (HasChain) { // If this intrinsic has side-effects, chainify it.
4072 if (OnlyLoad) {
4073 // We don't need to serialize loads against other loads.
4074 Ops.push_back(DAG.getRoot());
4075 } else {
4076 Ops.push_back(getRoot());
4077 }
4078 }
4079
4080 // Info is set by getTgtMemInstrinsic
4081 TargetLowering::IntrinsicInfo Info;
4082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4083 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
4084
4085 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4086 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4087 Info.opc == ISD::INTRINSIC_W_CHAIN)
4088 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4089 TLI.getPointerTy(DAG.getDataLayout())));
4090
4091 // Add all operands of the call to the operand list.
4092 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4093 SDValue Op = getValue(I.getArgOperand(i));
4094 Ops.push_back(Op);
4095 }
4096
4097 SmallVector<EVT, 4> ValueVTs;
4098 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4099
4100 if (HasChain)
4101 ValueVTs.push_back(MVT::Other);
4102
4103 SDVTList VTs = DAG.getVTList(ValueVTs);
4104
4105 // Create the node.
4106 SDValue Result;
4107 if (IsTgtIntrinsic) {
4108 // This is target intrinsic that touches memory
4109 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
4110 VTs, Ops, Info.memVT,
4111 MachinePointerInfo(Info.ptrVal, Info.offset),
4112 Info.align, Info.vol,
4113 Info.readMem, Info.writeMem, Info.size);
4114 } else if (!HasChain) {
4115 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4116 } else if (!I.getType()->isVoidTy()) {
4117 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4118 } else {
4119 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4120 }
4121
4122 if (HasChain) {
4123 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4124 if (OnlyLoad)
4125 PendingLoads.push_back(Chain);
4126 else
4127 DAG.setRoot(Chain);
4128 }
4129
4130 if (!I.getType()->isVoidTy()) {
4131 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4132 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4133 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4134 } else
4135 Result = lowerRangeToAssertZExt(DAG, I, Result);
4136
4137 setValue(&I, Result);
4138 }
4139}
4140
4141/// GetSignificand - Get the significand and build it into a floating-point
4142/// number with exponent of 1:
4143///
4144/// Op = (Op & 0x007fffff) | 0x3f800000;
4145///
4146/// where Op is the hexadecimal representation of floating point value.
4147static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4148 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4149 DAG.getConstant(0x007fffff, dl, MVT::i32));
4150 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4151 DAG.getConstant(0x3f800000, dl, MVT::i32));
4152 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4153}
4154
4155/// GetExponent - Get the exponent:
4156///
4157/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4158///
4159/// where Op is the hexadecimal representation of floating point value.
4160static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4161 const TargetLowering &TLI, const SDLoc &dl) {
4162 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4163 DAG.getConstant(0x7f800000, dl, MVT::i32));
4164 SDValue t1 = DAG.getNode(
4165 ISD::SRL, dl, MVT::i32, t0,
4166 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4167 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4168 DAG.getConstant(127, dl, MVT::i32));
4169 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4170}
4171
4172/// getF32Constant - Get 32-bit floating point constant.
4173static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4174 const SDLoc &dl) {
4175 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4176 MVT::f32);
4177}
4178
4179static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4180 SelectionDAG &DAG) {
4181 // TODO: What fast-math-flags should be set on the floating-point nodes?
4182
4183 // IntegerPartOfX = ((int32_t)(t0);
4184 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4185
4186 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
4187 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4188 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4189
4190 // IntegerPartOfX <<= 23;
4191 IntegerPartOfX = DAG.getNode(
4192 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4193 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4194 DAG.getDataLayout())));
4195
4196 SDValue TwoToFractionalPartOfX;
4197 if (LimitFloatPrecision <= 6) {
4198 // For floating-point precision of 6:
4199 //
4200 // TwoToFractionalPartOfX =
4201 // 0.997535578f +
4202 // (0.735607626f + 0.252464424f * x) * x;
4203 //
4204 // error 0.0144103317, which is 6 bits
4205 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4206 getF32Constant(DAG, 0x3e814304, dl));
4207 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4208 getF32Constant(DAG, 0x3f3c50c8, dl));
4209 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4210 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4211 getF32Constant(DAG, 0x3f7f5e7e, dl));
4212 } else if (LimitFloatPrecision <= 12) {
4213 // For floating-point precision of 12:
4214 //
4215 // TwoToFractionalPartOfX =
4216 // 0.999892986f +
4217 // (0.696457318f +
4218 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4219 //
4220 // error 0.000107046256, which is 13 to 14 bits
4221 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4222 getF32Constant(DAG, 0x3da235e3, dl));
4223 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4224 getF32Constant(DAG, 0x3e65b8f3, dl));
4225 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4226 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4227 getF32Constant(DAG, 0x3f324b07, dl));
4228 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4229 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4230 getF32Constant(DAG, 0x3f7ff8fd, dl));
4231 } else { // LimitFloatPrecision <= 18
4232 // For floating-point precision of 18:
4233 //
4234 // TwoToFractionalPartOfX =
4235 // 0.999999982f +
4236 // (0.693148872f +
4237 // (0.240227044f +
4238 // (0.554906021e-1f +
4239 // (0.961591928e-2f +
4240 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4241 // error 2.47208000*10^(-7), which is better than 18 bits
4242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4243 getF32Constant(DAG, 0x3924b03e, dl));
4244 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4245 getF32Constant(DAG, 0x3ab24b87, dl));
4246 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4247 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4248 getF32Constant(DAG, 0x3c1d8c17, dl));
4249 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4250 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4251 getF32Constant(DAG, 0x3d634a1d, dl));
4252 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4253 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4254 getF32Constant(DAG, 0x3e75fe14, dl));
4255 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4256 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4257 getF32Constant(DAG, 0x3f317234, dl));
4258 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4259 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4260 getF32Constant(DAG, 0x3f800000, dl));
4261 }
4262
4263 // Add the exponent into the result in integer domain.
4264 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4265 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4266 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4267}
4268
4269/// expandExp - Lower an exp intrinsic. Handles the special sequences for
4270/// limited-precision mode.
4271static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4272 const TargetLowering &TLI) {
4273 if (Op.getValueType() == MVT::f32 &&
4274 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4275
4276 // Put the exponent in the right bit position for later addition to the
4277 // final result:
4278 //
4279 // #define LOG2OFe 1.4426950f
4280 // t0 = Op * LOG2OFe
4281
4282 // TODO: What fast-math-flags should be set here?
4283 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4284 getF32Constant(DAG, 0x3fb8aa3b, dl));
4285 return getLimitedPrecisionExp2(t0, dl, DAG);
4286 }
4287
4288 // No special expansion.
4289 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4290}
4291
4292/// expandLog - Lower a log intrinsic. Handles the special sequences for
4293/// limited-precision mode.
4294static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4295 const TargetLowering &TLI) {
4296
4297 // TODO: What fast-math-flags should be set on the floating-point nodes?
4298
4299 if (Op.getValueType() == MVT::f32 &&
4300 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4301 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4302
4303 // Scale the exponent by log(2) [0.69314718f].
4304 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4305 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4306 getF32Constant(DAG, 0x3f317218, dl));
4307
4308 // Get the significand and build it into a floating-point number with
4309 // exponent of 1.
4310 SDValue X = GetSignificand(DAG, Op1, dl);
4311
4312 SDValue LogOfMantissa;
4313 if (LimitFloatPrecision <= 6) {
4314 // For floating-point precision of 6:
4315 //
4316 // LogofMantissa =
4317 // -1.1609546f +
4318 // (1.4034025f - 0.23903021f * x) * x;
4319 //
4320 // error 0.0034276066, which is better than 8 bits
4321 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4322 getF32Constant(DAG, 0xbe74c456, dl));
4323 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4324 getF32Constant(DAG, 0x3fb3a2b1, dl));
4325 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4326 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4327 getF32Constant(DAG, 0x3f949a29, dl));
4328 } else if (LimitFloatPrecision <= 12) {
4329 // For floating-point precision of 12:
4330 //
4331 // LogOfMantissa =
4332 // -1.7417939f +
4333 // (2.8212026f +
4334 // (-1.4699568f +
4335 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4336 //
4337 // error 0.000061011436, which is 14 bits
4338 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4339 getF32Constant(DAG, 0xbd67b6d6, dl));
4340 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4341 getF32Constant(DAG, 0x3ee4f4b8, dl));
4342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4343 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4344 getF32Constant(DAG, 0x3fbc278b, dl));
4345 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4346 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4347 getF32Constant(DAG, 0x40348e95, dl));
4348 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4349 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4350 getF32Constant(DAG, 0x3fdef31a, dl));
4351 } else { // LimitFloatPrecision <= 18
4352 // For floating-point precision of 18:
4353 //
4354 // LogOfMantissa =
4355 // -2.1072184f +
4356 // (4.2372794f +
4357 // (-3.7029485f +
4358 // (2.2781945f +
4359 // (-0.87823314f +
4360 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4361 //
4362 // error 0.0000023660568, which is better than 18 bits
4363 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4364 getF32Constant(DAG, 0xbc91e5ac, dl));
4365 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4366 getF32Constant(DAG, 0x3e4350aa, dl));
4367 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4368 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4369 getF32Constant(DAG, 0x3f60d3e3, dl));
4370 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4371 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4372 getF32Constant(DAG, 0x4011cdf0, dl));
4373 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4374 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4375 getF32Constant(DAG, 0x406cfd1c, dl));
4376 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4377 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4378 getF32Constant(DAG, 0x408797cb, dl));
4379 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4380 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4381 getF32Constant(DAG, 0x4006dcab, dl));
4382 }
4383
4384 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4385 }
4386
4387 // No special expansion.
4388 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4389}
4390
4391/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4392/// limited-precision mode.
4393static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4394 const TargetLowering &TLI) {
4395
4396 // TODO: What fast-math-flags should be set on the floating-point nodes?
4397
4398 if (Op.getValueType() == MVT::f32 &&
4399 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4400 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4401
4402 // Get the exponent.
4403 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4404
4405 // Get the significand and build it into a floating-point number with
4406 // exponent of 1.
4407 SDValue X = GetSignificand(DAG, Op1, dl);
4408
4409 // Different possible minimax approximations of significand in
4410 // floating-point for various degrees of accuracy over [1,2].
4411 SDValue Log2ofMantissa;
4412 if (LimitFloatPrecision <= 6) {
4413 // For floating-point precision of 6:
4414 //
4415 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4416 //
4417 // error 0.0049451742, which is more than 7 bits
4418 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4419 getF32Constant(DAG, 0xbeb08fe0, dl));
4420 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4421 getF32Constant(DAG, 0x40019463, dl));
4422 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4423 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4424 getF32Constant(DAG, 0x3fd6633d, dl));
4425 } else if (LimitFloatPrecision <= 12) {
4426 // For floating-point precision of 12:
4427 //
4428 // Log2ofMantissa =
4429 // -2.51285454f +
4430 // (4.07009056f +
4431 // (-2.12067489f +
4432 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4433 //
4434 // error 0.0000876136000, which is better than 13 bits
4435 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4436 getF32Constant(DAG, 0xbda7262e, dl));
4437 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4438 getF32Constant(DAG, 0x3f25280b, dl));
4439 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4440 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4441 getF32Constant(DAG, 0x4007b923, dl));
4442 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4443 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4444 getF32Constant(DAG, 0x40823e2f, dl));
4445 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4446 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4447 getF32Constant(DAG, 0x4020d29c, dl));
4448 } else { // LimitFloatPrecision <= 18
4449 // For floating-point precision of 18:
4450 //
4451 // Log2ofMantissa =
4452 // -3.0400495f +
4453 // (6.1129976f +
4454 // (-5.3420409f +
4455 // (3.2865683f +
4456 // (-1.2669343f +
4457 // (0.27515199f -
4458 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4459 //
4460 // error 0.0000018516, which is better than 18 bits
4461 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4462 getF32Constant(DAG, 0xbcd2769e, dl));
4463 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4464 getF32Constant(DAG, 0x3e8ce0b9, dl));
4465 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4466 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4467 getF32Constant(DAG, 0x3fa22ae7, dl));
4468 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4469 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4470 getF32Constant(DAG, 0x40525723, dl));
4471 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4472 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4473 getF32Constant(DAG, 0x40aaf200, dl));
4474 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4475 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4476 getF32Constant(DAG, 0x40c39dad, dl));
4477 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4478 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4479 getF32Constant(DAG, 0x4042902c, dl));
4480 }
4481
4482 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4483 }
4484
4485 // No special expansion.
4486 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4487}
4488
4489/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4490/// limited-precision mode.
4491static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4492 const TargetLowering &TLI) {
4493
4494 // TODO: What fast-math-flags should be set on the floating-point nodes?
4495
4496 if (Op.getValueType() == MVT::f32 &&
4497 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4498 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4499
4500 // Scale the exponent by log10(2) [0.30102999f].
4501 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4502 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4503 getF32Constant(DAG, 0x3e9a209a, dl));
4504
4505 // Get the significand and build it into a floating-point number with
4506 // exponent of 1.
4507 SDValue X = GetSignificand(DAG, Op1, dl);
4508
4509 SDValue Log10ofMantissa;
4510 if (LimitFloatPrecision <= 6) {
4511 // For floating-point precision of 6:
4512 //
4513 // Log10ofMantissa =
4514 // -0.50419619f +
4515 // (0.60948995f - 0.10380950f * x) * x;
4516 //
4517 // error 0.0014886165, which is 6 bits
4518 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4519 getF32Constant(DAG, 0xbdd49a13, dl));
4520 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4521 getF32Constant(DAG, 0x3f1c0789, dl));
4522 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4523 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4524 getF32Constant(DAG, 0x3f011300, dl));
4525 } else if (LimitFloatPrecision <= 12) {
4526 // For floating-point precision of 12:
4527 //
4528 // Log10ofMantissa =
4529 // -0.64831180f +
4530 // (0.91751397f +
4531 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4532 //
4533 // error 0.00019228036, which is better than 12 bits
4534 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4535 getF32Constant(DAG, 0x3d431f31, dl));
4536 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4537 getF32Constant(DAG, 0x3ea21fb2, dl));
4538 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4539 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4540 getF32Constant(DAG, 0x3f6ae232, dl));
4541 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4542 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4543 getF32Constant(DAG, 0x3f25f7c3, dl));
4544 } else { // LimitFloatPrecision <= 18
4545 // For floating-point precision of 18:
4546 //
4547 // Log10ofMantissa =
4548 // -0.84299375f +
4549 // (1.5327582f +
4550 // (-1.0688956f +
4551 // (0.49102474f +
4552 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4553 //
4554 // error 0.0000037995730, which is better than 18 bits
4555 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4556 getF32Constant(DAG, 0x3c5d51ce, dl));
4557 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4558 getF32Constant(DAG, 0x3e00685a, dl));
4559 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4560 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4561 getF32Constant(DAG, 0x3efb6798, dl));
4562 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4563 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4564 getF32Constant(DAG, 0x3f88d192, dl));
4565 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4566 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4567 getF32Constant(DAG, 0x3fc4316c, dl));
4568 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4569 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4570 getF32Constant(DAG, 0x3f57ce70, dl));
4571 }
4572
4573 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4574 }
4575
4576 // No special expansion.
4577 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4578}
4579
4580/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4581/// limited-precision mode.
4582static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4583 const TargetLowering &TLI) {
4584 if (Op.getValueType() == MVT::f32 &&
4585 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4586 return getLimitedPrecisionExp2(Op, dl, DAG);
4587
4588 // No special expansion.
4589 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4590}
4591
4592/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4593/// limited-precision mode with x == 10.0f.
4594static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4595 SelectionDAG &DAG, const TargetLowering &TLI) {
4596 bool IsExp10 = false;
4597 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4598 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4599 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4600 APFloat Ten(10.0f);
4601 IsExp10 = LHSC->isExactlyValue(Ten);
4602 }
4603 }
4604
4605 // TODO: What fast-math-flags should be set on the FMUL node?
4606 if (IsExp10) {
4607 // Put the exponent in the right bit position for later addition to the
4608 // final result:
4609 //
4610 // #define LOG2OF10 3.3219281f
4611 // t0 = Op * LOG2OF10;
4612 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4613 getF32Constant(DAG, 0x40549a78, dl));
4614 return getLimitedPrecisionExp2(t0, dl, DAG);
4615 }
4616
4617 // No special expansion.
4618 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4619}
4620
4621
4622/// ExpandPowI - Expand a llvm.powi intrinsic.
4623static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4624 SelectionDAG &DAG) {
4625 // If RHS is a constant, we can expand this out to a multiplication tree,
4626 // otherwise we end up lowering to a call to __powidf2 (for example). When
4627 // optimizing for size, we only want to do this if the expansion would produce
4628 // a small number of multiplies, otherwise we do the full expansion.
4629 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4630 // Get the exponent as a positive value.
4631 unsigned Val = RHSC->getSExtValue();
4632 if ((int)Val < 0) Val = -Val;
4633
4634 // powi(x, 0) -> 1.0
4635 if (Val == 0)
4636 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4637
4638 const Function *F = DAG.getMachineFunction().getFunction();
4639 if (!F->optForSize() ||
4640 // If optimizing for size, don't insert too many multiplies.
4641 // This inserts up to 5 multiplies.
4642 countPopulation(Val) + Log2_32(Val) < 7) {
4643 // We use the simple binary decomposition method to generate the multiply
4644 // sequence. There are more optimal ways to do this (for example,
4645 // powi(x,15) generates one more multiply than it should), but this has
4646 // the benefit of being both really simple and much better than a libcall.
4647 SDValue Res; // Logically starts equal to 1.0
4648 SDValue CurSquare = LHS;
4649 // TODO: Intrinsics should have fast-math-flags that propagate to these
4650 // nodes.
4651 while (Val) {
4652 if (Val & 1) {
4653 if (Res.getNode())
4654 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4655 else
4656 Res = CurSquare; // 1.0*CurSquare.
4657 }
4658
4659 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4660 CurSquare, CurSquare);
4661 Val >>= 1;
4662 }
4663
4664 // If the original was negative, invert the result, producing 1/(x*x*x).
4665 if (RHSC->getSExtValue() < 0)
4666 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4667 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4668 return Res;
4669 }
4670 }
4671
4672 // Otherwise, expand to a libcall.
4673 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4674}
4675
4676// getUnderlyingArgReg - Find underlying register used for a truncated or
4677// bitcasted argument.
4678static unsigned getUnderlyingArgReg(const SDValue &N) {
4679 switch (N.getOpcode()) {
4680 case ISD::CopyFromReg:
4681 return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4682 case ISD::BITCAST:
4683 case ISD::AssertZext:
4684 case ISD::AssertSext:
4685 case ISD::TRUNCATE:
4686 return getUnderlyingArgReg(N.getOperand(0));
4687 default:
4688 return 0;
4689 }
4690}
4691
4692/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4693/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4694/// At the end of instruction selection, they will be inserted to the entry BB.
4695bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4696 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4697 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
4698 const Argument *Arg = dyn_cast<Argument>(V);
4699 if (!Arg)
4700 return false;
4701
4702 MachineFunction &MF = DAG.getMachineFunction();
4703 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4704
4705 // Ignore inlined function arguments here.
4706 //
4707 // FIXME: Should we be checking DL->inlinedAt() to determine this?
4708 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
4709 return false;
4710
4711 Optional<MachineOperand> Op;
4712 // Some arguments' frame index is recorded during argument lowering.
4713 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4714 Op = MachineOperand::CreateFI(FI);
4715
4716 if (!Op && N.getNode()) {
4717 unsigned Reg = getUnderlyingArgReg(N);
4718 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4719 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4720 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4721 if (PR)
4722 Reg = PR;
4723 }
4724 if (Reg)
4725 Op = MachineOperand::CreateReg(Reg, false);
4726 }
4727
4728 if (!Op) {
4729 // Check if ValueMap has reg number.
4730 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4731 if (VMI != FuncInfo.ValueMap.end())
4732 Op = MachineOperand::CreateReg(VMI->second, false);
4733 }
4734
4735 if (!Op && N.getNode())
4736 // Check if frame index is available.
4737 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4738 if (FrameIndexSDNode *FINode =
4739 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4740 Op = MachineOperand::CreateFI(FINode->getIndex());
4741
4742 if (!Op)
4743 return false;
4744
4745 assert(Variable->isValidLocationForIntrinsic(DL) &&((Variable->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Variable->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 4746, __PRETTY_FUNCTION__))
4746 "Expected inlined-at fields to agree")((Variable->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Variable->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 4746, __PRETTY_FUNCTION__))
;
4747 if (Op->isReg())
4748 FuncInfo.ArgDbgValues.push_back(
4749 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4750 Op->getReg(), Offset, Variable, Expr));
4751 else
4752 FuncInfo.ArgDbgValues.push_back(
4753 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4754 .addOperand(*Op)
4755 .addImm(Offset)
4756 .addMetadata(Variable)
4757 .addMetadata(Expr));
4758
4759 return true;
4760}
4761
4762/// Return the appropriate SDDbgValue based on N.
4763SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4764 DILocalVariable *Variable,
4765 DIExpression *Expr, int64_t Offset,
4766 DebugLoc dl,
4767 unsigned DbgSDNodeOrder) {
4768 SDDbgValue *SDV;
4769 auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode());
4770 if (FISDN && Expr->startsWithDeref()) {
4771 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4772 // stack slot locations as such instead of as indirectly addressed
4773 // locations.
4774 ArrayRef<uint64_t> TrailingElements(Expr->elements_begin() + 1,
4775 Expr->elements_end());
4776 DIExpression *DerefedDIExpr =
4777 DIExpression::get(*DAG.getContext(), TrailingElements);
4778 int FI = FISDN->getIndex();
4779 SDV = DAG.getFrameIndexDbgValue(Variable, DerefedDIExpr, FI, 0, dl,
4780 DbgSDNodeOrder);
4781 } else {
4782 SDV = DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false,
4783 Offset, dl, DbgSDNodeOrder);
4784 }
4785 return SDV;
4786}
4787
4788// VisualStudio defines setjmp as _setjmp
4789#if defined(_MSC_VER) && defined(setjmp) && \
4790 !defined(setjmp_undefined_for_msvc)
4791# pragma push_macro("setjmp")
4792# undef setjmp
4793# define setjmp_undefined_for_msvc
4794#endif
4795
4796/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4797/// we want to emit this as a call to a named external function, return the name
4798/// otherwise lower it and return null.
4799const char *
4800SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4802 SDLoc sdl = getCurSDLoc();
4803 DebugLoc dl = getCurDebugLoc();
4804 SDValue Res;
4805
4806 switch (Intrinsic) {
4807 default:
4808 // By default, turn this into a target intrinsic node.
4809 visitTargetIntrinsic(I, Intrinsic);
4810 return nullptr;
4811 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4812 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4813 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4814 case Intrinsic::returnaddress:
4815 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4816 TLI.getPointerTy(DAG.getDataLayout()),
4817 getValue(I.getArgOperand(0))));
4818 return nullptr;
4819 case Intrinsic::addressofreturnaddress:
4820 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
4821 TLI.getPointerTy(DAG.getDataLayout())));
4822 return nullptr;
4823 case Intrinsic::frameaddress:
4824 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4825 TLI.getPointerTy(DAG.getDataLayout()),
4826 getValue(I.getArgOperand(0))));
4827 return nullptr;
4828 case Intrinsic::read_register: {
4829 Value *Reg = I.getArgOperand(0);
4830 SDValue Chain = getRoot();
4831 SDValue RegName =
4832 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4833 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4834 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4835 DAG.getVTList(VT, MVT::Other), Chain, RegName);
4836 setValue(&I, Res);
4837 DAG.setRoot(Res.getValue(1));
4838 return nullptr;
4839 }
4840 case Intrinsic::write_register: {
4841 Value *Reg = I.getArgOperand(0);
4842 Value *RegValue = I.getArgOperand(1);
4843 SDValue Chain = getRoot();
4844 SDValue RegName =
4845 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4846 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4847 RegName, getValue(RegValue)));
4848 return nullptr;
4849 }
4850 case Intrinsic::setjmp:
4851 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4852 case Intrinsic::longjmp:
4853 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4854 case Intrinsic::memcpy: {
4855 SDValue Op1 = getValue(I.getArgOperand(0));
4856 SDValue Op2 = getValue(I.getArgOperand(1));
4857 SDValue Op3 = getValue(I.getArgOperand(2));
4858 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4859 if (!Align)
4860 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4861 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4862 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4863 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4864 false, isTC,
4865 MachinePointerInfo(I.getArgOperand(0)),
4866 MachinePointerInfo(I.getArgOperand(1)));
4867 updateDAGForMaybeTailCall(MC);
4868 return nullptr;
4869 }
4870 case Intrinsic::memset: {
4871 SDValue Op1 = getValue(I.getArgOperand(0));
4872 SDValue Op2 = getValue(I.getArgOperand(1));
4873 SDValue Op3 = getValue(I.getArgOperand(2));
4874 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4875 if (!Align)
4876 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4877 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4878 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4879 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4880 isTC, MachinePointerInfo(I.getArgOperand(0)));
4881 updateDAGForMaybeTailCall(MS);
4882 return nullptr;
4883 }
4884 case Intrinsic::memmove: {
4885 SDValue Op1 = getValue(I.getArgOperand(0));
4886 SDValue Op2 = getValue(I.getArgOperand(1));
4887 SDValue Op3 = getValue(I.getArgOperand(2));
4888 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4889 if (!Align)
4890 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4891 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4892 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4893 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4894 isTC, MachinePointerInfo(I.getArgOperand(0)),
4895 MachinePointerInfo(I.getArgOperand(1)));
4896 updateDAGForMaybeTailCall(MM);
4897 return nullptr;
4898 }
4899 case Intrinsic::memcpy_element_atomic: {
4900 SDValue Dst = getValue(I.getArgOperand(0));
4901 SDValue Src = getValue(I.getArgOperand(1));
4902 SDValue NumElements = getValue(I.getArgOperand(2));
4903 SDValue ElementSize = getValue(I.getArgOperand(3));
4904
4905 // Emit a library call.
4906 TargetLowering::ArgListTy Args;
4907 TargetLowering::ArgListEntry Entry;
4908 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
4909 Entry.Node = Dst;
4910 Args.push_back(Entry);
4911
4912 Entry.Node = Src;
4913 Args.push_back(Entry);
4914
4915 Entry.Ty = I.getArgOperand(2)->getType();
4916 Entry.Node = NumElements;
4917 Args.push_back(Entry);
4918
4919 Entry.Ty = Type::getInt32Ty(*DAG.getContext());
4920 Entry.Node = ElementSize;
4921 Args.push_back(Entry);
4922
4923 uint64_t ElementSizeConstant =
4924 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4925 RTLIB::Libcall LibraryCall =
4926 RTLIB::getMEMCPY_ELEMENT_ATOMIC(ElementSizeConstant);
4927 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
4928 report_fatal_error("Unsupported element size");
4929
4930 TargetLowering::CallLoweringInfo CLI(DAG);
4931 CLI.setDebugLoc(sdl)
4932 .setChain(getRoot())
4933 .setCallee(TLI.getLibcallCallingConv(LibraryCall),
4934 Type::getVoidTy(*DAG.getContext()),
4935 DAG.getExternalSymbol(
4936 TLI.getLibcallName(LibraryCall),
4937 TLI.getPointerTy(DAG.getDataLayout())),
4938 std::move(Args));
4939
4940 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
4941 DAG.setRoot(CallResult.second);
4942 return nullptr;
4943 }
4944 case Intrinsic::dbg_declare: {
4945 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4946 DILocalVariable *Variable = DI.getVariable();
4947 DIExpression *Expression = DI.getExpression();
4948 const Value *Address = DI.getAddress();
4949 assert(Variable && "Missing variable")((Variable && "Missing variable") ? static_cast<void
> (0) : __assert_fail ("Variable && \"Missing variable\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 4949, __PRETTY_FUNCTION__))
;
4950 if (!Address) {
4951 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
DI << "\n"; } } while (false)
;
4952 return nullptr;
4953 }
4954
4955 // Check if address has undef value.
4956 if (isa<UndefValue>(Address) ||
4957 (Address->use_empty() && !isa<Argument>(Address))) {
4958 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
DI << "\n"; } } while (false)
;
4959 return nullptr;
4960 }
4961
4962 SDValue &N = NodeMap[Address];
4963 if (!N.getNode() && isa<Argument>(Address))
4964 // Check unused arguments map.
4965 N = UnusedArgNodeMap[Address];
4966 SDDbgValue *SDV;
4967 if (N.getNode()) {
4968 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4969 Address = BCI->getOperand(0);
4970 // Parameters are handled specially.
4971 bool isParameter = Variable->isParameter() || isa<Argument>(Address);
4972 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4973 if (isParameter && FINode) {
4974 // Byval parameter. We have a frame index at this point.
4975 SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
4976 FINode->getIndex(), 0, dl, SDNodeOrder);
4977 } else if (isa<Argument>(Address)) {
4978 // Address is an argument, so try to emit its dbg value using
4979 // virtual register info from the FuncInfo.ValueMap.
4980 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4981 N);
4982 return nullptr;
4983 } else {
4984 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4985 true, 0, dl, SDNodeOrder);
4986 }
4987 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4988 } else {
4989 // If Address is an argument then try to emit its dbg value using
4990 // virtual register info from the FuncInfo.ValueMap.
4991 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4992 N)) {
4993 // If variable is pinned by a alloca in dominating bb then
4994 // use StaticAllocaMap.
4995 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4996 if (AI->getParent() != DI.getParent()) {
4997 DenseMap<const AllocaInst*, int>::iterator SI =
4998 FuncInfo.StaticAllocaMap.find(AI);
4999 if (SI != FuncInfo.StaticAllocaMap.end()) {
5000 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
5001 0, dl, SDNodeOrder);
5002 DAG.AddDbgValue(SDV, nullptr, false);
5003 return nullptr;
5004 }
5005 }
5006 }
5007 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
DI << "\n"; } } while (false)
;
5008 }
5009 }
5010 return nullptr;
5011 }
5012 case Intrinsic::dbg_value: {
5013 const DbgValueInst &DI = cast<DbgValueInst>(I);
5014 assert(DI.getVariable() && "Missing variable")((DI.getVariable() && "Missing variable") ? static_cast
<void> (0) : __assert_fail ("DI.getVariable() && \"Missing variable\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5014, __PRETTY_FUNCTION__))
;
5015
5016 DILocalVariable *Variable = DI.getVariable();
5017 DIExpression *Expression = DI.getExpression();
5018 uint64_t Offset = DI.getOffset();
5019 const Value *V = DI.getValue();
5020 if (!V)
5021 return nullptr;
5022
5023 SDDbgValue *SDV;
5024 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5025 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
5026 SDNodeOrder);
5027 DAG.AddDbgValue(SDV, nullptr, false);
5028 } else {
5029 // Do not use getValue() in here; we don't want to generate code at
5030 // this point if it hasn't been done yet.
5031 SDValue N = NodeMap[V];
5032 if (!N.getNode() && isa<Argument>(V))
5033 // Check unused arguments map.
5034 N = UnusedArgNodeMap[V];
5035 if (N.getNode()) {
5036 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
5037 false, N)) {
5038 SDV = getDbgValue(N, Variable, Expression, Offset, dl, SDNodeOrder);
5039 DAG.AddDbgValue(SDV, N.getNode(), false);
5040 }
5041 } else if (!V->use_empty() ) {
5042 // Do not call getValue(V) yet, as we don't want to generate code.
5043 // Remember it for later.
5044 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5045 DanglingDebugInfoMap[V] = DDI;
5046 } else {
5047 // We may expand this to cover more cases. One case where we have no
5048 // data available is an unreferenced parameter.
5049 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
DI << "\n"; } } while (false)
;
5050 }
5051 }
5052
5053 // Build a debug info table entry.
5054 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
5055 V = BCI->getOperand(0);
5056 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
5057 // Don't handle byval struct arguments or VLAs, for example.
5058 if (!AI) {
5059 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug location info for:\n "
<< DI << "\n"; } } while (false)
;
5060 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << " Last seen at:\n " << *
V << "\n"; } } while (false)
;
5061 return nullptr;
5062 }
5063 DenseMap<const AllocaInst*, int>::iterator SI =
5064 FuncInfo.StaticAllocaMap.find(AI);
5065 if (SI == FuncInfo.StaticAllocaMap.end())
5066 return nullptr; // VLAs.
5067 return nullptr;
5068 }
5069
5070 case Intrinsic::eh_typeid_for: {
5071 // Find the type id for the given typeinfo.
5072 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5073 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5074 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5075 setValue(&I, Res);
5076 return nullptr;
5077 }
5078
5079 case Intrinsic::eh_return_i32:
5080 case Intrinsic::eh_return_i64:
5081 DAG.getMachineFunction().setCallsEHReturn(true);
5082 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5083 MVT::Other,
5084 getControlRoot(),
5085 getValue(I.getArgOperand(0)),
5086 getValue(I.getArgOperand(1))));
5087 return nullptr;
5088 case Intrinsic::eh_unwind_init:
5089 DAG.getMachineFunction().setCallsUnwindInit(true);
5090 return nullptr;
5091 case Intrinsic::eh_dwarf_cfa: {
5092 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5093 TLI.getPointerTy(DAG.getDataLayout()),
5094 getValue(I.getArgOperand(0))));
5095 return nullptr;
5096 }
5097 case Intrinsic::eh_sjlj_callsite: {
5098 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5099 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5100 assert(CI && "Non-constant call site value in eh.sjlj.callsite!")((CI && "Non-constant call site value in eh.sjlj.callsite!"
) ? static_cast<void> (0) : __assert_fail ("CI && \"Non-constant call site value in eh.sjlj.callsite!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5100, __PRETTY_FUNCTION__))
;
5101 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!")((MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"
) ? static_cast<void> (0) : __assert_fail ("MMI.getCurrentCallSite() == 0 && \"Overlapping call sites!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5101, __PRETTY_FUNCTION__))
;
5102
5103 MMI.setCurrentCallSite(CI->getZExtValue());
5104 return nullptr;
5105 }
5106 case Intrinsic::eh_sjlj_functioncontext: {
5107 // Get and store the index of the function context.
5108 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5109 AllocaInst *FnCtx =
5110 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5111 int FI = FuncInfo.StaticAllocaMap[FnCtx];
5112 MFI.setFunctionContextIndex(FI);
5113 return nullptr;
5114 }
5115 case Intrinsic::eh_sjlj_setjmp: {
5116 SDValue Ops[2];
5117 Ops[0] = getRoot();
5118 Ops[1] = getValue(I.getArgOperand(0));
5119 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5120 DAG.getVTList(MVT::i32, MVT::Other), Ops);
5121 setValue(&I, Op.getValue(0));
5122 DAG.setRoot(Op.getValue(1));
5123 return nullptr;
5124 }
5125 case Intrinsic::eh_sjlj_longjmp: {
5126 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5127 getRoot(), getValue(I.getArgOperand(0))));
5128 return nullptr;
5129 }
5130 case Intrinsic::eh_sjlj_setup_dispatch: {
5131 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5132 getRoot()));
5133 return nullptr;
5134 }
5135
5136 case Intrinsic::masked_gather:
5137 visitMaskedGather(I);
5138 return nullptr;
5139 case Intrinsic::masked_load:
5140 visitMaskedLoad(I);
5141 return nullptr;
5142 case Intrinsic::masked_scatter:
5143 visitMaskedScatter(I);
5144 return nullptr;
5145 case Intrinsic::masked_store:
5146 visitMaskedStore(I);
5147 return nullptr;
5148 case Intrinsic::masked_expandload:
5149 visitMaskedLoad(I, true /* IsExpanding */);
5150 return nullptr;
5151 case Intrinsic::masked_compressstore:
5152 visitMaskedStore(I, true /* IsCompressing */);
5153 return nullptr;
5154 case Intrinsic::x86_mmx_pslli_w:
5155 case Intrinsic::x86_mmx_pslli_d:
5156 case Intrinsic::x86_mmx_pslli_q:
5157 case Intrinsic::x86_mmx_psrli_w:
5158 case Intrinsic::x86_mmx_psrli_d:
5159 case Intrinsic::x86_mmx_psrli_q:
5160 case Intrinsic::x86_mmx_psrai_w:
5161 case Intrinsic::x86_mmx_psrai_d: {
5162 SDValue ShAmt = getValue(I.getArgOperand(1));
5163 if (isa<ConstantSDNode>(ShAmt)) {
5164 visitTargetIntrinsic(I, Intrinsic);
5165 return nullptr;
5166 }
5167 unsigned NewIntrinsic = 0;
5168 EVT ShAmtVT = MVT::v2i32;
5169 switch (Intrinsic) {
5170 case Intrinsic::x86_mmx_pslli_w:
5171 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5172 break;
5173 case Intrinsic::x86_mmx_pslli_d:
5174 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5175 break;
5176 case Intrinsic::x86_mmx_pslli_q:
5177 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5178 break;
5179 case Intrinsic::x86_mmx_psrli_w:
5180 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5181 break;
5182 case Intrinsic::x86_mmx_psrli_d:
5183 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5184 break;
5185 case Intrinsic::x86_mmx_psrli_q:
5186 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5187 break;
5188 case Intrinsic::x86_mmx_psrai_w:
5189 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5190 break;
5191 case Intrinsic::x86_mmx_psrai_d:
5192 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5193 break;
5194 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5194)
; // Can't reach here.
5195 }
5196
5197 // The vector shift intrinsics with scalars uses 32b shift amounts but
5198 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5199 // to be zero.
5200 // We must do this early because v2i32 is not a legal type.
5201 SDValue ShOps[2];
5202 ShOps[0] = ShAmt;
5203 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5204 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
5205 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5206 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5207 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5208 DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5209 getValue(I.getArgOperand(0)), ShAmt);
5210 setValue(&I, Res);
5211 return nullptr;
5212 }
5213 case Intrinsic::convertff:
5214 case Intrinsic::convertfsi:
5215 case Intrinsic::convertfui:
5216 case Intrinsic::convertsif:
5217 case Intrinsic::convertuif:
5218 case Intrinsic::convertss:
5219 case Intrinsic::convertsu:
5220 case Intrinsic::convertus:
5221 case Intrinsic::convertuu: {
5222 ISD::CvtCode Code = ISD::CVT_INVALID;
5223 switch (Intrinsic) {
5224 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5224)
; // Can't reach here.
5225 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5226 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5227 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5228 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5229 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5230 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5231 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5232 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5233 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5234 }
5235 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5236 const Value *Op1 = I.getArgOperand(0);
5237 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
5238 DAG.getValueType(DestVT),
5239 DAG.getValueType(getValue(Op1).getValueType()),
5240 getValue(I.getArgOperand(1)),
5241 getValue(I.getArgOperand(2)),
5242 Code);
5243 setValue(&I, Res);
5244 return nullptr;
5245 }
5246 case Intrinsic::powi:
5247 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5248 getValue(I.getArgOperand(1)), DAG));
5249 return nullptr;
5250 case Intrinsic::log:
5251 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5252 return nullptr;
5253 case Intrinsic::log2:
5254 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5255 return nullptr;
5256 case Intrinsic::log10:
5257 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5258 return nullptr;
5259 case Intrinsic::exp:
5260 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5261 return nullptr;
5262 case Intrinsic::exp2:
5263 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5264 return nullptr;
5265 case Intrinsic::pow:
5266 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5267 getValue(I.getArgOperand(1)), DAG, TLI));
5268 return nullptr;
5269 case Intrinsic::sqrt:
5270 case Intrinsic::fabs:
5271 case Intrinsic::sin:
5272 case Intrinsic::cos:
5273 case Intrinsic::floor:
5274 case Intrinsic::ceil:
5275 case Intrinsic::trunc:
5276 case Intrinsic::rint:
5277 case Intrinsic::nearbyint:
5278 case Intrinsic::round:
5279 case Intrinsic::canonicalize: {
5280 unsigned Opcode;
5281 switch (Intrinsic) {
5282 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5282)
; // Can't reach here.
5283 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5284 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5285 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5286 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5287 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5288 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5289 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5290 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5291 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5292 case Intrinsic::round: Opcode = ISD::FROUND; break;
5293 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5294 }
5295
5296 setValue(&I, DAG.getNode(Opcode, sdl,
5297 getValue(I.getArgOperand(0)).getValueType(),
5298 getValue(I.getArgOperand(0))));
5299 return nullptr;
5300 }
5301 case Intrinsic::minnum: {
5302 auto VT = getValue(I.getArgOperand(0)).getValueType();
5303 unsigned Opc =
5304 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5305 ? ISD::FMINNAN
5306 : ISD::FMINNUM;
5307 setValue(&I, DAG.getNode(Opc, sdl, VT,
5308 getValue(I.getArgOperand(0)),
5309 getValue(I.getArgOperand(1))));
5310 return nullptr;
5311 }
5312 case Intrinsic::maxnum: {
5313 auto VT = getValue(I.getArgOperand(0)).getValueType();
5314 unsigned Opc =
5315 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5316 ? ISD::FMAXNAN
5317 : ISD::FMAXNUM;
5318 setValue(&I, DAG.getNode(Opc, sdl, VT,
5319 getValue(I.getArgOperand(0)),
5320 getValue(I.getArgOperand(1))));
5321 return nullptr;
5322 }
5323 case Intrinsic::copysign:
5324 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5325 getValue(I.getArgOperand(0)).getValueType(),
5326 getValue(I.getArgOperand(0)),
5327 getValue(I.getArgOperand(1))));
5328 return nullptr;
5329 case Intrinsic::fma:
5330 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5331 getValue(I.getArgOperand(0)).getValueType(),
5332 getValue(I.getArgOperand(0)),
5333 getValue(I.getArgOperand(1)),
5334 getValue(I.getArgOperand(2))));
5335 return nullptr;
5336 case Intrinsic::fmuladd: {
5337 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5338 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5339 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5340 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5341 getValue(I.getArgOperand(0)).getValueType(),
5342 getValue(I.getArgOperand(0)),
5343 getValue(I.getArgOperand(1)),
5344 getValue(I.getArgOperand(2))));
5345 } else {
5346 // TODO: Intrinsic calls should have fast-math-flags.
5347 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5348 getValue(I.getArgOperand(0)).getValueType(),
5349 getValue(I.getArgOperand(0)),
5350 getValue(I.getArgOperand(1)));
5351 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5352 getValue(I.getArgOperand(0)).getValueType(),
5353 Mul,
5354 getValue(I.getArgOperand(2)));
5355 setValue(&I, Add);
5356 }
5357 return nullptr;
5358 }
5359 case Intrinsic::convert_to_fp16:
5360 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5361 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5362 getValue(I.getArgOperand(0)),
5363 DAG.getTargetConstant(0, sdl,
5364 MVT::i32))));
5365 return nullptr;
5366 case Intrinsic::convert_from_fp16:
5367 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5368 TLI.getValueType(DAG.getDataLayout(), I.getType()),
5369 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5370 getValue(I.getArgOperand(0)))));
5371 return nullptr;
5372 case Intrinsic::pcmarker: {
5373 SDValue Tmp = getValue(I.getArgOperand(0));
5374 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5375 return nullptr;
5376 }
5377 case Intrinsic::readcyclecounter: {
5378 SDValue Op = getRoot();
5379 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5380 DAG.getVTList(MVT::i64, MVT::Other), Op);
5381 setValue(&I, Res);
5382 DAG.setRoot(Res.getValue(1));
5383 return nullptr;
5384 }
5385 case Intrinsic::bitreverse:
5386 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5387 getValue(I.getArgOperand(0)).getValueType(),
5388 getValue(I.getArgOperand(0))));
5389 return nullptr;
5390 case Intrinsic::bswap:
5391 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5392 getValue(I.getArgOperand(0)).getValueType(),
5393 getValue(I.getArgOperand(0))));
5394 return nullptr;
5395 case Intrinsic::cttz: {
5396 SDValue Arg = getValue(I.getArgOperand(0));
5397 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5398 EVT Ty = Arg.getValueType();
5399 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5400 sdl, Ty, Arg));
5401 return nullptr;
5402 }
5403 case Intrinsic::ctlz: {
5404 SDValue Arg = getValue(I.getArgOperand(0));
5405 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5406 EVT Ty = Arg.getValueType();
5407 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5408 sdl, Ty, Arg));
5409 return nullptr;
5410 }
5411 case Intrinsic::ctpop: {
5412 SDValue Arg = getValue(I.getArgOperand(0));
5413 EVT Ty = Arg.getValueType();
5414 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5415 return nullptr;
5416 }
5417 case Intrinsic::stacksave: {
5418 SDValue Op = getRoot();
5419 Res = DAG.getNode(
5420 ISD::STACKSAVE, sdl,
5421 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5422 setValue(&I, Res);
5423 DAG.setRoot(Res.getValue(1));
5424 return nullptr;
5425 }
5426 case Intrinsic::stackrestore: {
5427 Res = getValue(I.getArgOperand(0));
5428 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5429 return nullptr;
5430 }
5431 case Intrinsic::get_dynamic_area_offset: {
5432 SDValue Op = getRoot();
5433 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5434 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5435 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5436 // target.
5437 if (PtrTy != ResTy)
5438 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5439 " intrinsic!");
5440 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5441 Op);
5442 DAG.setRoot(Op);
5443 setValue(&I, Res);
5444 return nullptr;
5445 }
5446 case Intrinsic::stackguard: {
5447 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5448 MachineFunction &MF = DAG.getMachineFunction();
5449 const Module &M = *MF.getFunction()->getParent();
5450 SDValue Chain = getRoot();
5451 if (TLI.useLoadStackGuardNode()) {
5452 Res = getLoadStackGuard(DAG, sdl, Chain);
5453 } else {
5454 const Value *Global = TLI.getSDagStackGuard(M);
5455 unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5456 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5457 MachinePointerInfo(Global, 0), Align,
5458 MachineMemOperand::MOVolatile);
5459 }
5460 DAG.setRoot(Chain);
5461 setValue(&I, Res);
5462 return nullptr;
5463 }
5464 case Intrinsic::stackprotector: {
5465 // Emit code into the DAG to store the stack guard onto the stack.
5466 MachineFunction &MF = DAG.getMachineFunction();
5467 MachineFrameInfo &MFI = MF.getFrameInfo();
5468 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5469 SDValue Src, Chain = getRoot();
5470
5471 if (TLI.useLoadStackGuardNode())
5472 Src = getLoadStackGuard(DAG, sdl, Chain);
5473 else
5474 Src = getValue(I.getArgOperand(0)); // The guard's value.
5475
5476 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5477
5478 int FI = FuncInfo.StaticAllocaMap[Slot];
5479 MFI.setStackProtectorIndex(FI);
5480
5481 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5482
5483 // Store the stack protector onto the stack.
5484 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5485 DAG.getMachineFunction(), FI),
5486 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5487 setValue(&I, Res);
5488 DAG.setRoot(Res);
5489 return nullptr;
5490 }
5491 case Intrinsic::objectsize: {
5492 // If we don't know by now, we're never going to know.
5493 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5494
5495 assert(CI && "Non-constant type in __builtin_object_size?")((CI && "Non-constant type in __builtin_object_size?"
) ? static_cast<void> (0) : __assert_fail ("CI && \"Non-constant type in __builtin_object_size?\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5495, __PRETTY_FUNCTION__))
;
5496
5497 SDValue Arg = getValue(I.getCalledValue());
5498 EVT Ty = Arg.getValueType();
5499
5500 if (CI->isZero())
5501 Res = DAG.getConstant(-1ULL, sdl, Ty);
5502 else
5503 Res = DAG.getConstant(0, sdl, Ty);
5504
5505 setValue(&I, Res);
5506 return nullptr;
5507 }
5508 case Intrinsic::annotation:
5509 case Intrinsic::ptr_annotation:
5510 case Intrinsic::invariant_group_barrier:
5511 // Drop the intrinsic, but forward the value
5512 setValue(&I, getValue(I.getOperand(0)));
5513 return nullptr;
5514 case Intrinsic::assume:
5515 case Intrinsic::var_annotation:
5516 // Discard annotate attributes and assumptions
5517 return nullptr;
5518
5519 case Intrinsic::init_trampoline: {
5520 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5521
5522 SDValue Ops[6];
5523 Ops[0] = getRoot();
5524 Ops[1] = getValue(I.getArgOperand(0));
5525 Ops[2] = getValue(I.getArgOperand(1));
5526 Ops[3] = getValue(I.getArgOperand(2));
5527 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5528 Ops[5] = DAG.getSrcValue(F);
5529
5530 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5531
5532 DAG.setRoot(Res);
5533 return nullptr;
5534 }
5535 case Intrinsic::adjust_trampoline: {
5536 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5537 TLI.getPointerTy(DAG.getDataLayout()),
5538 getValue(I.getArgOperand(0))));
5539 return nullptr;
5540 }
5541 case Intrinsic::gcroot: {
5542 MachineFunction &MF = DAG.getMachineFunction();
5543 const Function *F = MF.getFunction();
5544 (void)F;
5545 assert(F->hasGC() &&((F->hasGC() && "only valid in functions with gc specified, enforced by Verifier"
) ? static_cast<void> (0) : __assert_fail ("F->hasGC() && \"only valid in functions with gc specified, enforced by Verifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5546, __PRETTY_FUNCTION__))
5546 "only valid in functions with gc specified, enforced by Verifier")((F->hasGC() && "only valid in functions with gc specified, enforced by Verifier"
) ? static_cast<void> (0) : __assert_fail ("F->hasGC() && \"only valid in functions with gc specified, enforced by Verifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5546, __PRETTY_FUNCTION__))
;
5547 assert(GFI && "implied by previous")((GFI && "implied by previous") ? static_cast<void
> (0) : __assert_fail ("GFI && \"implied by previous\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5547, __PRETTY_FUNCTION__))
;
5548 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5549 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5550
5551 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5552 GFI->addStackRoot(FI->getIndex(), TypeMap);
5553 return nullptr;
5554 }
5555 case Intrinsic::gcread:
5556 case Intrinsic::gcwrite:
5557 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!")::llvm::llvm_unreachable_internal("GC failed to lower gcread/gcwrite intrinsics!"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5557)
;
5558 case Intrinsic::flt_rounds:
5559 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5560 return nullptr;
5561
5562 case Intrinsic::expect: {
5563 // Just replace __builtin_expect(exp, c) with EXP.
5564 setValue(&I, getValue(I.getArgOperand(0)));
5565 return nullptr;
5566 }
5567
5568 case Intrinsic::debugtrap:
5569 case Intrinsic::trap: {
5570 StringRef TrapFuncName =
5571 I.getAttributes()
5572 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
5573 .getValueAsString();
5574 if (TrapFuncName.empty()) {
5575 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5576 ISD::TRAP : ISD::DEBUGTRAP;
5577 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5578 return nullptr;
5579 }
5580 TargetLowering::ArgListTy Args;
5581
5582 TargetLowering::CallLoweringInfo CLI(DAG);
5583 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
5584 CallingConv::C, I.getType(),
5585 DAG.getExternalSymbol(TrapFuncName.data(),
5586 TLI.getPointerTy(DAG.getDataLayout())),
5587 std::move(Args));
5588
5589 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5590 DAG.setRoot(Result.second);
5591 return nullptr;
5592 }
5593
5594 case Intrinsic::uadd_with_overflow:
5595 case Intrinsic::sadd_with_overflow:
5596 case Intrinsic::usub_with_overflow:
5597 case Intrinsic::ssub_with_overflow:
5598 case Intrinsic::umul_with_overflow:
5599 case Intrinsic::smul_with_overflow: {
5600 ISD::NodeType Op;
5601 switch (Intrinsic) {
5602 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5602)
; // Can't reach here.
5603 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5604 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5605 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5606 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5607 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5608 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5609 }
5610 SDValue Op1 = getValue(I.getArgOperand(0));
5611 SDValue Op2 = getValue(I.getArgOperand(1));
5612
5613 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5614 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5615 return nullptr;
5616 }
5617 case Intrinsic::prefetch: {
5618 SDValue Ops[5];
5619 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5620 Ops[0] = getRoot();
5621 Ops[1] = getValue(I.getArgOperand(0));
5622 Ops[2] = getValue(I.getArgOperand(1));
5623 Ops[3] = getValue(I.getArgOperand(2));
5624 Ops[4] = getValue(I.getArgOperand(3));
5625 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5626 DAG.getVTList(MVT::Other), Ops,
5627 EVT::getIntegerVT(*Context, 8),
5628 MachinePointerInfo(I.getArgOperand(0)),
5629 0, /* align */
5630 false, /* volatile */
5631 rw==0, /* read */
5632 rw==1)); /* write */
5633 return nullptr;
5634 }
5635 case Intrinsic::lifetime_start:
5636 case Intrinsic::lifetime_end: {
5637 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5638 // Stack coloring is not enabled in O0, discard region information.
5639 if (TM.getOptLevel() == CodeGenOpt::None)
5640 return nullptr;
5641
5642 SmallVector<Value *, 4> Allocas;
5643 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5644
5645 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5646 E = Allocas.end(); Object != E; ++Object) {
5647 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5648
5649 // Could not find an Alloca.
5650 if (!LifetimeObject)
5651 continue;
5652
5653 // First check that the Alloca is static, otherwise it won't have a
5654 // valid frame index.
5655 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5656 if (SI == FuncInfo.StaticAllocaMap.end())
5657 return nullptr;
5658
5659 int FI = SI->second;
5660
5661 SDValue Ops[2];
5662 Ops[0] = getRoot();
5663 Ops[1] =
5664 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
5665 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5666
5667 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5668 DAG.setRoot(Res);
5669 }
5670 return nullptr;
5671 }
5672 case Intrinsic::invariant_start:
5673 // Discard region information.
5674 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5675 return nullptr;
5676 case Intrinsic::invariant_end:
5677 // Discard region information.
5678 return nullptr;
5679 case Intrinsic::clear_cache:
5680 return TLI.getClearCacheBuiltinName();
5681 case Intrinsic::donothing:
5682 // ignore
5683 return nullptr;
5684 case Intrinsic::experimental_stackmap: {
5685 visitStackmap(I);
5686 return nullptr;
5687 }
5688 case Intrinsic::experimental_patchpoint_void:
5689 case Intrinsic::experimental_patchpoint_i64: {
5690 visitPatchpoint(&I);
5691 return nullptr;
5692 }
5693 case Intrinsic::experimental_gc_statepoint: {
5694 LowerStatepoint(ImmutableStatepoint(&I));
5695 return nullptr;
5696 }
5697 case Intrinsic::experimental_gc_result: {
5698 visitGCResult(cast<GCResultInst>(I));
5699 return nullptr;
5700 }
5701 case Intrinsic::experimental_gc_relocate: {
5702 visitGCRelocate(cast<GCRelocateInst>(I));
5703 return nullptr;
5704 }
5705 case Intrinsic::instrprof_increment:
5706 llvm_unreachable("instrprof failed to lower an increment")::llvm::llvm_unreachable_internal("instrprof failed to lower an increment"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5706)
;
5707 case Intrinsic::instrprof_value_profile:
5708 llvm_unreachable("instrprof failed to lower a value profiling call")::llvm::llvm_unreachable_internal("instrprof failed to lower a value profiling call"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5708)
;
5709 case Intrinsic::localescape: {
5710 MachineFunction &MF = DAG.getMachineFunction();
5711 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5712
5713 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5714 // is the same on all targets.
5715 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5716 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5717 if (isa<ConstantPointerNull>(Arg))
5718 continue; // Skip null pointers. They represent a hole in index space.
5719 AllocaInst *Slot = cast<AllocaInst>(Arg);
5720 assert(FuncInfo.StaticAllocaMap.count(Slot) &&((FuncInfo.StaticAllocaMap.count(Slot) && "can only escape static allocas"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.StaticAllocaMap.count(Slot) && \"can only escape static allocas\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5721, __PRETTY_FUNCTION__))
5721 "can only escape static allocas")((FuncInfo.StaticAllocaMap.count(Slot) && "can only escape static allocas"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.StaticAllocaMap.count(Slot) && \"can only escape static allocas\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5721, __PRETTY_FUNCTION__))
;
5722 int FI = FuncInfo.StaticAllocaMap[Slot];
5723 MCSymbol *FrameAllocSym =
5724 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5725 GlobalValue::getRealLinkageName(MF.getName()), Idx);
5726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5727 TII->get(TargetOpcode::LOCAL_ESCAPE))
5728 .addSym(FrameAllocSym)
5729 .addFrameIndex(FI);
5730 }
5731
5732 return nullptr;
5733 }
5734
5735 case Intrinsic::localrecover: {
5736 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5737 MachineFunction &MF = DAG.getMachineFunction();
5738 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5739
5740 // Get the symbol that defines the frame offset.
5741 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5742 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5743 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX2147483647));
5744 MCSymbol *FrameAllocSym =
5745 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5746 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
5747
5748 // Create a MCSymbol for the label to avoid any target lowering
5749 // that would make this PC relative.
5750 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5751 SDValue OffsetVal =
5752 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5753
5754 // Add the offset to the FP.
5755 Value *FP = I.getArgOperand(1);
5756 SDValue FPVal = getValue(FP);
5757 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5758 setValue(&I, Add);
5759
5760 return nullptr;
5761 }
5762
5763 case Intrinsic::eh_exceptionpointer:
5764 case Intrinsic::eh_exceptioncode: {
5765 // Get the exception pointer vreg, copy from it, and resize it to fit.
5766 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5767 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5768 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5769 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5770 SDValue N =
5771 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5772 if (Intrinsic == Intrinsic::eh_exceptioncode)
5773 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5774 setValue(&I, N);
5775 return nullptr;
5776 }
5777
5778 case Intrinsic::experimental_deoptimize:
5779 LowerDeoptimizeCall(&I);
5780 return nullptr;
5781 }
5782}
5783
5784std::pair<SDValue, SDValue>
5785SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5786 const BasicBlock *EHPadBB) {
5787 MachineFunction &MF = DAG.getMachineFunction();
5788 MachineModuleInfo &MMI = MF.getMMI();
5789 MCSymbol *BeginLabel = nullptr;
5790
5791 if (EHPadBB) {
5792 // Insert a label before the invoke call to mark the try range. This can be
5793 // used to detect deletion of the invoke via the MachineModuleInfo.
5794 BeginLabel = MMI.getContext().createTempSymbol();
5795
5796 // For SjLj, keep track of which landing pads go with which invokes
5797 // so as to maintain the ordering of pads in the LSDA.
5798 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5799 if (CallSiteIndex) {
5800 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5801 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5802
5803 // Now that the call site is handled, stop tracking it.
5804 MMI.setCurrentCallSite(0);
5805 }
5806
5807 // Both PendingLoads and PendingExports must be flushed here;
5808 // this call might not return.
5809 (void)getRoot();
5810 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5811
5812 CLI.setChain(getRoot());
5813 }
5814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5815 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5816
5817 assert((CLI.IsTailCall || Result.second.getNode()) &&(((CLI.IsTailCall || Result.second.getNode()) && "Non-null chain expected with non-tail call!"
) ? static_cast<void> (0) : __assert_fail ("(CLI.IsTailCall || Result.second.getNode()) && \"Non-null chain expected with non-tail call!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5818, __PRETTY_FUNCTION__))
5818 "Non-null chain expected with non-tail call!")(((CLI.IsTailCall || Result.second.getNode()) && "Non-null chain expected with non-tail call!"
) ? static_cast<void> (0) : __assert_fail ("(CLI.IsTailCall || Result.second.getNode()) && \"Non-null chain expected with non-tail call!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5818, __PRETTY_FUNCTION__))
;
5819 assert((Result.second.getNode() || !Result.first.getNode()) &&(((Result.second.getNode() || !Result.first.getNode()) &&
"Null value expected with tail call!") ? static_cast<void
> (0) : __assert_fail ("(Result.second.getNode() || !Result.first.getNode()) && \"Null value expected with tail call!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5820, __PRETTY_FUNCTION__))
5820 "Null value expected with tail call!")(((Result.second.getNode() || !Result.first.getNode()) &&
"Null value expected with tail call!") ? static_cast<void
> (0) : __assert_fail ("(Result.second.getNode() || !Result.first.getNode()) && \"Null value expected with tail call!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5820, __PRETTY_FUNCTION__))
;
5821
5822 if (!Result.second.getNode()) {
5823 // As a special case, a null chain means that a tail call has been emitted
5824 // and the DAG root is already updated.
5825 HasTailCall = true;
5826
5827 // Since there's no actual continuation from this block, nothing can be
5828 // relying on us setting vregs for them.
5829 PendingExports.clear();
5830 } else {
5831 DAG.setRoot(Result.second);
5832 }
5833
5834 if (EHPadBB) {
5835 // Insert a label at the end of the invoke call to mark the try range. This
5836 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5837 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5838 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5839
5840 // Inform MachineModuleInfo of range.
5841 if (MF.hasEHFunclets()) {
5842 assert(CLI.CS)((CLI.CS) ? static_cast<void> (0) : __assert_fail ("CLI.CS"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5842, __PRETTY_FUNCTION__))
;
5843 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
5844 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
5845 BeginLabel, EndLabel);
5846 } else {
5847 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5848 }
5849 }
5850
5851 return Result;
5852}
5853
5854void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5855 bool isTailCall,
5856 const BasicBlock *EHPadBB) {
5857 auto &DL = DAG.getDataLayout();
5858 FunctionType *FTy = CS.getFunctionType();
5859 Type *RetTy = CS.getType();
5860
5861 TargetLowering::ArgListTy Args;
5862 TargetLowering::ArgListEntry Entry;
5863 Args.reserve(CS.arg_size());
5864
5865 const Value *SwiftErrorVal = nullptr;
5866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5867 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5868 i != e; ++i) {
5869 const Value *V = *i;
5870
5871 // Skip empty types
5872 if (V->getType()->isEmptyTy())
5873 continue;
5874
5875 SDValue ArgNode = getValue(V);
5876 Entry.Node = ArgNode; Entry.Ty = V->getType();
5877
5878 // Skip the first return-type Attribute to get to params.
5879 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5880
5881 // Use swifterror virtual register as input to the call.
5882 if (Entry.isSwiftError && TLI.supportSwiftError()) {
5883 SwiftErrorVal = V;
5884 // We find the virtual register for the actual swifterror argument.
5885 // Instead of using the Value, we use the virtual register instead.
5886 Entry.Node =
5887 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVReg(FuncInfo.MBB, V),
5888 EVT(TLI.getPointerTy(DL)));
5889 }
5890
5891 Args.push_back(Entry);
5892
5893 // If we have an explicit sret argument that is an Instruction, (i.e., it
5894 // might point to function-local memory), we can't meaningfully tail-call.
5895 if (Entry.isSRet && isa<Instruction>(V))
5896 isTailCall = false;
5897 }
5898
5899 // Check if target-independent constraints permit a tail call here.
5900 // Target-dependent constraints are checked within TLI->LowerCallTo.
5901 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5902 isTailCall = false;
5903
5904 // Disable tail calls if there is an swifterror argument. Targets have not
5905 // been updated to support tail calls.
5906 if (TLI.supportSwiftError() && SwiftErrorVal)
5907 isTailCall = false;
5908
5909 TargetLowering::CallLoweringInfo CLI(DAG);
5910 CLI.setDebugLoc(getCurSDLoc())
5911 .setChain(getRoot())
5912 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5913 .setTailCall(isTailCall)
5914 .setConvergent(CS.isConvergent());
5915 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5916
5917 if (Result.first.getNode()) {
5918 const Instruction *Inst = CS.getInstruction();
5919 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
5920 setValue(Inst, Result.first);
5921 }
5922
5923 // The last element of CLI.InVals has the SDValue for swifterror return.
5924 // Here we copy it to a virtual register and update SwiftErrorMap for
5925 // book-keeping.
5926 if (SwiftErrorVal && TLI.supportSwiftError()) {
5927 // Get the last element of InVals.
5928 SDValue Src = CLI.InVals.back();
5929 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
5930 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
5931 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
5932 // We update the virtual register for the actual swifterror argument.
5933 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
5934 DAG.setRoot(CopyNode);
5935 }
5936}
5937
5938/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5939/// value is equal or not-equal to zero.
5940static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5941 for (const User *U : V->users()) {
5942 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5943 if (IC->isEquality())
5944 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5945 if (C->isNullValue())
5946 continue;
5947 // Unknown instruction.
5948 return false;
5949 }
5950 return true;
5951}
5952
5953static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5954 Type *LoadTy,
5955 SelectionDAGBuilder &Builder) {
5956
5957 // Check to see if this load can be trivially constant folded, e.g. if the
5958 // input is from a string literal.
5959 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5960 // Cast pointer to the type we really want to load.
5961 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5962 PointerType::getUnqual(LoadTy));
5963
5964 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5965 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
5966 return Builder.getValue(LoadCst);
5967 }
5968
5969 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5970 // still constant memory, the input chain can be the entry node.
5971 SDValue Root;
5972 bool ConstantMemory = false;
5973
5974 // Do not serialize (non-volatile) loads of constant memory with anything.
5975 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5976 Root = Builder.DAG.getEntryNode();
5977 ConstantMemory = true;
5978 } else {
5979 // Do not serialize non-volatile loads against each other.
5980 Root = Builder.DAG.getRoot();
5981 }
5982
5983 SDValue Ptr = Builder.getValue(PtrVal);
5984 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5985 Ptr, MachinePointerInfo(PtrVal),
5986 /* Alignment = */ 1);
5987
5988 if (!ConstantMemory)
5989 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5990 return LoadVal;
5991}
5992
5993/// processIntegerCallValue - Record the value for an instruction that
5994/// produces an integer result, converting the type where necessary.
5995void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5996 SDValue Value,
5997 bool IsSigned) {
5998 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5999 I.getType(), true);
6000 if (IsSigned)
6001 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6002 else
6003 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6004 setValue(&I, Value);
6005}
6006
6007/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
6008/// If so, return true and lower it, otherwise return false and it will be
6009/// lowered like a normal call.
6010bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6011 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
6012 if (I.getNumArgOperands() != 3)
6013 return false;
6014
6015 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6016 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
6017 !I.getArgOperand(2)->getType()->isIntegerTy() ||
6018 !I.getType()->isIntegerTy())
6019 return false;
6020
6021 const Value *Size = I.getArgOperand(2);
6022 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6023 if (CSize && CSize->getZExtValue() == 0) {
6024 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6025 I.getType(), true);
6026 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6027 return true;
6028 }
6029
6030 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6031 std::pair<SDValue, SDValue> Res =
6032 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6033 getValue(LHS), getValue(RHS), getValue(Size),
6034 MachinePointerInfo(LHS),
6035 MachinePointerInfo(RHS));
6036 if (Res.first.getNode()) {
6037 processIntegerCallValue(I, Res.first, true);
6038 PendingLoads.push_back(Res.second);
6039 return true;
6040 }
6041
6042 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
6043 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
6044 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
6045 bool ActuallyDoIt = true;
6046 MVT LoadVT;
6047 Type *LoadTy;
6048 switch (CSize->getZExtValue()) {
6049 default:
6050 LoadVT = MVT::Other;
6051 LoadTy = nullptr;
6052 ActuallyDoIt = false;
6053 break;
6054 case 2:
6055 LoadVT = MVT::i16;
6056 LoadTy = Type::getInt16Ty(CSize->getContext());
6057 break;
6058 case 4:
6059 LoadVT = MVT::i32;
6060 LoadTy = Type::getInt32Ty(CSize->getContext());
6061 break;
6062 case 8:
6063 LoadVT = MVT::i64;
6064 LoadTy = Type::getInt64Ty(CSize->getContext());
6065 break;
6066 /*
6067 case 16:
6068 LoadVT = MVT::v4i32;
6069 LoadTy = Type::getInt32Ty(CSize->getContext());
6070 LoadTy = VectorType::get(LoadTy, 4);
6071 break;
6072 */
6073 }
6074
6075 // This turns into unaligned loads. We only do this if the target natively
6076 // supports the MVT we'll be loading or if it is small enough (<= 4) that
6077 // we'll only produce a small number of byte loads.
6078
6079 // Require that we can find a legal MVT, and only do this if the target
6080 // supports unaligned loads of that type. Expanding into byte loads would
6081 // bloat the code.
6082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6083 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
6084 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6085 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6086 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6087 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6088 // TODO: Check alignment of src and dest ptrs.
6089 if (!TLI.isTypeLegal(LoadVT) ||
6090 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
6091 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
6092 ActuallyDoIt = false;
6093 }
6094
6095 if (ActuallyDoIt) {
6096 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
6097 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
6098
6099 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
6100 ISD::SETNE);
6101 processIntegerCallValue(I, Res, false);
6102 return true;
6103 }
6104 }
6105
6106
6107 return false;
6108}
6109
6110/// visitMemChrCall -- See if we can lower a memchr call into an optimized
6111/// form. If so, return true and lower it, otherwise return false and it
6112/// will be lowered like a normal call.
6113bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6114 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
6115 if (I.getNumArgOperands() != 3)
6116 return false;
6117
6118 const Value *Src = I.getArgOperand(0);
6119 const Value *Char = I.getArgOperand(1);
6120 const Value *Length = I.getArgOperand(2);
6121 if (!Src->getType()->isPointerTy() ||
6122 !Char->getType()->isIntegerTy() ||
6123 !Length->getType()->isIntegerTy() ||
6124 !I.getType()->isPointerTy())
6125 return false;
6126
6127 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6128 std::pair<SDValue, SDValue> Res =
6129 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6130 getValue(Src), getValue(Char), getValue(Length),
6131 MachinePointerInfo(Src));
6132 if (Res.first.getNode()) {
6133 setValue(&I, Res.first);
6134 PendingLoads.push_back(Res.second);
6135 return true;
6136 }
6137
6138 return false;
6139}
6140
6141///
6142/// visitMemPCpyCall -- lower a mempcpy call as a memcpy followed by code to
6143/// to adjust the dst pointer by the size of the copied memory.
6144bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6145
6146 // Verify argument count: void *mempcpy(void *, const void *, size_t)
6147 if (I.getNumArgOperands() != 3)
6148 return false;
6149
6150 SDValue Dst = getValue(I.getArgOperand(0));
6151 SDValue Src = getValue(I.getArgOperand(1));
6152 SDValue Size = getValue(I.getArgOperand(2));
6153
6154 unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6155 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6156 unsigned Align = std::min(DstAlign, SrcAlign);
6157 if (Align == 0) // Alignment of one or both could not be inferred.
6158 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6159
6160 bool isVol = false;
6161 SDLoc sdl = getCurSDLoc();
6162
6163 // In the mempcpy context we need to pass in a false value for isTailCall
6164 // because the return pointer needs to be adjusted by the size of
6165 // the copied memory.
6166 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6167 false, /*isTailCall=*/false,
6168 MachinePointerInfo(I.getArgOperand(0)),
6169 MachinePointerInfo(I.getArgOperand(1)));
6170 assert(MC.getNode() != nullptr &&((MC.getNode() != nullptr && "** memcpy should not be lowered as TailCall in mempcpy context **"
) ? static_cast<void> (0) : __assert_fail ("MC.getNode() != nullptr && \"** memcpy should not be lowered as TailCall in mempcpy context **\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6171, __PRETTY_FUNCTION__))
6171 "** memcpy should not be lowered as TailCall in mempcpy context **")((MC.getNode() != nullptr && "** memcpy should not be lowered as TailCall in mempcpy context **"
) ? static_cast<void> (0) : __assert_fail ("MC.getNode() != nullptr && \"** memcpy should not be lowered as TailCall in mempcpy context **\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6171, __PRETTY_FUNCTION__))
;
6172 DAG.setRoot(MC);
6173
6174 // Check if Size needs to be truncated or extended.
6175 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6176
6177 // Adjust return pointer to point just past the last dst byte.
6178 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6179 Dst, Size);
6180 setValue(&I, DstPlusSize);
6181 return true;
6182}
6183
6184/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
6185/// optimized form. If so, return true and lower it, otherwise return false
6186/// and it will be lowered like a normal call.
6187bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6188 // Verify that the prototype makes sense. char *strcpy(char *, char *)
6189 if (I.getNumArgOperands() != 2)
6190 return false;
6191
6192 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6193 if (!Arg0->getType()->isPointerTy() ||
6194 !Arg1->getType()->isPointerTy() ||
6195 !I.getType()->isPointerTy())
6196 return false;
6197
6198 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6199 std::pair<SDValue, SDValue> Res =
6200 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6201 getValue(Arg0), getValue(Arg1),
6202 MachinePointerInfo(Arg0),
6203 MachinePointerInfo(Arg1), isStpcpy);
6204 if (Res.first.getNode()) {
6205 setValue(&I, Res.first);
6206 DAG.setRoot(Res.second);
6207 return true;
6208 }
6209
6210 return false;
6211}
6212
6213/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
6214/// If so, return true and lower it, otherwise return false and it will be
6215/// lowered like a normal call.
6216bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6217 // Verify that the prototype makes sense. int strcmp(void*,void*)
6218 if (I.getNumArgOperands() != 2)
6219 return false;
6220
6221 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6222 if (!Arg0->getType()->isPointerTy() ||
6223 !Arg1->getType()->isPointerTy() ||
6224 !I.getType()->isIntegerTy())
6225 return false;
6226
6227 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6228 std::pair<SDValue, SDValue> Res =
6229 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6230 getValue(Arg0), getValue(Arg1),
6231 MachinePointerInfo(Arg0),
6232 MachinePointerInfo(Arg1));
6233 if (Res.first.getNode()) {
6234 processIntegerCallValue(I, Res.first, true);
6235 PendingLoads.push_back(Res.second);
6236 return true;
6237 }
6238
6239 return false;
6240}
6241
6242/// visitStrLenCall -- See if we can lower a strlen call into an optimized
6243/// form. If so, return true and lower it, otherwise return false and it
6244/// will be lowered like a normal call.
6245bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6246 // Verify that the prototype makes sense. size_t strlen(char *)
6247 if (I.getNumArgOperands() != 1)
6248 return false;
6249
6250 const Value *Arg0 = I.getArgOperand(0);
6251 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
6252 return false;
6253
6254 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6255 std::pair<SDValue, SDValue> Res =
6256 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6257 getValue(Arg0), MachinePointerInfo(Arg0));
6258 if (Res.first.getNode()) {
6259 processIntegerCallValue(I, Res.first, false);
6260 PendingLoads.push_back(Res.second);
6261 return true;
6262 }
6263
6264 return false;
6265}
6266
6267/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
6268/// form. If so, return true and lower it, otherwise return false and it
6269/// will be lowered like a normal call.
6270bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6271 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
6272 if (I.getNumArgOperands() != 2)
6273 return false;
6274
6275 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6276 if (!Arg0->getType()->isPointerTy() ||
6277 !Arg1->getType()->isIntegerTy() ||
6278 !I.getType()->isIntegerTy())
6279 return false;
6280
6281 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6282 std::pair<SDValue, SDValue> Res =
6283 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6284 getValue(Arg0), getValue(Arg1),
6285 MachinePointerInfo(Arg0));
6286 if (Res.first.getNode()) {
6287 processIntegerCallValue(I, Res.first, false);
6288 PendingLoads.push_back(Res.second);
6289 return true;
6290 }
6291
6292 return false;
6293}
6294
6295/// visitUnaryFloatCall - If a call instruction is a unary floating-point
6296/// operation (as expected), translate it to an SDNode with the specified opcode
6297/// and return true.
6298bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6299 unsigned Opcode) {
6300 // Sanity check that it really is a unary floating-point call.
6301 if (I.getNumArgOperands() != 1 ||
6302 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6303 I.getType() != I.getArgOperand(0)->getType() ||
6304 !I.onlyReadsMemory())
6305 return false;
6306
6307 SDValue Tmp = getValue(I.getArgOperand(0));
6308 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6309 return true;
6310}
6311
6312/// visitBinaryFloatCall - If a call instruction is a binary floating-point
6313/// operation (as expected), translate it to an SDNode with the specified opcode
6314/// and return true.
6315bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6316 unsigned Opcode) {
6317 // Sanity check that it really is a binary floating-point call.
6318 if (I.getNumArgOperands() != 2 ||
6319 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6320 I.getType() != I.getArgOperand(0)->getType() ||
6321 I.getType() != I.getArgOperand(1)->getType() ||
6322 !I.onlyReadsMemory())
6323 return false;
6324
6325 SDValue Tmp0 = getValue(I.getArgOperand(0));
6326 SDValue Tmp1 = getValue(I.getArgOperand(1));
6327 EVT VT = Tmp0.getValueType();
6328 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6329 return true;
6330}
6331
6332void SelectionDAGBuilder::visitCall(const CallInst &I) {
6333 // Handle inline assembly differently.
6334 if (isa<InlineAsm>(I.getCalledValue())) {
6335 visitInlineAsm(&I);
6336 return;
6337 }
6338
6339 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6340 computeUsesVAFloatArgument(I, MMI);
6341
6342 const char *RenameFn = nullptr;
6343 if (Function *F = I.getCalledFunction()) {
6344 if (F->isDeclaration()) {
6345 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6346 if (unsigned IID = II->getIntrinsicID(F)) {
6347 RenameFn = visitIntrinsicCall(I, IID);
6348 if (!RenameFn)
6349 return;
6350 }
6351 }
6352 if (Intrinsic::ID IID = F->getIntrinsicID()) {
6353 RenameFn = visitIntrinsicCall(I, IID);
6354 if (!RenameFn)
6355 return;
6356 }
6357 }
6358
6359 // Check for well-known libc/libm calls. If the function is internal, it
6360 // can't be a library call. Don't do the check if marked as nobuiltin for
6361 // some reason.
6362 LibFunc::Func Func;
6363 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
6364 LibInfo->getLibFunc(F->getName(), Func) &&
6365 LibInfo->hasOptimizedCodeGen(Func)) {
6366 switch (Func) {
6367 default: break;
6368 case LibFunc::copysign:
6369 case LibFunc::copysignf:
6370 case LibFunc::copysignl:
6371 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
6372 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
6373 I.getType() == I.getArgOperand(0)->getType() &&
6374 I.getType() == I.getArgOperand(1)->getType() &&
6375 I.onlyReadsMemory()) {
6376 SDValue LHS = getValue(I.getArgOperand(0));
6377 SDValue RHS = getValue(I.getArgOperand(1));
6378 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6379 LHS.getValueType(), LHS, RHS));
6380 return;
6381 }
6382 break;
6383 case LibFunc::fabs:
6384 case LibFunc::fabsf:
6385 case LibFunc::fabsl:
6386 if (visitUnaryFloatCall(I, ISD::FABS))
6387 return;
6388 break;
6389 case LibFunc::fmin:
6390 case LibFunc::fminf:
6391 case LibFunc::fminl:
6392 if (visitBinaryFloatCall(I, ISD::FMINNUM))
6393 return;
6394 break;
6395 case LibFunc::fmax:
6396 case LibFunc::fmaxf:
6397 case LibFunc::fmaxl:
6398 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6399 return;
6400 break;
6401 case LibFunc::sin:
6402 case LibFunc::sinf:
6403 case LibFunc::sinl:
6404 if (visitUnaryFloatCall(I, ISD::FSIN))
6405 return;
6406 break;
6407 case LibFunc::cos:
6408 case LibFunc::cosf:
6409 case LibFunc::cosl:
6410 if (visitUnaryFloatCall(I, ISD::FCOS))
6411 return;
6412 break;
6413 case LibFunc::sqrt:
6414 case LibFunc::sqrtf:
6415 case LibFunc::sqrtl:
6416 case LibFunc::sqrt_finite:
6417 case LibFunc::sqrtf_finite:
6418 case LibFunc::sqrtl_finite:
6419 if (visitUnaryFloatCall(I, ISD::FSQRT))
6420 return;
6421 break;
6422 case LibFunc::floor:
6423 case LibFunc::floorf:
6424 case LibFunc::floorl:
6425 if (visitUnaryFloatCall(I, ISD::FFLOOR))
6426 return;
6427 break;
6428 case LibFunc::nearbyint:
6429 case LibFunc::nearbyintf:
6430 case LibFunc::nearbyintl:
6431 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6432 return;
6433 break;
6434 case LibFunc::ceil:
6435 case LibFunc::ceilf:
6436 case LibFunc::ceill:
6437 if (visitUnaryFloatCall(I, ISD::FCEIL))
6438 return;
6439 break;
6440 case LibFunc::rint:
6441 case LibFunc::rintf:
6442 case LibFunc::rintl:
6443 if (visitUnaryFloatCall(I, ISD::FRINT))
6444 return;
6445 break;
6446 case LibFunc::round:
6447 case LibFunc::roundf:
6448 case LibFunc::roundl:
6449 if (visitUnaryFloatCall(I, ISD::FROUND))
6450 return;
6451 break;
6452 case LibFunc::trunc:
6453 case LibFunc::truncf:
6454 case LibFunc::truncl:
6455 if (visitUnaryFloatCall(I, ISD::FTRUNC))
6456 return;
6457 break;
6458 case LibFunc::log2:
6459 case LibFunc::log2f:
6460 case LibFunc::log2l:
6461 if (visitUnaryFloatCall(I, ISD::FLOG2))
6462 return;
6463 break;
6464 case LibFunc::exp2:
6465 case LibFunc::exp2f:
6466 case LibFunc::exp2l:
6467 if (visitUnaryFloatCall(I, ISD::FEXP2))
6468 return;
6469 break;
6470 case LibFunc::memcmp:
6471 if (visitMemCmpCall(I))
6472 return;
6473 break;
6474 case LibFunc::mempcpy:
6475 if (visitMemPCpyCall(I))
6476 return;
6477 break;
6478 case LibFunc::memchr:
6479 if (visitMemChrCall(I))
6480 return;
6481 break;
6482 case LibFunc::strcpy:
6483 if (visitStrCpyCall(I, false))
6484 return;
6485 break;
6486 case LibFunc::stpcpy:
6487 if (visitStrCpyCall(I, true))
6488 return;
6489 break;
6490 case LibFunc::strcmp:
6491 if (visitStrCmpCall(I))
6492 return;
6493 break;
6494 case LibFunc::strlen:
6495 if (visitStrLenCall(I))
6496 return;
6497 break;
6498 case LibFunc::strnlen:
6499 if (visitStrNLenCall(I))
6500 return;
6501 break;
6502 }
6503 }
6504 }
6505
6506 SDValue Callee;
6507 if (!RenameFn)
6508 Callee = getValue(I.getCalledValue());
6509 else
6510 Callee = DAG.getExternalSymbol(
6511 RenameFn,
6512 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6513
6514 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6515 // have to do anything here to lower funclet bundles.
6516 assert(!I.hasOperandBundlesOtherThan(((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower calls with arbitrary operand bundles!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower calls with arbitrary operand bundles!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6518, __PRETTY_FUNCTION__))
6517 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower calls with arbitrary operand bundles!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower calls with arbitrary operand bundles!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6518, __PRETTY_FUNCTION__))
6518 "Cannot lower calls with arbitrary operand bundles!")((!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext
::OB_funclet}) && "Cannot lower calls with arbitrary operand bundles!"
) ? static_cast<void> (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower calls with arbitrary operand bundles!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6518, __PRETTY_FUNCTION__))
;
6519
6520 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6521 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6522 else
6523 // Check if we can potentially perform a tail call. More detailed checking
6524 // is be done within LowerCallTo, after more information about the call is
6525 // known.
6526 LowerCallTo(&I, Callee, I.isTailCall());
6527}
6528
6529namespace {
6530
6531/// AsmOperandInfo - This contains information for each constraint that we are
6532/// lowering.
6533class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6534public:
6535 /// CallOperand - If this is the result output operand or a clobber
6536 /// this is null, otherwise it is the incoming operand to the CallInst.
6537 /// This gets modified as the asm is processed.
6538 SDValue CallOperand;
6539
6540 /// AssignedRegs - If this is a register or register class operand, this
6541 /// contains the set of register corresponding to the operand.
6542 RegsForValue AssignedRegs;
6543
6544 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6545 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6546 }
6547
6548 /// Whether or not this operand accesses memory
6549 bool hasMemory(const TargetLowering &TLI) const {
6550 // Indirect operand accesses access memory.
6551 if (isIndirect)
6552 return true;
6553
6554 for (const auto &Code : Codes)
6555 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6556 return true;
6557
6558 return false;
6559 }
6560
6561 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6562 /// corresponds to. If there is no Value* for this operand, it returns
6563 /// MVT::Other.
6564 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6565 const DataLayout &DL) const {
6566 if (!CallOperandVal) return MVT::Other;
6567
6568 if (isa<BasicBlock>(CallOperandVal))
6569 return TLI.getPointerTy(DL);
6570
6571 llvm::Type *OpTy = CallOperandVal->getType();
6572
6573 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6574 // If this is an indirect operand, the operand is a pointer to the
6575 // accessed type.
6576 if (isIndirect) {
6577 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6578 if (!PtrTy)
6579 report_fatal_error("Indirect operand for inline asm not a pointer!");
6580 OpTy = PtrTy->getElementType();
6581 }
6582
6583 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6584 if (StructType *STy = dyn_cast<StructType>(OpTy))
6585 if (STy->getNumElements() == 1)
6586 OpTy = STy->getElementType(0);
6587
6588 // If OpTy is not a single value, it may be a struct/union that we
6589 // can tile with integers.
6590 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6591 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6592 switch (BitSize) {
6593 default: break;
6594 case 1:
6595 case 8:
6596 case 16:
6597 case 32:
6598 case 64:
6599 case 128:
6600 OpTy = IntegerType::get(Context, BitSize);
6601 break;
6602 }
6603 }
6604
6605 return TLI.getValueType(DL, OpTy, true);
6606 }
6607};
6608
6609typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6610
6611} // end anonymous namespace
6612
6613/// Make sure that the output operand \p OpInfo and its corresponding input
6614/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
6615/// out).
6616static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
6617 SDISelAsmOperandInfo &MatchingOpInfo,
6618 SelectionDAG &DAG) {
6619 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
6620 return;
6621
6622 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6623 const auto &TLI = DAG.getTargetLoweringInfo();
6624
6625 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6626 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6627 OpInfo.ConstraintVT);
6628 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6629 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
6630 MatchingOpInfo.ConstraintVT);
6631 if ((OpInfo.ConstraintVT.isInteger() !=
6632 MatchingOpInfo.ConstraintVT.isInteger()) ||
6633 (MatchRC.second != InputRC.second)) {
6634 // FIXME: error out in a more elegant fashion
6635 report_fatal_error("Unsupported asm: input constraint"
6636 " with a matching output constraint of"
6637 " incompatible type!");
6638 }
6639 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
6640}
6641
6642/// Get a direct memory input to behave well as an indirect operand.
6643/// This may introduce stores, hence the need for a \p Chain.
6644/// \return The (possibly updated) chain.
6645static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
6646 SDISelAsmOperandInfo &OpInfo,
6647 SelectionDAG &DAG) {
6648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6649
6650 // If we don't have an indirect input, put it in the constpool if we can,
6651 // otherwise spill it to a stack slot.
6652 // TODO: This isn't quite right. We need to handle these according to
6653 // the addressing mode that the constraint wants. Also, this may take
6654 // an additional register for the computation and we don't want that
6655 // either.
6656
6657 // If the operand is a float, integer, or vector constant, spill to a
6658 // constant pool entry to get its address.
6659 const Value *OpVal = OpInfo.CallOperandVal;
6660 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6661 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6662 OpInfo.CallOperand = DAG.getConstantPool(
6663 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6664 return Chain;
6665 }
6666
6667 // Otherwise, create a stack slot and emit a store to it before the asm.
6668 Type *Ty = OpVal->getType();
6669 auto &DL = DAG.getDataLayout();
6670 uint64_t TySize = DL.getTypeAllocSize(Ty);
6671 unsigned Align = DL.getPrefTypeAlignment(Ty);
6672 MachineFunction &MF = DAG.getMachineFunction();
6673 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
6674 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy(DL));
6675 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
6676 MachinePointerInfo::getFixedStack(MF, SSFI));
6677 OpInfo.CallOperand = StackSlot;
6678
6679 return Chain;
6680}
6681
6682/// GetRegistersForValue - Assign registers (virtual or physical) for the
6683/// specified operand. We prefer to assign virtual registers, to allow the
6684/// register allocator to handle the assignment process. However, if the asm
6685/// uses features that we can't model on machineinstrs, we have SDISel do the
6686/// allocation. This produces generally horrible, but correct, code.
6687///
6688/// OpInfo describes the operand.
6689///
6690static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
6691 const SDLoc &DL,
6692 SDISelAsmOperandInfo &OpInfo) {
6693 LLVMContext &Context = *DAG.getContext();
6694
6695 MachineFunction &MF = DAG.getMachineFunction();
6696 SmallVector<unsigned, 4> Regs;
6697
6698 // If this is a constraint for a single physreg, or a constraint for a
6699 // register class, find it.
6700 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6701 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
1
Value assigned to 'PhysReg.second'
6702 OpInfo.ConstraintCode,
6703 OpInfo.ConstraintVT);
6704
6705 unsigned NumRegs = 1;
6706 if (OpInfo.ConstraintVT != MVT::Other) {
2
Taking true branch
6707 // If this is a FP input in an integer register (or visa versa) insert a bit
6708 // cast of the input value. More generally, handle any case where the input
6709 // value disagrees with the register class we plan to stick this in.
6710 if (OpInfo.Type == InlineAsm::isInput &&
3
Assuming the condition is true
4
Assuming pointer value is null
6711 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5
Assuming the condition is false
6712 // Try to convert to the first EVT that the reg class contains. If the
6713 // types are identical size, use a bitcast to convert (e.g. two differing
6714 // vector types).
6715 MVT RegVT = *PhysReg.second->vt_begin();
6716 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6717 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6718 RegVT, OpInfo.CallOperand);
6719 OpInfo.ConstraintVT = RegVT;
6720 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6721 // If the input is a FP value and we want it in FP registers, do a
6722 // bitcast to the corresponding integer type. This turns an f64 value
6723 // into i64, which can be passed with two i32 values on a 32-bit
6724 // machine.
6725 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6726 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6727 RegVT, OpInfo.CallOperand);
6728 OpInfo.ConstraintVT = RegVT;
6729 }
6730 }
6731
6732 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6733 }
6734
6735 MVT RegVT;
6736 EVT ValueVT = OpInfo.ConstraintVT;
6737
6738 // If this is a constraint for a specific physical register, like {r17},
6739 // assign it now.
6740 if (unsigned AssignedReg = PhysReg.first) {
6
Assuming 'AssignedReg' is not equal to 0
7
Taking true branch
6741 const TargetRegisterClass *RC = PhysReg.second;
8
'RC' initialized to a null pointer value
6742 if (OpInfo.ConstraintVT == MVT::Other)
9
Taking false branch
6743 ValueVT = *RC->vt_begin();
6744
6745 // Get the actual register value type. This is important, because the user
6746 // may have asked for (e.g.) the AX register in i32 type. We need to
6747 // remember that AX is actually i16 to get the right extension.
6748 RegVT = *RC->vt_begin();
10
Called C++ object pointer is null
6749
6750 // This is a explicit reference to a physical register.
6751 Regs.push_back(AssignedReg);
6752
6753 // If this is an expanded reference, add the rest of the regs to Regs.
6754 if (NumRegs != 1) {
6755 TargetRegisterClass::iterator I = RC->begin();
6756 for (; *I != AssignedReg; ++I)
6757 assert(I != RC->end() && "Didn't find reg!")((I != RC->end() && "Didn't find reg!") ? static_cast
<void> (0) : __assert_fail ("I != RC->end() && \"Didn't find reg!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6757, __PRETTY_FUNCTION__))
;
6758
6759 // Already added the first reg.
6760 --NumRegs; ++I;
6761 for (; NumRegs; --NumRegs, ++I) {
6762 assert(I != RC->end() && "Ran out of registers to allocate!")((I != RC->end() && "Ran out of registers to allocate!"
) ? static_cast<void> (0) : __assert_fail ("I != RC->end() && \"Ran out of registers to allocate!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6762, __PRETTY_FUNCTION__))
;
6763 Regs.push_back(*I);
6764 }
6765 }
6766
6767 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6768 return;
6769 }
6770
6771 // Otherwise, if this was a reference to an LLVM register class, create vregs
6772 // for this reference.
6773 if (const TargetRegisterClass *RC = PhysReg.second) {
6774 RegVT = *RC->vt_begin();
6775 if (OpInfo.ConstraintVT == MVT::Other)
6776 ValueVT = RegVT;
6777
6778 // Create the appropriate number of virtual registers.
6779 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6780 for (; NumRegs; --NumRegs)
6781 Regs.push_back(RegInfo.createVirtualRegister(RC));
6782
6783 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6784 return;
6785 }
6786
6787 // Otherwise, we couldn't allocate enough registers for this.
6788}
6789
6790static unsigned
6791findMatchingInlineAsmOperand(unsigned OperandNo,
6792 const std::vector<SDValue> &AsmNodeOperands) {
6793 // Scan until we find the definition we already emitted of this operand.
6794 unsigned CurOp = InlineAsm::Op_FirstOperand;
6795 for (; OperandNo; --OperandNo) {
6796 // Advance to the next operand.
6797 unsigned OpFlag =
6798 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6799 assert((InlineAsm::isRegDefKind(OpFlag) ||(((InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind
(OpFlag) || InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"
) ? static_cast<void> (0) : __assert_fail ("(InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind(OpFlag) || InlineAsm::isMemKind(OpFlag)) && \"Skipped past definitions?\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6802, __PRETTY_FUNCTION__))
6800 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||(((InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind
(OpFlag) || InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"
) ? static_cast<void> (0) : __assert_fail ("(InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind(OpFlag) || InlineAsm::isMemKind(OpFlag)) && \"Skipped past definitions?\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6802, __PRETTY_FUNCTION__))
6801 InlineAsm::isMemKind(OpFlag)) &&(((InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind
(OpFlag) || InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"
) ? static_cast<void> (0) : __assert_fail ("(InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind(OpFlag) || InlineAsm::isMemKind(OpFlag)) && \"Skipped past definitions?\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6802, __PRETTY_FUNCTION__))
6802 "Skipped past definitions?")(((InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind
(OpFlag) || InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"
) ? static_cast<void> (0) : __assert_fail ("(InlineAsm::isRegDefKind(OpFlag) || InlineAsm::isRegDefEarlyClobberKind(OpFlag) || InlineAsm::isMemKind(OpFlag)) && \"Skipped past definitions?\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6802, __PRETTY_FUNCTION__))
;
6803 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
6804 }
6805 return CurOp;
6806}
6807
6808/// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
6809/// \return true if it has succeeded, false otherwise
6810static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
6811 MVT RegVT, SelectionDAG &DAG) {
6812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6813 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6814 for (unsigned i = 0, e = NumRegs; i != e; ++i) {
6815 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6816 Regs.push_back(RegInfo.createVirtualRegister(RC));
6817 else
6818 return false;
6819 }
6820 return true;
6821}
6822
6823class ExtraFlags {
6824 unsigned Flags = 0;
6825
6826public:
6827 explicit ExtraFlags(ImmutableCallSite CS) {
6828 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6829 if (IA->hasSideEffects())
6830 Flags |= InlineAsm::Extra_HasSideEffects;
6831 if (IA->isAlignStack())
6832 Flags |= InlineAsm::Extra_IsAlignStack;
6833 if (CS.isConvergent())
6834 Flags |= InlineAsm::Extra_IsConvergent;
6835 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6836 }
6837
6838 void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) {
6839 // Ideally, we would only check against memory constraints. However, the
6840 // meaning of an Other constraint can be target-specific and we can't easily
6841 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6842 // for Other constraints as well.
6843 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6844 OpInfo.ConstraintType == TargetLowering::C_Other) {
6845 if (OpInfo.Type == InlineAsm::isInput)
6846 Flags |= InlineAsm::Extra_MayLoad;
6847 else if (OpInfo.Type == InlineAsm::isOutput)
6848 Flags |= InlineAsm::Extra_MayStore;
6849 else if (OpInfo.Type == InlineAsm::isClobber)
6850 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6851 }
6852 }
6853
6854 unsigned get() const { return Flags; }
6855};
6856
6857/// visitInlineAsm - Handle a call to an InlineAsm object.
6858///
6859void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6860 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6861
6862 /// ConstraintOperands - Information about all of the constraints.
6863 SDISelAsmOperandInfoVector ConstraintOperands;
6864
6865 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6866 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6867 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6868
6869 bool hasMemory = false;
6870
6871 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6872 ExtraFlags ExtraInfo(CS);
6873
6874 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6875 unsigned ResNo = 0; // ResNo - The result number of the next output.
6876 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6877 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6878 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6879
6880 MVT OpVT = MVT::Other;
6881
6882 // Compute the value type for each operand.
6883 if (OpInfo.Type == InlineAsm::isInput ||
6884 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
6885 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6886
6887 // Process the call argument. BasicBlocks are labels, currently appearing
6888 // only in asm's.
6889 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6890 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6891 } else {
6892 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6893 }
6894
6895 OpVT =
6896 OpInfo
6897 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
6898 .getSimpleVT();
6899 }
6900
6901 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
6902 // The return value of the call is this value. As such, there is no
6903 // corresponding argument.
6904 assert(!CS.getType()->isVoidTy() && "Bad inline asm!")((!CS.getType()->isVoidTy() && "Bad inline asm!") ?
static_cast<void> (0) : __assert_fail ("!CS.getType()->isVoidTy() && \"Bad inline asm!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6904, __PRETTY_FUNCTION__))
;
6905 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6906 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6907 STy->getElementType(ResNo));
6908 } else {
6909 assert(ResNo == 0 && "Asm only has one result!")((ResNo == 0 && "Asm only has one result!") ? static_cast
<void> (0) : __assert_fail ("ResNo == 0 && \"Asm only has one result!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6909, __PRETTY_FUNCTION__))
;
6910 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6911 }
6912 ++ResNo;
6913 }
6914
6915 OpInfo.ConstraintVT = OpVT;
6916
6917 if (!hasMemory)
6918 hasMemory = OpInfo.hasMemory(TLI);
6919
6920 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6921 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
6922 auto TargetConstraint = TargetConstraints[i];
6923
6924 // Compute the constraint code and ConstraintType to use.
6925 TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
6926
6927 ExtraInfo.update(TargetConstraint);
6928 }
6929
6930 SDValue Chain, Flag;
6931
6932 // We won't need to flush pending loads if this asm doesn't touch
6933 // memory and is nonvolatile.
6934 if (hasMemory || IA->hasSideEffects())
6935 Chain = getRoot();
6936 else
6937 Chain = DAG.getRoot();
6938
6939 // Second pass over the constraints: compute which constraint option to use
6940 // and assign registers to constraints that want a specific physreg.
6941 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6942 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6943
6944 // If this is an output operand with a matching input operand, look up the
6945 // matching input. If their types mismatch, e.g. one is an integer, the
6946 // other is floating point, or their sizes are different, flag it as an
6947 // error.
6948 if (OpInfo.hasMatchingInput()) {
6949 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6950 patchMatchingInput(OpInfo, Input, DAG);
6951 }
6952
6953 // Compute the constraint code and ConstraintType to use.
6954 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6955
6956 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6957 OpInfo.Type == InlineAsm::isClobber)
6958 continue;
6959
6960 // If this is a memory input, and if the operand is not indirect, do what we
6961 // need to to provide an address for the memory input.
6962 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6963 !OpInfo.isIndirect) {
6964 assert((OpInfo.isMultipleAlternative ||(((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::
isInput)) && "Can only indirectify direct input operands!"
) ? static_cast<void> (0) : __assert_fail ("(OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) && \"Can only indirectify direct input operands!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6966, __PRETTY_FUNCTION__))
6965 (OpInfo.Type == InlineAsm::isInput)) &&(((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::
isInput)) && "Can only indirectify direct input operands!"
) ? static_cast<void> (0) : __assert_fail ("(OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) && \"Can only indirectify direct input operands!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6966, __PRETTY_FUNCTION__))
6966 "Can only indirectify direct input operands!")(((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::
isInput)) && "Can only indirectify direct input operands!"
) ? static_cast<void> (0) : __assert_fail ("(OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) && \"Can only indirectify direct input operands!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 6966, __PRETTY_FUNCTION__))
;
6967
6968 // Memory operands really want the address of the value.
6969 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
6970
6971 // There is no longer a Value* corresponding to this operand.
6972 OpInfo.CallOperandVal = nullptr;
6973
6974 // It is now an indirect operand.
6975 OpInfo.isIndirect = true;
6976 }
6977
6978 // If this constraint is for a specific register, allocate it before
6979 // anything else.
6980 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6981 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6982 }
6983
6984 // Third pass - Loop over all of the operands, assigning virtual or physregs
6985 // to register class operands.
6986 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6987 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6988
6989 // C_Register operands have already been allocated, Other/Memory don't need
6990 // to be.
6991 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6992 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6993 }
6994
6995 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6996 std::vector<SDValue> AsmNodeOperands;
6997 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6998 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6999 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7000
7001 // If we have a !srcloc metadata node associated with it, we want to attach
7002 // this to the ultimately generated inline asm machineinstr. To do this, we
7003 // pass in the third operand as this (potentially null) inline asm MDNode.
7004 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7005 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7006
7007 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7008 // bits as operand 3.
7009 AsmNodeOperands.push_back(DAG.getTargetConstant(
7010 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7011
7012 // Loop over all of the inputs, copying the operand values into the
7013 // appropriate registers and processing the output regs.
7014 RegsForValue RetValRegs;
7015
7016 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7017 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
7018
7019 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7020 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7021
7022 switch (OpInfo.Type) {
7023 case InlineAsm::isOutput: {
7024 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7025 OpInfo.ConstraintType != TargetLowering::C_Register) {
7026 // Memory output, or 'other' output (e.g. 'X' constraint).
7027 assert(OpInfo.isIndirect && "Memory output must be indirect operand")((OpInfo.isIndirect && "Memory output must be indirect operand"
) ? static_cast<void> (0) : __assert_fail ("OpInfo.isIndirect && \"Memory output must be indirect operand\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7027, __PRETTY_FUNCTION__))
;
7028
7029 unsigned ConstraintID =
7030 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7031 assert(ConstraintID != InlineAsm::Constraint_Unknown &&((ConstraintID != InlineAsm::Constraint_Unknown && "Failed to convert memory constraint code to constraint id."
) ? static_cast<void> (0) : __assert_fail ("ConstraintID != InlineAsm::Constraint_Unknown && \"Failed to convert memory constraint code to constraint id.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7032, __PRETTY_FUNCTION__))
7032 "Failed to convert memory constraint code to constraint id.")((ConstraintID != InlineAsm::Constraint_Unknown && "Failed to convert memory constraint code to constraint id."
) ? static_cast<void> (0) : __assert_fail ("ConstraintID != InlineAsm::Constraint_Unknown && \"Failed to convert memory constraint code to constraint id.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7032, __PRETTY_FUNCTION__))
;
7033
7034 // Add information to the INLINEASM node to know about this output.
7035 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7036 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7037 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7038 MVT::i32));
7039 AsmNodeOperands.push_back(OpInfo.CallOperand);
7040 break;
7041 }
7042
7043 // Otherwise, this is a register or register class output.
7044
7045 // Copy the output from the appropriate register. Find a register that
7046 // we can use.
7047 if (OpInfo.AssignedRegs.Regs.empty()) {
7048 emitInlineAsmError(
7049 CS, "couldn't allocate output register for constraint '" +
7050 Twine(OpInfo.ConstraintCode) + "'");
7051 return;
7052 }
7053
7054 // If this is an indirect operand, store through the pointer after the
7055 // asm.
7056 if (OpInfo.isIndirect) {
7057 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7058 OpInfo.CallOperandVal));
7059 } else {
7060 // This is the result value of the call.
7061 assert(!CS.getType()->isVoidTy() && "Bad inline asm!")((!CS.getType()->isVoidTy() && "Bad inline asm!") ?
static_cast<void> (0) : __assert_fail ("!CS.getType()->isVoidTy() && \"Bad inline asm!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7061, __PRETTY_FUNCTION__))
;
7062 // Concatenate this output onto the outputs list.
7063 RetValRegs.append(OpInfo.AssignedRegs);
7064 }
7065
7066 // Add information to the INLINEASM node to know that this register is
7067 // set.
7068 OpInfo.AssignedRegs
7069 .AddInlineAsmOperands(OpInfo.isEarlyClobber
7070 ? InlineAsm::Kind_RegDefEarlyClobber
7071 : InlineAsm::Kind_RegDef,
7072 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7073 break;
7074 }
7075 case InlineAsm::isInput: {
7076 SDValue InOperandVal = OpInfo.CallOperand;
7077
7078 if (OpInfo.isMatchingInputConstraint()) {
7079 // If this is required to match an output register we have already set,
7080 // just use its register.
7081 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7082 AsmNodeOperands);
7083 unsigned OpFlag =
7084 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7085 if (InlineAsm::isRegDefKind(OpFlag) ||
7086 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7087 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7088 if (OpInfo.isIndirect) {
7089 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7090 emitInlineAsmError(CS, "inline asm not supported yet:"
7091 " don't know how to handle tied "
7092 "indirect register inputs");
7093 return;
7094 }
7095
7096 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7097 SmallVector<unsigned, 4> Regs;
7098
7099 if (!createVirtualRegs(Regs,
7100 InlineAsm::getNumOperandRegisters(OpFlag),
7101 RegVT, DAG)) {
7102 emitInlineAsmError(CS, "inline asm error: This value type register "
7103 "class is not natively supported!");
7104 return;
7105 }
7106
7107 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7108
7109 SDLoc dl = getCurSDLoc();
7110 // Use the produced MatchedRegs object to
7111 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7112 Chain, &Flag, CS.getInstruction());
7113 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7114 true, OpInfo.getMatchedOperand(), dl,
7115 DAG, AsmNodeOperands);
7116 break;
7117 }
7118
7119 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!")((InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"
) ? static_cast<void> (0) : __assert_fail ("InlineAsm::isMemKind(OpFlag) && \"Unknown matching constraint!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7119, __PRETTY_FUNCTION__))
;
7120 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&((InlineAsm::getNumOperandRegisters(OpFlag) == 1 && "Unexpected number of operands"
) ? static_cast<void> (0) : __assert_fail ("InlineAsm::getNumOperandRegisters(OpFlag) == 1 && \"Unexpected number of operands\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7121, __PRETTY_FUNCTION__))
7121 "Unexpected number of operands")((InlineAsm::getNumOperandRegisters(OpFlag) == 1 && "Unexpected number of operands"
) ? static_cast<void> (0) : __assert_fail ("InlineAsm::getNumOperandRegisters(OpFlag) == 1 && \"Unexpected number of operands\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7121, __PRETTY_FUNCTION__))
;
7122 // Add information to the INLINEASM node to know about this input.
7123 // See InlineAsm.h isUseOperandTiedToDef.
7124 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7125 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7126 OpInfo.getMatchedOperand());
7127 AsmNodeOperands.push_back(DAG.getTargetConstant(
7128 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7129 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7130 break;
7131 }
7132
7133 // Treat indirect 'X' constraint as memory.
7134 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7135 OpInfo.isIndirect)
7136 OpInfo.ConstraintType = TargetLowering::C_Memory;
7137
7138 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7139 std::vector<SDValue> Ops;
7140 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7141 Ops, DAG);
7142 if (Ops.empty()) {
7143 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7144 Twine(OpInfo.ConstraintCode) + "'");
7145 return;
7146 }
7147
7148 // Add information to the INLINEASM node to know about this input.
7149 unsigned ResOpType =
7150 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7151 AsmNodeOperands.push_back(DAG.getTargetConstant(
7152 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7153 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7154 break;
7155 }
7156
7157 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7158 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!")((OpInfo.isIndirect && "Operand must be indirect to be a mem!"
) ? static_cast<void> (0) : __assert_fail ("OpInfo.isIndirect && \"Operand must be indirect to be a mem!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7158, __PRETTY_FUNCTION__))
;
7159 assert(InOperandVal.getValueType() ==((InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout
()) && "Memory operands expect pointer values") ? static_cast
<void> (0) : __assert_fail ("InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout()) && \"Memory operands expect pointer values\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7161, __PRETTY_FUNCTION__))
7160 TLI.getPointerTy(DAG.getDataLayout()) &&((InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout
()) && "Memory operands expect pointer values") ? static_cast
<void> (0) : __assert_fail ("InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout()) && \"Memory operands expect pointer values\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7161, __PRETTY_FUNCTION__))
7161 "Memory operands expect pointer values")((InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout
()) && "Memory operands expect pointer values") ? static_cast
<void> (0) : __assert_fail ("InOperandVal.getValueType() == TLI.getPointerTy(DAG.getDataLayout()) && \"Memory operands expect pointer values\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7161, __PRETTY_FUNCTION__))
;
7162
7163 unsigned ConstraintID =
7164 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7165 assert(ConstraintID != InlineAsm::Constraint_Unknown &&((ConstraintID != InlineAsm::Constraint_Unknown && "Failed to convert memory constraint code to constraint id."
) ? static_cast<void> (0) : __assert_fail ("ConstraintID != InlineAsm::Constraint_Unknown && \"Failed to convert memory constraint code to constraint id.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7166, __PRETTY_FUNCTION__))
7166 "Failed to convert memory constraint code to constraint id.")((ConstraintID != InlineAsm::Constraint_Unknown && "Failed to convert memory constraint code to constraint id."
) ? static_cast<void> (0) : __assert_fail ("ConstraintID != InlineAsm::Constraint_Unknown && \"Failed to convert memory constraint code to constraint id.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7166, __PRETTY_FUNCTION__))
;
7167
7168 // Add information to the INLINEASM node to know about this input.
7169 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7170 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7171 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7172 getCurSDLoc(),
7173 MVT::i32));
7174 AsmNodeOperands.push_back(InOperandVal);
7175 break;
7176 }
7177
7178 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||(((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
OpInfo.ConstraintType == TargetLowering::C_Register) &&
"Unknown constraint type!") ? static_cast<void> (0) : __assert_fail
("(OpInfo.ConstraintType == TargetLowering::C_RegisterClass || OpInfo.ConstraintType == TargetLowering::C_Register) && \"Unknown constraint type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7180, __PRETTY_FUNCTION__))
7179 OpInfo.ConstraintType == TargetLowering::C_Register) &&(((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
OpInfo.ConstraintType == TargetLowering::C_Register) &&
"Unknown constraint type!") ? static_cast<void> (0) : __assert_fail
("(OpInfo.ConstraintType == TargetLowering::C_RegisterClass || OpInfo.ConstraintType == TargetLowering::C_Register) && \"Unknown constraint type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7180, __PRETTY_FUNCTION__))
7180 "Unknown constraint type!")(((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
OpInfo.ConstraintType == TargetLowering::C_Register) &&
"Unknown constraint type!") ? static_cast<void> (0) : __assert_fail
("(OpInfo.ConstraintType == TargetLowering::C_RegisterClass || OpInfo.ConstraintType == TargetLowering::C_Register) && \"Unknown constraint type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7180, __PRETTY_FUNCTION__))
;
7181
7182 // TODO: Support this.
7183 if (OpInfo.isIndirect) {
7184 emitInlineAsmError(
7185 CS, "Don't know how to handle indirect register inputs yet "
7186 "for constraint '" +
7187 Twine(OpInfo.ConstraintCode) + "'");
7188 return;
7189 }
7190
7191 // Copy the input into the appropriate registers.
7192 if (OpInfo.AssignedRegs.Regs.empty()) {
7193 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7194 Twine(OpInfo.ConstraintCode) + "'");
7195 return;
7196 }
7197
7198 SDLoc dl = getCurSDLoc();
7199
7200 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7201 Chain, &Flag, CS.getInstruction());
7202
7203 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7204 dl, DAG, AsmNodeOperands);
7205 break;
7206 }
7207 case InlineAsm::isClobber: {
7208 // Add the clobbered value to the operand list, so that the register
7209 // allocator is aware that the physreg got clobbered.
7210 if (!OpInfo.AssignedRegs.Regs.empty())
7211 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7212 false, 0, getCurSDLoc(), DAG,
7213 AsmNodeOperands);
7214 break;
7215 }
7216 }
7217 }
7218
7219 // Finish up input operands. Set the input chain and add the flag last.
7220 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7221 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7222
7223 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7224 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7225 Flag = Chain.getValue(1);
7226
7227 // If this asm returns a register value, copy the result from that register
7228 // and set it as the value of the call.
7229 if (!RetValRegs.Regs.empty()) {
7230 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7231 Chain, &Flag, CS.getInstruction());
7232
7233 // FIXME: Why don't we do this for inline asms with MRVs?
7234 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7235 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7236
7237 // If any of the results of the inline asm is a vector, it may have the
7238 // wrong width/num elts. This can happen for register classes that can
7239 // contain multiple different value types. The preg or vreg allocated may
7240 // not have the same VT as was expected. Convert it to the right type
7241 // with bit_convert.
7242 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7243 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7244 ResultType, Val);
7245
7246 } else if (ResultType != Val.getValueType() &&
7247 ResultType.isInteger() && Val.getValueType().isInteger()) {
7248 // If a result value was tied to an input value, the computed result may
7249 // have a wider width than the expected result. Extract the relevant
7250 // portion.
7251 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7252 }
7253
7254 assert(ResultType == Val.getValueType() && "Asm result value mismatch!")((ResultType == Val.getValueType() && "Asm result value mismatch!"
) ? static_cast<void> (0) : __assert_fail ("ResultType == Val.getValueType() && \"Asm result value mismatch!\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7254, __PRETTY_FUNCTION__))
;
7255 }
7256
7257 setValue(CS.getInstruction(), Val);
7258 // Don't need to use this as a chain in this case.
7259 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7260 return;
7261 }
7262
7263 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
7264
7265 // Process indirect outputs, first output all of the flagged copies out of
7266 // physregs.
7267 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7268 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7269 const Value *Ptr = IndirectStoresToEmit[i].second;
7270 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7271 Chain, &Flag, IA);
7272 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7273 }
7274
7275 // Emit the non-flagged stores from the physregs.
7276 SmallVector<SDValue, 8> OutChains;
7277 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7278 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7279 getValue(StoresToEmit[i].second),
7280 MachinePointerInfo(StoresToEmit[i].second));
7281 OutChains.push_back(Val);
7282 }
7283
7284 if (!OutChains.empty())
7285 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7286
7287 DAG.setRoot(Chain);
7288}
7289
7290void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7291 const Twine &Message) {
7292 LLVMContext &Ctx = *DAG.getContext();
7293 Ctx.emitError(CS.getInstruction(), Message);
7294
7295 // Make sure we leave the DAG in a valid state
7296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7297 auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7298 setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7299}
7300
7301void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7302 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7303 MVT::Other, getRoot(),
7304 getValue(I.getArgOperand(0)),
7305 DAG.getSrcValue(I.getArgOperand(0))));
7306}
7307
7308void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7309 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7310 const DataLayout &DL = DAG.getDataLayout();
7311 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7312 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7313 DAG.getSrcValue(I.getOperand(0)),
7314 DL.getABITypeAlignment(I.getType()));
7315 setValue(&I, V);
7316 DAG.setRoot(V.getValue(1));
7317}
7318
7319void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7320 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7321 MVT::Other, getRoot(),
7322 getValue(I.getArgOperand(0)),
7323 DAG.getSrcValue(I.getArgOperand(0))));
7324}
7325
7326void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7327 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7328 MVT::Other, getRoot(),
7329 getValue(I.getArgOperand(0)),
7330 getValue(I.getArgOperand(1)),
7331 DAG.getSrcValue(I.getArgOperand(0)),
7332 DAG.getSrcValue(I.getArgOperand(1))));
7333}
7334
7335SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7336 const Instruction &I,
7337 SDValue Op) {
7338 const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7339 if (!Range)
7340 return Op;
7341
7342 Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
7343 if (!Lo->isNullValue())
7344 return Op;
7345
7346 Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
7347 unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
7348
7349 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7350
7351 SDLoc SL = getCurSDLoc();
7352
7353 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
7354 Op, DAG.getValueType(SmallVT));
7355 unsigned NumVals = Op.getNode()->getNumValues();
7356 if (NumVals == 1)
7357 return ZExt;
7358
7359 SmallVector<SDValue, 4> Ops;
7360
7361 Ops.push_back(ZExt);
7362 for (unsigned I = 1; I != NumVals; ++I)
7363 Ops.push_back(Op.getValue(I));
7364
7365 return DAG.getMergeValues(Ops, SL);
7366}
7367
7368/// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
7369/// the call being lowered.
7370///
7371/// This is a helper for lowering intrinsics that follow a target calling
7372/// convention or require stack pointer adjustment. Only a subset of the
7373/// intrinsic's operands need to participate in the calling convention.
7374void SelectionDAGBuilder::populateCallLoweringInfo(
7375 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7376 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7377 bool IsPatchPoint) {
7378 TargetLowering::ArgListTy Args;
7379 Args.reserve(NumArgs);
7380
7381 // Populate the argument list.
7382 // Attributes for args start at offset 1, after the return attribute.
7383 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
7384 ArgI != ArgE; ++ArgI) {
7385 const Value *V = CS->getOperand(ArgI);
7386
7387 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.")((!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isEmptyTy() && \"Empty type passed to intrinsic.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7387, __PRETTY_FUNCTION__))
;
7388
7389 TargetLowering::ArgListEntry Entry;
7390 Entry.Node = getValue(V);
7391 Entry.Ty = V->getType();
7392 Entry.setAttributes(&CS, AttrI);
7393 Args.push_back(Entry);
7394 }
7395
7396 CLI.setDebugLoc(getCurSDLoc())
7397 .setChain(getRoot())
7398 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7399 .setDiscardResult(CS->use_empty())
7400 .setIsPatchPoint(IsPatchPoint);
7401}
7402
7403/// \brief Add a stack map intrinsic call's live variable operands to a stackmap
7404/// or patchpoint target node's operand list.
7405///
7406/// Constants are converted to TargetConstants purely as an optimization to
7407/// avoid constant materialization and register allocation.
7408///
7409/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7410/// generate addess computation nodes, and so ExpandISelPseudo can convert the
7411/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7412/// address materialization and register allocation, but may also be required
7413/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7414/// alloca in the entry block, then the runtime may assume that the alloca's
7415/// StackMap location can be read immediately after compilation and that the
7416/// location is valid at any point during execution (this is similar to the
7417/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7418/// only available in a register, then the runtime would need to trap when
7419/// execution reaches the StackMap in order to read the alloca's location.
7420static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7421 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7422 SelectionDAGBuilder &Builder) {
7423 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7424 SDValue OpVal = Builder.getValue(CS.getArgument(i));
7425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7426 Ops.push_back(
7427 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7428 Ops.push_back(
7429 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7430 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7431 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7432 Ops.push_back(Builder.DAG.getTargetFrameIndex(
7433 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
7434 } else
7435 Ops.push_back(OpVal);
7436 }
7437}
7438
7439/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7440void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7441 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7442 // [live variables...])
7443
7444 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.")((CI.getType()->isVoidTy() && "Stackmap cannot return a value."
) ? static_cast<void> (0) : __assert_fail ("CI.getType()->isVoidTy() && \"Stackmap cannot return a value.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7444, __PRETTY_FUNCTION__))
;
7445
7446 SDValue Chain, InFlag, Callee, NullPtr;
7447 SmallVector<SDValue, 32> Ops;
7448
7449 SDLoc DL = getCurSDLoc();
7450 Callee = getValue(CI.getCalledValue());
7451 NullPtr = DAG.getIntPtrConstant(0, DL, true);
7452
7453 // The stackmap intrinsic only records the live variables (the arguemnts
7454 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7455 // intrinsic, this won't be lowered to a function call. This means we don't
7456 // have to worry about calling conventions and target specific lowering code.
7457 // Instead we perform the call lowering right here.
7458 //
7459 // chain, flag = CALLSEQ_START(chain, 0)
7460 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7461 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7462 //
7463 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7464 InFlag = Chain.getValue(1);
7465
7466 // Add the <id> and <numBytes> constants.
7467 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7468 Ops.push_back(DAG.getTargetConstant(
7469 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7470 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7471 Ops.push_back(DAG.getTargetConstant(
7472 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7473 MVT::i32));
7474
7475 // Push live variables for the stack map.
7476 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7477
7478 // We are not pushing any register mask info here on the operands list,
7479 // because the stackmap doesn't clobber anything.
7480
7481 // Push the chain and the glue flag.
7482 Ops.push_back(Chain);
7483 Ops.push_back(InFlag);
7484
7485 // Create the STACKMAP node.
7486 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7487 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7488 Chain = SDValue(SM, 0);
7489 InFlag = Chain.getValue(1);
7490
7491 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7492
7493 // Stackmaps don't generate values, so nothing goes into the NodeMap.
7494
7495 // Set the root to the target-lowered call chain.
7496 DAG.setRoot(Chain);
7497
7498 // Inform the Frame Information that we have a stackmap in this function.
7499 FuncInfo.MF->getFrameInfo().setHasStackMap();
7500}
7501
7502/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7503void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7504 const BasicBlock *EHPadBB) {
7505 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7506 // i32 <numBytes>,
7507 // i8* <target>,
7508 // i32 <numArgs>,
7509 // [Args...],
7510 // [live variables...])
7511
7512 CallingConv::ID CC = CS.getCallingConv();
7513 bool IsAnyRegCC = CC == CallingConv::AnyReg;
7514 bool HasDef = !CS->getType()->isVoidTy();
7515 SDLoc dl = getCurSDLoc();
7516 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7517
7518 // Handle immediate and symbolic callees.
7519 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7520 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7521 /*isTarget=*/true);
7522 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7523 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7524 SDLoc(SymbolicCallee),
7525 SymbolicCallee->getValueType(0));
7526
7527 // Get the real number of arguments participating in the call <numArgs>
7528 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7529 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7530
7531 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7532 // Intrinsics include all meta-operands up to but not including CC.
7533 unsigned NumMetaOpers = PatchPointOpers::CCPos;
7534 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&((CS.arg_size() >= NumMetaOpers + NumArgs && "Not enough arguments provided to the patchpoint intrinsic"
) ? static_cast<void> (0) : __assert_fail ("CS.arg_size() >= NumMetaOpers + NumArgs && \"Not enough arguments provided to the patchpoint intrinsic\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7535, __PRETTY_FUNCTION__))
7535 "Not enough arguments provided to the patchpoint intrinsic")((CS.arg_size() >= NumMetaOpers + NumArgs && "Not enough arguments provided to the patchpoint intrinsic"
) ? static_cast<void> (0) : __assert_fail ("CS.arg_size() >= NumMetaOpers + NumArgs && \"Not enough arguments provided to the patchpoint intrinsic\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7535, __PRETTY_FUNCTION__))
;
7536
7537 // For AnyRegCC the arguments are lowered later on manually.
7538 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7539 Type *ReturnTy =
7540 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7541
7542 TargetLowering::CallLoweringInfo CLI(DAG);
7543 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7544 true);
7545 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7546
7547 SDNode *CallEnd = Result.second.getNode();
7548 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7549 CallEnd = CallEnd->getOperand(0).getNode();
7550
7551 /// Get a call instruction from the call sequence chain.
7552 /// Tail calls are not allowed.
7553 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&((CallEnd->getOpcode() == ISD::CALLSEQ_END && "Expected a callseq node."
) ? static_cast<void> (0) : __assert_fail ("CallEnd->getOpcode() == ISD::CALLSEQ_END && \"Expected a callseq node.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7554, __PRETTY_FUNCTION__))
7554 "Expected a callseq node.")((CallEnd->getOpcode() == ISD::CALLSEQ_END && "Expected a callseq node."
) ? static_cast<void> (0) : __assert_fail ("CallEnd->getOpcode() == ISD::CALLSEQ_END && \"Expected a callseq node.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7554, __PRETTY_FUNCTION__))
;
7555 SDNode *Call = CallEnd->getOperand(0).getNode();
7556 bool HasGlue = Call->getGluedNode();
7557
7558 // Replace the target specific call node with the patchable intrinsic.
7559 SmallVector<SDValue, 8> Ops;
7560
7561 // Add the <id> and <numBytes> constants.
7562 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7563 Ops.push_back(DAG.getTargetConstant(
7564 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7565 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7566 Ops.push_back(DAG.getTargetConstant(
7567 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7568 MVT::i32));
7569
7570 // Add the callee.
7571 Ops.push_back(Callee);
7572
7573 // Adjust <numArgs> to account for any arguments that have been passed on the
7574 // stack instead.
7575 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7576 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7577 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7578 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7579
7580 // Add the calling convention
7581 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7582
7583 // Add the arguments we omitted previously. The register allocator should
7584 // place these in any free register.
7585 if (IsAnyRegCC)
7586 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7587 Ops.push_back(getValue(CS.getArgument(i)));
7588
7589 // Push the arguments from the call instruction up to the register mask.
7590 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7591 Ops.append(Call->op_begin() + 2, e);
7592
7593 // Push live variables for the stack map.
7594 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7595
7596 // Push the register mask info.
7597 if (HasGlue)
7598 Ops.push_back(*(Call->op_end()-2));
7599 else
7600 Ops.push_back(*(Call->op_end()-1));
7601
7602 // Push the chain (this is originally the first operand of the call, but
7603 // becomes now the last or second to last operand).
7604 Ops.push_back(*(Call->op_begin()));
7605
7606 // Push the glue flag (last operand).
7607 if (HasGlue)
7608 Ops.push_back(*(Call->op_end()-1));
7609
7610 SDVTList NodeTys;
7611 if (IsAnyRegCC && HasDef) {
7612 // Create the return types based on the intrinsic definition
7613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7614 SmallVector<EVT, 3> ValueVTs;
7615 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7616 assert(ValueVTs.size() == 1 && "Expected only one return value type.")((ValueVTs.size() == 1 && "Expected only one return value type."
) ? static_cast<void> (0) : __assert_fail ("ValueVTs.size() == 1 && \"Expected only one return value type.\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn290870/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 7616, __PRETTY_FUNCTION__))
;
7617
7618 // There is always a chain and a glue type at the end
7619 ValueVTs.push_back(MVT::Other);
7620 ValueVTs.push_back(MVT::Glue);
7621 NodeTys = DAG.getVTList(ValueVTs);
7622 } else
7623 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7624
7625 // Replace the target specific call node with a PATCHPOINT node.
7626 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7627 dl, NodeTys, Ops);
7628
7629 // Update the NodeMap.
7630 if (HasDef) {
7631 if (IsAnyRegCC)
7632 setValue(CS.getInstruction(), SDValue(MN, 0));
7633 else
7634 setValue(CS.getInstruction(), Result.first);
7635 }
7636
7637 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7638 // call sequence. Furthermore the location of the chain and glue can change
7639 // when the AnyReg calling convention is used and the intrinsic returns a
7640 // value.
7641 if (IsAnyRegCC && HasDef) {
7642 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7643 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7644 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7645 } else
7646 DAG.ReplaceAllUsesWith(Call, MN);
7647 DAG.DeleteNode(Call);
7648
7649 // Inform the Frame Information that we have a patchpoint in this function.
7650 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
7651}
7652
7653/// Returns an AttributeSet representing the attributes applied to the return
7654/// value of the given call.
7655static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7656 SmallVector<Attribute::AttrKind, 2> Attrs;
7657 if (CLI.RetSExt)
7658 Attrs.push_back(Attribute::SExt);
7659 if (CLI.RetZExt)
7660 Attrs.push_back(Attribute::ZExt);
7661 if (CLI.IsInReg)
7662 Attrs.push_back(Attribute::InReg);
7663
7664 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7665 Attrs);
7666}
7667
7668/// TargetLowering::LowerCallTo - This is the default LowerCallTo
7669/// implementation, which just calls LowerCall.
7670/// FIXME: When all targets are
7671/// migrated to using LowerCall, this hook should be integrated into SDISel.
7672std::pair<SDValue, SDValue>
7673TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7674 // Handle the incoming return values from the call.
7675 CLI.Ins.clear();
7676 Type *OrigRetTy = CLI.RetTy;
7677 SmallVector<EVT, 4> RetTys;
7678 SmallVector<uint64_t, 4> Offsets;
7679 auto &DL = CLI.DAG.getDataLayout();
7680 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7681
7682 SmallVector<ISD::OutputArg, 4> Outs;
7683 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7684
7685 bool CanLowerReturn =
7686 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7687 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7688
7689 SDValue DemoteStackSlot;
7690 int DemoteStackIdx = -100;
7691 if (!CanLowerReturn) {
7692 // FIXME: equivalent assert?
7693 // assert(!CS.hasInAllocaArgument() &&
7694 // "sret demotion is incompatible with inalloca");
7695 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7696 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7697 MachineFunction &MF = CLI.DAG.getMachineFunction();
7698 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7699 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7700
7701 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
7702 ArgListEntry Entry;
7703 Entry.Node = DemoteStackSlot;
7704 Entry.Ty = StackSlotPtrType;
7705 Entry.isSExt = false;
7706 Entry.isZExt = false;
7707 Entry.isInReg = false;
7708 Entry.isSRet = true;
7709 Entry.isNest = false;
7710 Entry.isByVal = false;
7711 Entry.isReturned = false;
7712 Entry.isSwiftSelf = false;
7713 Entry.isSwiftError = false;
7714 Entry.Alignment = Align;
7715 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7716 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7717
7718 // sret demotion isn't compatible with tail-calls, since the sret argument
7719 // points into the callers stack frame.
7720 CLI.IsTailCall = false;
7721 } else {
7722 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7723 EVT VT = RetTys[I];
7724 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7725 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7726 for (unsigned i = 0; i != NumRegs; ++i) {
7727 ISD::InputArg MyFlags;
7728 MyFlags.VT = RegisterVT;
7729 MyFlags.ArgVT = VT;
7730 MyFlags.Used = CLI.IsReturnValueUsed;
7731 if (CLI.RetSExt)
7732 MyFlags.Flags.setSExt();
7733 if (CLI.RetZExt)
7734 MyFlags.Flags.setZExt();
7735 if (CLI.IsInReg)
7736 MyFlags.Flags.setInReg();
7737 CLI.Ins.push_back(MyFlags);
7738 }
7739 }
7740 }
7741
7742 // We push in swifterror return as the last element of CLI.Ins.
7743 ArgListTy &Args = CLI.getArgs();
7744 if (supportSwiftError()) {
7745 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7746 if (Args[i].isSwiftError) {
77