blob: 00d6cc7ea23ff2f8fc4c3b7e801f0337856b316b [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00008//
Chris Lattnere17322b2011-02-07 20:03:14 +00009// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000010//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth9fb823b2013-01-02 11:36:10 +000013#include "llvm/IR/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000014#include "ConstantFold.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "LLVMContextImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000020#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/GlobalValue.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000027#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000028#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000030#include <algorithm>
Serge Gueltone38003f2017-05-09 19:31:13 +000031
Chris Lattner189d19f2003-11-21 20:23:48 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner2f7c9632001-06-06 20:29:01 +000034//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000035// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
37
Chris Lattnerac5fb562011-07-15 05:58:04 +000038bool Constant::isNegativeZeroValue() const {
39 // Floating point values have an explicit -0.0 value.
40 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
41 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000042
David Tweed5493fee2013-03-18 11:54:44 +000043 // Equivalent for a vector of -0.0's.
44 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000045 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
46 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweed5493fee2013-03-18 11:54:44 +000047 return true;
48
Owen Anderson8e851302015-11-20 22:34:48 +000049 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
50 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
51 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
52 return true;
53
David Tweed298e4192013-03-19 10:16:40 +000054 // We've already handled true FP case; any other FP vectors can't represent -0.0.
55 if (getType()->isFPOrFPVectorTy())
56 return false;
David Tweed5493fee2013-03-18 11:54:44 +000057
Chris Lattnerac5fb562011-07-15 05:58:04 +000058 // Otherwise, just use +0.0.
59 return isNullValue();
60}
61
Shuxin Yang9ca562e2013-01-09 00:53:25 +000062// Return true iff this constant is positive zero (floating point), negative
63// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000064bool Constant::isZeroValue() const {
65 // Floating point values have an explicit -0.0 value.
66 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
67 return CFP->isZero();
68
Owen Anderson630077e2015-11-20 08:16:13 +000069 // Equivalent for a vector of -0.0's.
70 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000071 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
72 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson630077e2015-11-20 08:16:13 +000073 return true;
74
Owen Anderson8e851302015-11-20 22:34:48 +000075 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
77 if (SplatCFP && SplatCFP->isZero())
78 return true;
79
Shuxin Yangf0537ab2013-01-09 00:13:41 +000080 // Otherwise, just use +0.0.
81 return isNullValue();
82}
83
Chris Lattnerbe6610c2011-07-15 06:14:08 +000084bool Constant::isNullValue() const {
85 // 0 is null.
86 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
87 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000088
Chris Lattnerbe6610c2011-07-15 06:14:08 +000089 // +0.0 is null.
90 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
91 return CFP->isZero() && !CFP->isNegative();
92
David Majnemerf0f224d2015-11-11 21:57:16 +000093 // constant zero is zero for aggregates, cpnull is null for pointers, none for
94 // tokens.
95 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
96 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +000097}
98
Nadav Rotem365af6f2011-08-24 20:18:38 +000099bool Constant::isAllOnesValue() const {
100 // Check for -1 integers
101 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
102 return CI->isMinusOne();
103
104 // Check for FP which are bitcasted from -1 integers
105 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
106 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
107
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000108 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000109 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000110 if (Constant *Splat = CV->getSplatValue())
111 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000112
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000113 // Check for constant vectors which are splats of -1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000114 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
115 if (CV->isSplat()) {
116 if (CV->getElementType()->isFloatingPointTy())
117 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
118 return CV->getElementAsAPInt(0).isAllOnesValue();
119 }
120 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000121
Nadav Rotem365af6f2011-08-24 20:18:38 +0000122 return false;
123}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000124
David Majnemer1a0bbc82014-08-16 09:23:42 +0000125bool Constant::isOneValue() const {
126 // Check for 1 integers
127 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128 return CI->isOne();
129
130 // Check for FP which are bitcasted from 1 integers
131 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
Craig Topper93ac6e12017-06-07 00:58:02 +0000132 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer1a0bbc82014-08-16 09:23:42 +0000133
134 // Check for constant vectors which are splats of 1 values.
135 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
136 if (Constant *Splat = CV->getSplatValue())
137 return Splat->isOneValue();
138
139 // Check for constant vectors which are splats of 1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000140 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
141 if (CV->isSplat()) {
142 if (CV->getElementType()->isFloatingPointTy())
143 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
144 return CV->getElementAsAPInt(0).isOneValue();
145 }
146 }
David Majnemer1a0bbc82014-08-16 09:23:42 +0000147
148 return false;
149}
150
David Majnemerbdeef602014-07-02 06:07:09 +0000151bool Constant::isMinSignedValue() const {
152 // Check for INT_MIN integers
153 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
154 return CI->isMinValue(/*isSigned=*/true);
155
156 // Check for FP which are bitcasted from INT_MIN integers
157 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
158 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
159
160 // Check for constant vectors which are splats of INT_MIN values.
161 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
162 if (Constant *Splat = CV->getSplatValue())
163 return Splat->isMinSignedValue();
164
165 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000166 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
167 if (CV->isSplat()) {
168 if (CV->getElementType()->isFloatingPointTy())
169 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
170 return CV->getElementAsAPInt(0).isMinSignedValue();
171 }
172 }
David Majnemerbdeef602014-07-02 06:07:09 +0000173
174 return false;
175}
176
David Majnemer0e6c9862014-08-22 16:41:23 +0000177bool Constant::isNotMinSignedValue() const {
178 // Check for INT_MIN integers
179 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
180 return !CI->isMinValue(/*isSigned=*/true);
181
182 // Check for FP which are bitcasted from INT_MIN integers
183 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
184 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
185
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000186 // Check that vectors don't contain INT_MIN
187 if (this->getType()->isVectorTy()) {
188 unsigned NumElts = this->getType()->getVectorNumElements();
189 for (unsigned i = 0; i != NumElts; ++i) {
190 Constant *Elt = this->getAggregateElement(i);
191 if (!Elt || !Elt->isNotMinSignedValue())
192 return false;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000193 }
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000194 return true;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000195 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000196
197 // It *may* contain INT_MIN, we can't tell.
198 return false;
199}
200
Sanjay Patel08868e4942018-02-16 22:32:54 +0000201bool Constant::isFiniteNonZeroFP() const {
202 if (auto *CFP = dyn_cast<ConstantFP>(this))
203 return CFP->getValueAPF().isFiniteNonZero();
204 if (!getType()->isVectorTy())
205 return false;
206 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209 return false;
210 }
211 return true;
212}
213
214bool Constant::isNormalFP() const {
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isNormal();
217 if (!getType()->isVectorTy())
218 return false;
219 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221 if (!CFP || !CFP->getValueAPF().isNormal())
222 return false;
223 }
224 return true;
225}
226
Sanjay Patel90f4c8e2018-02-20 16:08:15 +0000227bool Constant::hasExactInverseFP() const {
228 if (auto *CFP = dyn_cast<ConstantFP>(this))
229 return CFP->getValueAPF().getExactInverse(nullptr);
230 if (!getType()->isVectorTy())
231 return false;
232 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235 return false;
236 }
237 return true;
238}
239
Sanjay Patel46b083e2018-03-02 18:36:08 +0000240bool Constant::isNaN() const {
241 if (auto *CFP = dyn_cast<ConstantFP>(this))
242 return CFP->isNaN();
243 if (!getType()->isVectorTy())
244 return false;
245 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247 if (!CFP || !CFP->isNaN())
248 return false;
249 }
250 return true;
251}
252
Sanjay Patele6dda2f2018-07-06 14:52:36 +0000253bool Constant::containsUndefElement() const {
254 if (!getType()->isVectorTy())
255 return false;
256 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257 if (isa<UndefValue>(getAggregateElement(i)))
258 return true;
259
260 return false;
261}
262
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000263/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000264Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000265 switch (Ty->getTypeID()) {
266 case Type::IntegerTyID:
267 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000268 case Type::HalfTyID:
269 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000270 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000271 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000272 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000273 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000274 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000275 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000276 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000277 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000278 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000279 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000280 case Type::FP128TyID:
281 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000282 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000283 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000284 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000285 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000286 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000287 case Type::PointerTyID:
288 return ConstantPointerNull::get(cast<PointerType>(Ty));
289 case Type::StructTyID:
290 case Type::ArrayTyID:
291 case Type::VectorTyID:
292 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000293 case Type::TokenTyID:
294 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000295 default:
296 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000297 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000298 }
299}
300
Chris Lattner229907c2011-07-18 04:54:35 +0000301Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
302 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000303
304 // Create the base integer constant.
305 Constant *C = ConstantInt::get(Ty->getContext(), V);
306
307 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000308 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000309 C = ConstantExpr::getIntToPtr(C, PTy);
310
311 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000312 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000313 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000314
315 return C;
316}
317
Chris Lattner229907c2011-07-18 04:54:35 +0000318Constant *Constant::getAllOnesValue(Type *Ty) {
319 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000320 return ConstantInt::get(Ty->getContext(),
321 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000322
323 if (Ty->isFloatingPointTy()) {
324 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
325 !Ty->isPPC_FP128Ty());
326 return ConstantFP::get(Ty->getContext(), FL);
327 }
328
Chris Lattner229907c2011-07-18 04:54:35 +0000329 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000330 return ConstantVector::getSplat(VTy->getNumElements(),
331 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000332}
333
Chris Lattner7e683d12012-01-25 06:16:32 +0000334Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000335 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
336 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000337
David Majnemer9b529a72015-02-16 04:02:09 +0000338 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
339 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000340
Chris Lattner7e683d12012-01-25 06:16:32 +0000341 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000342 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000343
Chris Lattner8326bd82012-01-26 00:42:34 +0000344 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000345 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
346 : nullptr;
347 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000348}
349
350Constant *Constant::getAggregateElement(Constant *Elt) const {
351 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
Florian Hahncc419ad2018-12-12 02:22:12 +0000352 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
353 // Check if the constant fits into an uint64_t.
354 if (CI->getValue().getActiveBits() > 64)
355 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000356 return getAggregateElement(CI->getZExtValue());
Florian Hahncc419ad2018-12-12 02:22:12 +0000357 }
Craig Topperc6207612014-04-09 06:08:46 +0000358 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000359}
360
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000361void Constant::destroyConstant() {
362 /// First call destroyConstantImpl on the subclass. This gives the subclass
363 /// a chance to remove the constant from any maps/pools it's contained in.
364 switch (getValueID()) {
365 default:
366 llvm_unreachable("Not a constant!");
367#define HANDLE_CONSTANT(Name) \
368 case Value::Name##Val: \
369 cast<Name>(this)->destroyConstantImpl(); \
370 break;
371#include "llvm/IR/Value.def"
372 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000373
Chris Lattner3462ae32001-12-03 22:26:30 +0000374 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000375 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000376 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000377 // but they don't know that. Because we only find out when the CPV is
378 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000379 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000380 //
381 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000382 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000383#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000384 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000385 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000386 << "\n\nUse still stuck around after Def is destroyed: " << *V
387 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000388 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000389#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000390 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000391 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000392
393 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000394 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000395 }
396
397 // Value has no outstanding references it is safe to delete it now...
398 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000399}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000400
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000401static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000402 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000403 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000404 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000405 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
406 if (!CE)
407 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000408
409 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000410 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
411 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000412 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000413 return true;
414 }
415 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000416
417 // Otherwise, only specific operations can trap.
418 switch (CE->getOpcode()) {
419 default:
420 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000421 case Instruction::UDiv:
422 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000423 case Instruction::URem:
424 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000425 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000426 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000427 return true;
428 return false;
429 }
430}
431
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000432bool Constant::canTrap() const {
433 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
434 return canTrapImpl(this, NonTrappingOps);
435}
436
Hans Wennborg4dc89512014-06-20 00:38:12 +0000437/// Check if C contains a GlobalValue for which Predicate is true.
438static bool
439ConstHasGlobalValuePredicate(const Constant *C,
440 bool (*Predicate)(const GlobalValue *)) {
441 SmallPtrSet<const Constant *, 8> Visited;
442 SmallVector<const Constant *, 8> WorkList;
443 WorkList.push_back(C);
444 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000445
446 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000447 const Constant *WorkItem = WorkList.pop_back_val();
448 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
449 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000450 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000451 for (const Value *Op : WorkItem->operands()) {
452 const Constant *ConstOp = dyn_cast<Constant>(Op);
453 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000454 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000455 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000456 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000457 }
458 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000459 return false;
460}
461
Hans Wennborg4dc89512014-06-20 00:38:12 +0000462bool Constant::isThreadDependent() const {
463 auto DLLImportPredicate = [](const GlobalValue *GV) {
464 return GV->isThreadLocal();
465 };
466 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
467}
468
469bool Constant::isDLLImportDependent() const {
470 auto DLLImportPredicate = [](const GlobalValue *GV) {
471 return GV->hasDLLImportStorageClass();
472 };
473 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
474}
475
Chris Lattner253bc772009-11-01 18:11:50 +0000476bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000477 for (const User *U : users()) {
478 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000479 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000480 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000481
Chris Lattner253bc772009-11-01 18:11:50 +0000482 if (UC->isConstantUsed())
483 return true;
484 }
485 return false;
486}
487
Rafael Espindola65e49022015-11-17 00:51:23 +0000488bool Constant::needsRelocation() const {
489 if (isa<GlobalValue>(this))
490 return true; // Global reference.
491
Chris Lattner2cb85b42009-10-28 04:12:16 +0000492 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000493 return BA->getFunction()->needsRelocation();
494
Chris Lattnera7cfc432010-01-03 18:09:40 +0000495 // While raw uses of blockaddress need to be relocated, differences between
496 // two of them don't when they are for labels in the same function. This is a
497 // common idiom when creating a table for the indirect goto extension, so we
498 // handle it efficiently here.
499 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
500 if (CE->getOpcode() == Instruction::Sub) {
501 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
502 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000503 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000504 RHS->getOpcode() == Instruction::PtrToInt &&
505 isa<BlockAddress>(LHS->getOperand(0)) &&
506 isa<BlockAddress>(RHS->getOperand(0)) &&
507 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000508 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
509 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000510 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000511
Rafael Espindola65e49022015-11-17 00:51:23 +0000512 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000513 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000514 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000515
Chris Lattner4565ef52009-07-22 00:05:44 +0000516 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000517}
518
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000519/// If the specified constantexpr is dead, remove it. This involves recursively
520/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000521static bool removeDeadUsersOfConstant(const Constant *C) {
522 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000523
Chris Lattner84886402011-02-18 04:41:42 +0000524 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000525 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000526 if (!User) return false; // Non-constant usage;
527 if (!removeDeadUsersOfConstant(User))
528 return false; // Constant wasn't dead
529 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000530
Chris Lattner84886402011-02-18 04:41:42 +0000531 const_cast<Constant*>(C)->destroyConstant();
532 return true;
533}
534
535
Chris Lattner84886402011-02-18 04:41:42 +0000536void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000537 Value::const_user_iterator I = user_begin(), E = user_end();
538 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000539 while (I != E) {
540 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000541 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000542 LastNonDeadUser = I;
543 ++I;
544 continue;
545 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000546
Chris Lattner84886402011-02-18 04:41:42 +0000547 if (!removeDeadUsersOfConstant(User)) {
548 // If the constant wasn't dead, remember that this was the last live use
549 // and move on to the next constant.
550 LastNonDeadUser = I;
551 ++I;
552 continue;
553 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000554
Chris Lattner84886402011-02-18 04:41:42 +0000555 // If the constant was dead, then the iterator is invalidated.
556 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000557 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000558 if (I == E) break;
559 } else {
560 I = LastNonDeadUser;
561 ++I;
562 }
563 }
564}
565
566
Chris Lattner2105d662008-07-10 00:28:11 +0000567
Chris Lattner2f7c9632001-06-06 20:29:01 +0000568//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000569// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000570//===----------------------------------------------------------------------===//
571
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000572ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
573 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000574 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000575}
576
Nick Lewycky92db8e82011-03-06 03:36:19 +0000577ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000578 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000579 if (!pImpl->TheTrueVal)
580 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
581 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000582}
583
Nick Lewycky92db8e82011-03-06 03:36:19 +0000584ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000585 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000586 if (!pImpl->TheFalseVal)
587 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
588 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000589}
590
Chris Lattner229907c2011-07-18 04:54:35 +0000591Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000592 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000593 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
594 if (auto *VTy = dyn_cast<VectorType>(Ty))
595 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
596 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000597}
598
Chris Lattner229907c2011-07-18 04:54:35 +0000599Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000600 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000601 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
602 if (auto *VTy = dyn_cast<VectorType>(Ty))
603 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
604 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000605}
606
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000607// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000608ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000609 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000610 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000611 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000612 if (!Slot) {
613 // Get the corresponding integer type for the bit width of the value.
614 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000615 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000616 }
617 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000618 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000619}
620
Chris Lattner229907c2011-07-18 04:54:35 +0000621Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000622 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000623
624 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000625 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000626 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000627
628 return C;
629}
630
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000631ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000632 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
633}
634
Chris Lattner0256be92012-01-27 03:08:05 +0000635ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000636 return get(Ty, V, true);
637}
638
Chris Lattner229907c2011-07-18 04:54:35 +0000639Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000640 return get(Ty, V, true);
641}
642
Chris Lattner0256be92012-01-27 03:08:05 +0000643Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000644 ConstantInt *C = get(Ty->getContext(), V);
645 assert(C->getType() == Ty->getScalarType() &&
646 "ConstantInt type doesn't match the type implied by its value!");
647
648 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000649 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000650 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000651
652 return C;
653}
654
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000655ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000656 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
657}
658
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000659/// Remove the constant from the constant table.
660void ConstantInt::destroyConstantImpl() {
661 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
662}
663
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000664//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000665// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000666//===----------------------------------------------------------------------===//
667
Chris Lattner229907c2011-07-18 04:54:35 +0000668static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000669 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000670 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000671 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000672 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000673 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000674 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000675 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000676 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000677 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000678 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000679
Chris Lattnerfdd87902009-10-05 05:54:46 +0000680 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000681 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000682}
683
Chris Lattner0256be92012-01-27 03:08:05 +0000684Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000685 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000686
Owen Anderson69c464d2009-07-27 20:59:43 +0000687 APFloat FV(V);
688 bool ignored;
689 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
690 APFloat::rmNearestTiesToEven, &ignored);
691 Constant *C = get(Context, FV);
692
693 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000694 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000695 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000696
697 return C;
698}
699
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000700Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
701 ConstantFP *C = get(Ty->getContext(), V);
702 assert(C->getType() == Ty->getScalarType() &&
703 "ConstantFP type doesn't match the type implied by its value!");
704
705 // For vectors, broadcast the value.
706 if (auto *VTy = dyn_cast<VectorType>(Ty))
707 return ConstantVector::getSplat(VTy->getNumElements(), C);
708
709 return C;
710}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000711
Chris Lattner0256be92012-01-27 03:08:05 +0000712Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000713 LLVMContext &Context = Ty->getContext();
714
715 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
716 Constant *C = get(Context, FV);
717
718 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000719 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000720 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000721
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000722 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000723}
724
JF Bastien69f60982018-12-10 19:27:38 +0000725Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
Tom Stellard67246d12015-04-20 19:38:24 +0000726 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
JF Bastien69f60982018-12-10 19:27:38 +0000727 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
Tom Stellard67246d12015-04-20 19:38:24 +0000728 Constant *C = get(Ty->getContext(), NaN);
729
730 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
731 return ConstantVector::getSplat(VTy->getNumElements(), C);
732
733 return C;
734}
735
JF Bastien69f60982018-12-10 19:27:38 +0000736Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
737 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
738 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
739 Constant *C = get(Ty->getContext(), NaN);
740
741 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
742 return ConstantVector::getSplat(VTy->getNumElements(), C);
743
744 return C;
745}
746
747Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
748 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
749 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
750 Constant *C = get(Ty->getContext(), NaN);
751
752 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
753 return ConstantVector::getSplat(VTy->getNumElements(), C);
754
755 return C;
756}
757
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000758Constant *ConstantFP::getNegativeZero(Type *Ty) {
759 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
760 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
761 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000762
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000763 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
764 return ConstantVector::getSplat(VTy->getNumElements(), C);
765
766 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000767}
768
769
Chris Lattnere9eed292012-01-25 05:19:54 +0000770Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000771 if (Ty->isFPOrFPVectorTy())
772 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000773
Owen Anderson5a1acd92009-07-31 20:28:14 +0000774 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000775}
776
777
778// ConstantFP accessors.
779ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000780 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000781
Justin Lebar611c5c22016-10-10 16:26:13 +0000782 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000783
Owen Anderson69c464d2009-07-27 20:59:43 +0000784 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000785 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000786 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000787 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000788 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000789 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000790 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000791 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000792 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000793 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000794 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000795 Ty = Type::getFP128Ty(Context);
796 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000797 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000798 "Unknown FP format");
799 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000800 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000801 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000802 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000803
Justin Lebar611c5c22016-10-10 16:26:13 +0000804 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000805}
806
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000807Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
808 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
809 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
810
811 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
812 return ConstantVector::getSplat(VTy->getNumElements(), C);
813
814 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000815}
816
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000817ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
818 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000819 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
820 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000821}
822
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000823bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000824 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000825}
826
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000827/// Remove the constant from the constant table.
828void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000829 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000830}
831
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000832//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000833// ConstantAggregateZero Implementation
834//===----------------------------------------------------------------------===//
835
Chris Lattner7e683d12012-01-25 06:16:32 +0000836Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000837 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000838}
839
Chris Lattner7e683d12012-01-25 06:16:32 +0000840Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000841 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000842}
843
Chris Lattner7e683d12012-01-25 06:16:32 +0000844Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000845 if (isa<SequentialType>(getType()))
846 return getSequentialElement();
847 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
848}
849
Chris Lattner7e683d12012-01-25 06:16:32 +0000850Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000851 if (isa<SequentialType>(getType()))
852 return getSequentialElement();
853 return getStructElement(Idx);
854}
855
David Majnemer9b529a72015-02-16 04:02:09 +0000856unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000857 Type *Ty = getType();
858 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000859 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000860 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000861 return VT->getNumElements();
862 return Ty->getStructNumElements();
863}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000864
Chris Lattner030af792012-01-24 05:42:11 +0000865//===----------------------------------------------------------------------===//
866// UndefValue Implementation
867//===----------------------------------------------------------------------===//
868
Chris Lattner7e683d12012-01-25 06:16:32 +0000869UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000870 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000871}
872
Chris Lattner7e683d12012-01-25 06:16:32 +0000873UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000874 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000875}
876
Chris Lattner7e683d12012-01-25 06:16:32 +0000877UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000878 if (isa<SequentialType>(getType()))
879 return getSequentialElement();
880 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
881}
882
Chris Lattner7e683d12012-01-25 06:16:32 +0000883UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000884 if (isa<SequentialType>(getType()))
885 return getSequentialElement();
886 return getStructElement(Idx);
887}
888
David Majnemer9b529a72015-02-16 04:02:09 +0000889unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000890 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000891 if (auto *ST = dyn_cast<SequentialType>(Ty))
892 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000893 return Ty->getStructNumElements();
894}
Chris Lattner030af792012-01-24 05:42:11 +0000895
896//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000897// ConstantXXX Classes
898//===----------------------------------------------------------------------===//
899
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000900template <typename ItTy, typename EltTy>
901static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
902 for (; Start != End; ++Start)
903 if (*Start != Elt)
904 return false;
905 return true;
906}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000907
Justin Bogner909e1c02015-12-01 20:20:49 +0000908template <typename SequentialTy, typename ElementTy>
909static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
910 assert(!V.empty() && "Cannot get empty int sequence.");
911
912 SmallVector<ElementTy, 16> Elts;
913 for (Constant *C : V)
914 if (auto *CI = dyn_cast<ConstantInt>(C))
915 Elts.push_back(CI->getZExtValue());
916 else
917 return nullptr;
918 return SequentialTy::get(V[0]->getContext(), Elts);
919}
920
921template <typename SequentialTy, typename ElementTy>
922static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
923 assert(!V.empty() && "Cannot get empty FP sequence.");
924
925 SmallVector<ElementTy, 16> Elts;
926 for (Constant *C : V)
927 if (auto *CFP = dyn_cast<ConstantFP>(C))
928 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
929 else
930 return nullptr;
931 return SequentialTy::getFP(V[0]->getContext(), Elts);
932}
933
934template <typename SequenceTy>
935static Constant *getSequenceIfElementsMatch(Constant *C,
936 ArrayRef<Constant *> V) {
937 // We speculatively build the elements here even if it turns out that there is
938 // a constantexpr or something else weird, since it is so uncommon for that to
939 // happen.
940 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
941 if (CI->getType()->isIntegerTy(8))
942 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
943 else if (CI->getType()->isIntegerTy(16))
944 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
945 else if (CI->getType()->isIntegerTy(32))
946 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
947 else if (CI->getType()->isIntegerTy(64))
948 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
949 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000950 if (CFP->getType()->isHalfTy())
951 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
952 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000953 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
954 else if (CFP->getType()->isDoubleTy())
955 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
956 }
957
958 return nullptr;
959}
960
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000961ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
962 ArrayRef<Constant *> V)
963 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
964 V.size()) {
Fangrui Song75709322018-11-17 01:44:25 +0000965 llvm::copy(V, op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000966
967 // Check that types match, unless this is an opaque struct.
968 if (auto *ST = dyn_cast<StructType>(T))
969 if (ST->isOpaque())
970 return;
971 for (unsigned I = 0, E = V.size(); I != E; ++I)
972 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
973 "Initializer for composite element doesn't match!");
974}
975
976ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
977 : ConstantAggregate(T, ConstantArrayVal, V) {
978 assert(V.size() == T->getNumElements() &&
979 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000980}
981
Chris Lattner229907c2011-07-18 04:54:35 +0000982Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000983 if (Constant *C = getImpl(Ty, V))
984 return C;
985 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
986}
Justin Bogner909e1c02015-12-01 20:20:49 +0000987
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000988Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000989 // Empty arrays are canonicalized to ConstantAggregateZero.
990 if (V.empty())
991 return ConstantAggregateZero::get(Ty);
992
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000993 for (unsigned i = 0, e = V.size(); i != e; ++i) {
994 assert(V[i]->getType() == Ty->getElementType() &&
995 "Wrong type in array element initializer");
996 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000997
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000998 // If this is an all-zero array, return a ConstantAggregateZero object. If
999 // all undef, return an UndefValue, if "all simple", then return a
1000 // ConstantDataArray.
1001 Constant *C = V[0];
1002 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1003 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001004
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001005 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1006 return ConstantAggregateZero::get(Ty);
1007
1008 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1009 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001010 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1011 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001012
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001013 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001014 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +00001015}
1016
Chris Lattnercc19efa2011-06-20 04:01:31 +00001017StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1018 ArrayRef<Constant*> V,
1019 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +00001020 unsigned VecSize = V.size();
1021 SmallVector<Type*, 16> EltTypes(VecSize);
1022 for (unsigned i = 0; i != VecSize; ++i)
1023 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +00001024
Chris Lattnercc19efa2011-06-20 04:01:31 +00001025 return StructType::get(Context, EltTypes, Packed);
1026}
1027
1028
1029StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1030 bool Packed) {
1031 assert(!V.empty() &&
1032 "ConstantStruct::getTypeForElements cannot be called on empty list");
1033 return getTypeForElements(V[0]->getContext(), V, Packed);
1034}
1035
Jay Foad89d9b812011-07-25 10:14:44 +00001036ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001037 : ConstantAggregate(T, ConstantStructVal, V) {
1038 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1039 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001040}
1041
Owen Anderson45308b52009-07-27 22:29:26 +00001042// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001043Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001044 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1045 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001046
1047 // Create a ConstantAggregateZero value if all elements are zeros.
1048 bool isZero = true;
1049 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001050
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001051 if (!V.empty()) {
1052 isUndef = isa<UndefValue>(V[0]);
1053 isZero = V[0]->isNullValue();
1054 if (isUndef || isZero) {
1055 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1056 if (!V[i]->isNullValue())
1057 isZero = false;
1058 if (!isa<UndefValue>(V[i]))
1059 isUndef = false;
1060 }
1061 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001062 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001063 if (isZero)
1064 return ConstantAggregateZero::get(ST);
1065 if (isUndef)
1066 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001067
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001068 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001069}
1070
Jay Foad89d9b812011-07-25 10:14:44 +00001071ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001072 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001073 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001074 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001075}
1076
Owen Anderson4aa32952009-07-28 21:19:26 +00001077// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001078Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001079 if (Constant *C = getImpl(V))
1080 return C;
1081 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1082 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1083}
Justin Bogner909e1c02015-12-01 20:20:49 +00001084
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001085Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001086 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001087 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001088
Chris Lattner69229312011-02-15 00:14:00 +00001089 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001090 // ConstantAggregateZero or UndefValue.
1091 Constant *C = V[0];
1092 bool isZero = C->isNullValue();
1093 bool isUndef = isa<UndefValue>(C);
1094
1095 if (isZero || isUndef) {
1096 for (unsigned i = 1, e = V.size(); i != e; ++i)
1097 if (V[i] != C) {
1098 isZero = isUndef = false;
1099 break;
1100 }
1101 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001102
Owen Anderson4aa32952009-07-28 21:19:26 +00001103 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001104 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001105 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001106 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001107
Chris Lattner978fe0c2012-01-30 06:21:21 +00001108 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1109 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001110 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1111 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001112
Chris Lattner978fe0c2012-01-30 06:21:21 +00001113 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001114 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001115 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001116}
1117
Chris Lattnere9eed292012-01-25 05:19:54 +00001118Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001119 // If this splat is compatible with ConstantDataVector, use it instead of
1120 // ConstantVector.
1121 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1122 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1123 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001124
Chris Lattnere9eed292012-01-25 05:19:54 +00001125 SmallVector<Constant*, 32> Elts(NumElts, V);
1126 return get(Elts);
1127}
1128
David Majnemerf0f224d2015-11-11 21:57:16 +00001129ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1130 LLVMContextImpl *pImpl = Context.pImpl;
1131 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001132 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1133 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001134}
1135
1136/// Remove the constant from the constant table.
1137void ConstantTokenNone::destroyConstantImpl() {
1138 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1139}
Chris Lattnere9eed292012-01-25 05:19:54 +00001140
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001141// Utility function for determining if a ConstantExpr is a CastOp or not. This
1142// can't be inline because we don't want to #include Instruction.h into
1143// Constant.h
1144bool ConstantExpr::isCast() const {
1145 return Instruction::isCast(getOpcode());
1146}
1147
Reid Spenceree3c9912006-12-04 05:19:50 +00001148bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001149 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001150}
1151
Dan Gohman7190d482009-09-10 23:37:55 +00001152bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1153 if (getOpcode() != Instruction::GetElementPtr) return false;
1154
1155 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001156 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001157
Sanjay Patel81ed3492016-12-11 20:07:02 +00001158 // The remaining indices may be compile-time known integers within the bounds
1159 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001160 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001161 if (isa<UndefValue>(*OI))
1162 continue;
1163 auto *CI = dyn_cast<ConstantInt>(*OI);
1164 if (!CI || (GEPI.isBoundedSequential() &&
1165 (CI->getValue().getActiveBits() > 64 ||
1166 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001167 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001168 }
1169
1170 // All the indices checked out.
1171 return true;
1172}
1173
Dan Gohman1ecaf452008-05-31 00:58:22 +00001174bool ConstantExpr::hasIndices() const {
1175 return getOpcode() == Instruction::ExtractValue ||
1176 getOpcode() == Instruction::InsertValue;
1177}
1178
Jay Foad0091fe82011-04-13 15:22:40 +00001179ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001180 if (const ExtractValueConstantExpr *EVCE =
1181 dyn_cast<ExtractValueConstantExpr>(this))
1182 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001183
1184 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001185}
1186
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001187unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001188 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001189}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001190
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001191Constant *
1192ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001193 assert(Op->getType() == getOperand(OpNo)->getType() &&
1194 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001195 if (getOperand(OpNo) == Op)
1196 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001197
1198 SmallVector<Constant*, 8> NewOps;
1199 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1200 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001201
Chris Lattner37e38352012-01-26 20:37:11 +00001202 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001203}
1204
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001205Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001206 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001207 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001208
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001209 // If no operands changed return self.
1210 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001211 return const_cast<ConstantExpr*>(this);
1212
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001213 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001214 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001215 case Instruction::Trunc:
1216 case Instruction::ZExt:
1217 case Instruction::SExt:
1218 case Instruction::FPTrunc:
1219 case Instruction::FPExt:
1220 case Instruction::UIToFP:
1221 case Instruction::SIToFP:
1222 case Instruction::FPToUI:
1223 case Instruction::FPToSI:
1224 case Instruction::PtrToInt:
1225 case Instruction::IntToPtr:
1226 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001227 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001228 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001229 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001230 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001231 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001232 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1233 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001234 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001235 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001236 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001237 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1238 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001239 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001240 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001241 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001242 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1243 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001244 case Instruction::GetElementPtr: {
1245 auto *GEPO = cast<GEPOperator>(this);
1246 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1247 return ConstantExpr::getGetElementPtr(
1248 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001249 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001250 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001251 case Instruction::ICmp:
1252 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001253 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1254 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001255 default:
1256 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001257 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1258 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001259 }
1260}
1261
Chris Lattner2f7c9632001-06-06 20:29:01 +00001262
1263//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001264// isValueValidForType implementations
1265
Chris Lattner229907c2011-07-18 04:54:35 +00001266bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001267 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1268 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001269 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001270 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001271}
1272
Chris Lattner229907c2011-07-18 04:54:35 +00001273bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001274 unsigned NumBits = Ty->getIntegerBitWidth();
1275 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001276 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001277 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001278}
1279
Chris Lattner229907c2011-07-18 04:54:35 +00001280bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001281 // convert modifies in place, so make a copy.
1282 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001283 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001284 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001285 default:
1286 return false; // These can't be represented as floating point!
1287
Dale Johannesend246b2c2007-08-30 00:23:21 +00001288 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001289 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001290 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001291 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001292 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001293 return !losesInfo;
1294 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001295 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001296 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001297 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001298 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001299 return !losesInfo;
1300 }
1301 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001302 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1303 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1304 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001305 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001306 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001307 return !losesInfo;
1308 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001309 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001310 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001311 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001312 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1313 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001314 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001315 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001316 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001317 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1318 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001319 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001320 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001321 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001322 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1323 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001324 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001325}
Chris Lattner9655e542001-07-20 19:16:02 +00001326
Chris Lattner030af792012-01-24 05:42:11 +00001327
Chris Lattner49d855c2001-09-07 16:46:31 +00001328//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001329// Factory Function Implementation
1330
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001331ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001332 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001333 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001334
Justin Lebar611c5c22016-10-10 16:26:13 +00001335 std::unique_ptr<ConstantAggregateZero> &Entry =
1336 Ty->getContext().pImpl->CAZConstants[Ty];
1337 if (!Entry)
1338 Entry.reset(new ConstantAggregateZero(Ty));
1339
1340 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001341}
1342
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001343/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001344void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001345 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001346}
1347
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001348/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001349void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001350 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001351}
1352
Chris Lattner81fabb02002-08-26 17:53:56 +00001353
Chris Lattner3462ae32001-12-03 22:26:30 +00001354//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001355//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001356
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001357/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001358void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001359 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001360}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001361
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001362/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001363void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001364 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001365}
1366
Duncan Sandse6beec62012-11-13 12:59:33 +00001367Constant *Constant::getSplatValue() const {
1368 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1369 if (isa<ConstantAggregateZero>(this))
1370 return getNullValue(this->getType()->getVectorElementType());
1371 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1372 return CV->getSplatValue();
1373 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1374 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001375 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001376}
1377
Duncan Sandscf0ff032011-02-01 08:39:12 +00001378Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001379 // Check out first element.
1380 Constant *Elt = getOperand(0);
1381 // Then make sure all remaining elements point to the same value.
1382 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001383 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001384 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001385 return Elt;
1386}
1387
Duncan Sandse6beec62012-11-13 12:59:33 +00001388const APInt &Constant::getUniqueInteger() const {
1389 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1390 return CI->getValue();
1391 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1392 const Constant *C = this->getAggregateElement(0U);
1393 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1394 return cast<ConstantInt>(C)->getValue();
1395}
1396
Chris Lattner31b132c2009-10-28 00:01:44 +00001397//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001398//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001399
Chris Lattner229907c2011-07-18 04:54:35 +00001400ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001401 std::unique_ptr<ConstantPointerNull> &Entry =
1402 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001403 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001404 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001405
Justin Lebar611c5c22016-10-10 16:26:13 +00001406 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001407}
1408
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001409/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001410void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001411 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001412}
1413
Chris Lattner229907c2011-07-18 04:54:35 +00001414UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001415 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001416 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001417 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001418
Justin Lebar611c5c22016-10-10 16:26:13 +00001419 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001420}
1421
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001422/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001423void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001424 // Free the constant and any dangling references to it.
1425 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001426}
1427
Chris Lattner31b132c2009-10-28 00:01:44 +00001428BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001429 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001430 return get(BB->getParent(), BB);
1431}
1432
1433BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1434 BlockAddress *&BA =
1435 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001436 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001437 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001438
Chris Lattner31b132c2009-10-28 00:01:44 +00001439 assert(BA->getFunction() == F && "Basic block moved between functions");
1440 return BA;
1441}
1442
1443BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1444: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1445 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001446 setOperand(0, F);
1447 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001448 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001449}
1450
Chandler Carruth6a936922014-01-19 02:13:50 +00001451BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1452 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001453 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001454
1455 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001456 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001457 BlockAddress *BA =
1458 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1459 assert(BA && "Refcount and block address map disagree!");
1460 return BA;
1461}
Chris Lattner31b132c2009-10-28 00:01:44 +00001462
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001463/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001464void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001465 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001466 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001467 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001468}
1469
Mehdi Amini8914d292016-02-10 22:47:15 +00001470Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001471 // This could be replacing either the Basic Block or the Function. In either
1472 // case, we have to remove the map entry.
1473 Function *NewF = getFunction();
1474 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001475
Mehdi Amini8914d292016-02-10 22:47:15 +00001476 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001477 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001478 else {
1479 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001480 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001481 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001482
Chris Lattner31b132c2009-10-28 00:01:44 +00001483 // See if the 'new' entry already exists, if not, just update this in place
1484 // and return early.
1485 BlockAddress *&NewBA =
1486 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001487 if (NewBA)
1488 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001489
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001490 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001491
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001492 // Remove the old entry, this can't cause the map to rehash (just a
1493 // tombstone will get added).
1494 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1495 getBasicBlock()));
1496 NewBA = this;
1497 setOperand(0, NewF);
1498 setOperand(1, NewBB);
1499 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001500
1501 // If we just want to keep the existing value, then return null.
1502 // Callers know that this means we shouldn't delete this value.
1503 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001504}
1505
1506//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001507//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001508
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001509/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001510/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001511static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1512 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001513 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001514 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001515 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001516 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001517
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001518 if (OnlyIfReduced)
1519 return nullptr;
1520
Owen Anderson1584a292009-08-04 20:25:11 +00001521 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1522
Nadav Rotem88330432013-03-07 01:30:40 +00001523 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001524 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001525
Owen Anderson1584a292009-08-04 20:25:11 +00001526 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001527}
Galina Kistanovafc259902012-07-13 01:25:27 +00001528
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001529Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1530 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001531 Instruction::CastOps opc = Instruction::CastOps(oc);
1532 assert(Instruction::isCast(opc) && "opcode out of range");
1533 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001534 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001535
1536 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001537 default:
1538 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001539 case Instruction::Trunc:
1540 return getTrunc(C, Ty, OnlyIfReduced);
1541 case Instruction::ZExt:
1542 return getZExt(C, Ty, OnlyIfReduced);
1543 case Instruction::SExt:
1544 return getSExt(C, Ty, OnlyIfReduced);
1545 case Instruction::FPTrunc:
1546 return getFPTrunc(C, Ty, OnlyIfReduced);
1547 case Instruction::FPExt:
1548 return getFPExtend(C, Ty, OnlyIfReduced);
1549 case Instruction::UIToFP:
1550 return getUIToFP(C, Ty, OnlyIfReduced);
1551 case Instruction::SIToFP:
1552 return getSIToFP(C, Ty, OnlyIfReduced);
1553 case Instruction::FPToUI:
1554 return getFPToUI(C, Ty, OnlyIfReduced);
1555 case Instruction::FPToSI:
1556 return getFPToSI(C, Ty, OnlyIfReduced);
1557 case Instruction::PtrToInt:
1558 return getPtrToInt(C, Ty, OnlyIfReduced);
1559 case Instruction::IntToPtr:
1560 return getIntToPtr(C, Ty, OnlyIfReduced);
1561 case Instruction::BitCast:
1562 return getBitCast(C, Ty, OnlyIfReduced);
1563 case Instruction::AddrSpaceCast:
1564 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001565 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001566}
Reid Spencerf37dc652006-12-05 19:14:13 +00001567
Chris Lattner229907c2011-07-18 04:54:35 +00001568Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001569 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001570 return getBitCast(C, Ty);
1571 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001572}
1573
Chris Lattner229907c2011-07-18 04:54:35 +00001574Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001575 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001576 return getBitCast(C, Ty);
1577 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001578}
1579
Chris Lattner229907c2011-07-18 04:54:35 +00001580Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001581 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001582 return getBitCast(C, Ty);
1583 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001584}
1585
Chris Lattner229907c2011-07-18 04:54:35 +00001586Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001587 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1588 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1589 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001590
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001591 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001592 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001593
1594 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1595 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1596 return getAddrSpaceCast(S, Ty);
1597
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001598 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001599}
1600
Matt Arsenault21f38f42013-12-07 02:58:41 +00001601Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1602 Type *Ty) {
1603 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1604 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1605
1606 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1607 return getAddrSpaceCast(S, Ty);
1608
1609 return getBitCast(S, Ty);
1610}
1611
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001612Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001613 assert(C->getType()->isIntOrIntVectorTy() &&
1614 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001615 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1616 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001617 Instruction::CastOps opcode =
1618 (SrcBits == DstBits ? Instruction::BitCast :
1619 (SrcBits > DstBits ? Instruction::Trunc :
1620 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1621 return getCast(opcode, C, Ty);
1622}
1623
Chris Lattner229907c2011-07-18 04:54:35 +00001624Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001625 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001626 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001627 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1628 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001629 if (SrcBits == DstBits)
1630 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001631 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001632 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001633 return getCast(opcode, C, Ty);
1634}
1635
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001636Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001637#ifndef NDEBUG
1638 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1639 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1640#endif
1641 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001642 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1643 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001644 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001645 "SrcTy must be larger than DestTy for Trunc!");
1646
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001647 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001648}
1649
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001650Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001651#ifndef NDEBUG
1652 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1653 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1654#endif
1655 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001656 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1657 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001658 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001659 "SrcTy must be smaller than DestTy for SExt!");
1660
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001661 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001662}
1663
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001664Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001665#ifndef NDEBUG
1666 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1667 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1668#endif
1669 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001670 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1671 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001672 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001673 "SrcTy must be smaller than DestTy for ZExt!");
1674
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001675 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001676}
1677
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001678Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001679#ifndef NDEBUG
1680 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1681 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1682#endif
1683 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001684 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001685 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001686 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001687 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001688}
1689
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001690Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001691#ifndef NDEBUG
1692 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1693 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1694#endif
1695 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001696 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001697 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001699 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001700}
1701
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001702Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001703#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001704 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1705 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001706#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001707 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001708 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001709 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001710 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711}
1712
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001713Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001714#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001715 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001717#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001718 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001719 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001720 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001721 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001722}
1723
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001724Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001725#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001726 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1727 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001728#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001729 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001730 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001731 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001732 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001733}
1734
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001735Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001736#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001737 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1738 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001739#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001740 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001741 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001742 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001743 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001744}
1745
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001746Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1747 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001748 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001749 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001750 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001751 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001752 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001753 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001754 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001755 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001756 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001757}
1758
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001759Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1760 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001761 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001762 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001763 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001764 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001765 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001766 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001767 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001768 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001769 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001770}
1771
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001772Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1773 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001774 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1775 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001776
Chris Lattnercbeda872009-03-21 06:55:54 +00001777 // It is common to ask for a bitcast of a value to its own type, handle this
1778 // speedily.
1779 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001780
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001781 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001782}
1783
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001784Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1785 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001786 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1787 "Invalid constantexpr addrspacecast!");
1788
Jingyue Wubaabe502014-06-15 21:40:57 +00001789 // Canonicalize addrspacecasts between different pointer types by first
1790 // bitcasting the pointer type and then converting the address space.
1791 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1792 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1793 Type *DstElemTy = DstScalarTy->getElementType();
1794 if (SrcScalarTy->getElementType() != DstElemTy) {
1795 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1796 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1797 // Handle vectors of pointers.
1798 MidTy = VectorType::get(MidTy, VT->getNumElements());
1799 }
1800 C = getBitCast(C, MidTy);
1801 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001802 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001803}
1804
Cameron McInallycbde0d92018-11-13 18:15:47 +00001805Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1806 Type *OnlyIfReducedTy) {
1807 // Check the operands for consistency first.
1808 assert(Instruction::isUnaryOp(Opcode) &&
1809 "Invalid opcode in unary constant expression");
1810
1811#ifndef NDEBUG
1812 switch (Opcode) {
1813 case Instruction::FNeg:
1814 assert(C->getType()->isFPOrFPVectorTy() &&
1815 "Tried to create a floating-point operation on a "
1816 "non-floating-point type!");
1817 break;
1818 default:
1819 break;
1820 }
1821#endif
1822
1823 // TODO: Try to constant fold operation.
1824
1825 if (OnlyIfReducedTy == C->getType())
1826 return nullptr;
1827
1828 Constant *ArgVec[] = { C };
1829 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1830
1831 LLVMContextImpl *pImpl = C->getContext().pImpl;
1832 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1833}
1834
Chris Lattner887ecac2011-07-09 18:23:52 +00001835Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001836 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001837 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001838 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001839 "Invalid opcode in binary constant expression");
1840 assert(C1->getType() == C2->getType() &&
1841 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001842
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001843#ifndef NDEBUG
1844 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001845 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001846 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001847 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001848 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001849 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001850 "Tried to create an integer operation on a non-integer type!");
1851 break;
1852 case Instruction::FAdd:
1853 case Instruction::FSub:
1854 case Instruction::FMul:
1855 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001856 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001857 "Tried to create a floating-point operation on a "
1858 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001859 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001860 case Instruction::UDiv:
1861 case Instruction::SDiv:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001862 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001863 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001864 "Tried to create an arithmetic operation on a non-arithmetic type!");
1865 break;
1866 case Instruction::FDiv:
1867 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001868 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001869 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001870 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001871 case Instruction::URem:
1872 case Instruction::SRem:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001873 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001874 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001875 "Tried to create an arithmetic operation on a non-arithmetic type!");
1876 break;
1877 case Instruction::FRem:
1878 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001879 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001880 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001881 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001882 case Instruction::And:
1883 case Instruction::Or:
1884 case Instruction::Xor:
1885 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001886 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001887 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001888 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001889 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001890 case Instruction::LShr:
1891 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001892 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001893 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001894 "Tried to create a shift operation on a non-integer type!");
1895 break;
1896 default:
1897 break;
1898 }
1899#endif
1900
Chris Lattner887ecac2011-07-09 18:23:52 +00001901 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1902 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001903
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001904 if (OnlyIfReducedTy == C1->getType())
1905 return nullptr;
1906
Benjamin Kramer324322b2013-03-07 20:53:34 +00001907 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001908 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001909
Chris Lattner887ecac2011-07-09 18:23:52 +00001910 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1911 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001912}
1913
Chris Lattner229907c2011-07-18 04:54:35 +00001914Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001915 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1916 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001917 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001918 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001919 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001920 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001921 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001922}
1923
Chris Lattner229907c2011-07-18 04:54:35 +00001924Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001925 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001926 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001927 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001928 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001929 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001930 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001931 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001932 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001933 return getPtrToInt(GEP,
1934 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001935}
1936
Chris Lattner229907c2011-07-18 04:54:35 +00001937Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001938 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1939 FieldNo));
1940}
1941
Chris Lattner229907c2011-07-18 04:54:35 +00001942Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001943 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1944 // Note that a non-inbounds gep is used, as null isn't within any object.
1945 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001946 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1947 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001948 };
1949 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001950 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001951 return getPtrToInt(GEP,
1952 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001953}
Owen Anderson487375e2009-07-29 18:55:55 +00001954
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001955Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1956 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001957 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001958
Chris Lattner887ecac2011-07-09 18:23:52 +00001959 switch (Predicate) {
1960 default: llvm_unreachable("Invalid CmpInst predicate");
1961 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1962 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1963 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1964 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1965 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1966 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001967 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001968
Chris Lattner887ecac2011-07-09 18:23:52 +00001969 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1970 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1971 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1972 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001973 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001974 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001975}
1976
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001977Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1978 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001979 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001980
Chris Lattner887ecac2011-07-09 18:23:52 +00001981 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1982 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001983
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001984 if (OnlyIfReducedTy == V1->getType())
1985 return nullptr;
1986
Benjamin Kramer324322b2013-03-07 20:53:34 +00001987 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001988 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001989
Chris Lattner887ecac2011-07-09 18:23:52 +00001990 LLVMContextImpl *pImpl = C->getContext().pImpl;
1991 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001992}
1993
David Blaikie4a2e73b2015-04-02 18:55:32 +00001994Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1995 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001996 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001997 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001998 if (!Ty)
1999 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2000 else
James Y Knight62df5ee2019-01-10 16:07:20 +00002001 assert(Ty ==
2002 cast<PointerType>(C->getType()->getScalarType())->getElementType());
David Blaikied9d900c2015-05-07 17:28:58 +00002003
Peter Collingbourned93620b2016-11-10 22:34:55 +00002004 if (Constant *FC =
2005 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00002006 return FC; // Fold a few common cases.
2007
Chris Lattner887ecac2011-07-09 18:23:52 +00002008 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00002009 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2010 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002011 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00002012 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002013
2014 unsigned NumVecElts = 0;
2015 if (C->getType()->isVectorTy())
2016 NumVecElts = C->getType()->getVectorNumElements();
2017 else for (auto Idx : Idxs)
2018 if (Idx->getType()->isVectorTy())
2019 NumVecElts = Idx->getType()->getVectorNumElements();
2020
2021 if (NumVecElts)
2022 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00002023
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002024 if (OnlyIfReducedTy == ReqTy)
2025 return nullptr;
2026
Dan Gohman1b849082009-09-07 23:54:19 +00002027 // Look up the constant in the table first to ensure uniqueness
2028 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002029 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002030 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002031 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002032 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002033 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00002034 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002035
2036 Constant *Idx = cast<Constant>(Idxs[i]);
2037 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2038 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2039 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00002040 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002041
2042 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2043 if (InRangeIndex && *InRangeIndex < 63)
2044 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002045 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002046 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002047
Chris Lattner887ecac2011-07-09 18:23:52 +00002048 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002049 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2050}
2051
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002052Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2053 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002054 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002055 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2056 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002057
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002058 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002059 return FC; // Fold a few common cases...
2060
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002061 if (OnlyIfReduced)
2062 return nullptr;
2063
Reid Spenceree3c9912006-12-04 05:19:50 +00002064 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002065 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002066 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002067 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002068
Chris Lattner229907c2011-07-18 04:54:35 +00002069 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2070 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002071 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2072
Owen Anderson1584a292009-08-04 20:25:11 +00002073 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002074 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002075}
2076
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002077Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2078 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002079 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002080 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2081 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002082
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002083 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002084 return FC; // Fold a few common cases...
2085
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002086 if (OnlyIfReduced)
2087 return nullptr;
2088
Reid Spenceree3c9912006-12-04 05:19:50 +00002089 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002090 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002091 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002092 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002093
Chris Lattner229907c2011-07-18 04:54:35 +00002094 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2095 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002096 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2097
Owen Anderson1584a292009-08-04 20:25:11 +00002098 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002099 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002100}
2101
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002102Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2103 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002104 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002105 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002106 assert(Idx->getType()->isIntegerTy() &&
2107 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002108
Chris Lattner887ecac2011-07-09 18:23:52 +00002109 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002110 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002111
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002112 Type *ReqTy = Val->getType()->getVectorElementType();
2113 if (OnlyIfReducedTy == ReqTy)
2114 return nullptr;
2115
Robert Bocchinoca27f032006-01-17 20:07:22 +00002116 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002117 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002118 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002119
Chris Lattner887ecac2011-07-09 18:23:52 +00002120 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002121 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002122}
2123
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002124Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2125 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002126 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002127 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002128 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2129 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002130 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002131 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002132
Chris Lattner887ecac2011-07-09 18:23:52 +00002133 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2134 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002135
2136 if (OnlyIfReducedTy == Val->getType())
2137 return nullptr;
2138
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002139 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002140 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002141 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002142
Chris Lattner887ecac2011-07-09 18:23:52 +00002143 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2144 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002145}
2146
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002147Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2148 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002149 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2150 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002151
Chris Lattner887ecac2011-07-09 18:23:52 +00002152 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2153 return FC; // Fold a few common cases.
2154
Chris Lattner8326bd82012-01-26 00:42:34 +00002155 unsigned NElts = Mask->getType()->getVectorNumElements();
2156 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002157 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002158
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002159 if (OnlyIfReducedTy == ShufTy)
2160 return nullptr;
2161
Chris Lattner887ecac2011-07-09 18:23:52 +00002162 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002163 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002164 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002165
Chris Lattner887ecac2011-07-09 18:23:52 +00002166 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2167 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002168}
2169
Chris Lattner887ecac2011-07-09 18:23:52 +00002170Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002171 ArrayRef<unsigned> Idxs,
2172 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002173 assert(Agg->getType()->isFirstClassType() &&
2174 "Non-first-class type for constant insertvalue expression");
2175
Jay Foad57aa6362011-07-13 10:26:04 +00002176 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2177 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002178 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002179 Type *ReqTy = Val->getType();
2180
2181 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2182 return FC;
2183
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002184 if (OnlyIfReducedTy == ReqTy)
2185 return nullptr;
2186
Hal Finkelb31366d2013-07-10 22:51:01 +00002187 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002188 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002189
2190 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2191 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002192}
2193
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002194Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2195 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002196 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002197 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002198
Chris Lattner229907c2011-07-18 04:54:35 +00002199 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002200 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002201 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002202
Dan Gohman0752bff2008-05-23 00:36:11 +00002203 assert(Agg->getType()->isFirstClassType() &&
2204 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002205 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2206 return FC;
2207
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002208 if (OnlyIfReducedTy == ReqTy)
2209 return nullptr;
2210
Hal Finkelb31366d2013-07-10 22:51:01 +00002211 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002212 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002213
2214 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2215 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002216}
2217
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002218Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002219 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002220 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002221 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2222 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002223}
2224
Chris Lattnera676c0f2011-02-07 16:40:21 +00002225Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002226 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002227 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002228 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002229}
2230
Chris Lattnera676c0f2011-02-07 16:40:21 +00002231Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002232 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002233 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002234 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002235}
2236
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002237Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2238 bool HasNUW, bool HasNSW) {
2239 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2240 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2241 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002242}
2243
Chris Lattnera676c0f2011-02-07 16:40:21 +00002244Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002245 return get(Instruction::FAdd, C1, C2);
2246}
2247
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002248Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2249 bool HasNUW, bool HasNSW) {
2250 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2251 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2252 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002253}
2254
Chris Lattnera676c0f2011-02-07 16:40:21 +00002255Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002256 return get(Instruction::FSub, C1, C2);
2257}
2258
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002259Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2260 bool HasNUW, bool HasNSW) {
2261 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2262 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2263 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002264}
2265
Chris Lattnera676c0f2011-02-07 16:40:21 +00002266Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002267 return get(Instruction::FMul, C1, C2);
2268}
2269
Chris Lattner0d75eac2011-02-09 16:43:07 +00002270Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2271 return get(Instruction::UDiv, C1, C2,
2272 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002273}
2274
Chris Lattner0d75eac2011-02-09 16:43:07 +00002275Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2276 return get(Instruction::SDiv, C1, C2,
2277 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002278}
2279
Chris Lattnera676c0f2011-02-07 16:40:21 +00002280Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002281 return get(Instruction::FDiv, C1, C2);
2282}
2283
Chris Lattnera676c0f2011-02-07 16:40:21 +00002284Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002285 return get(Instruction::URem, C1, C2);
2286}
2287
Chris Lattnera676c0f2011-02-07 16:40:21 +00002288Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002289 return get(Instruction::SRem, C1, C2);
2290}
2291
Chris Lattnera676c0f2011-02-07 16:40:21 +00002292Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002293 return get(Instruction::FRem, C1, C2);
2294}
2295
Chris Lattnera676c0f2011-02-07 16:40:21 +00002296Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002297 return get(Instruction::And, C1, C2);
2298}
2299
Chris Lattnera676c0f2011-02-07 16:40:21 +00002300Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002301 return get(Instruction::Or, C1, C2);
2302}
2303
Chris Lattnera676c0f2011-02-07 16:40:21 +00002304Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002305 return get(Instruction::Xor, C1, C2);
2306}
2307
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002308Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2309 bool HasNUW, bool HasNSW) {
2310 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2311 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2312 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002313}
2314
Chris Lattner0d75eac2011-02-09 16:43:07 +00002315Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2316 return get(Instruction::LShr, C1, C2,
2317 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002318}
2319
Chris Lattner0d75eac2011-02-09 16:43:07 +00002320Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2321 return get(Instruction::AShr, C1, C2,
2322 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002323}
2324
Sanjay Patele85a3002018-07-06 15:18:58 +00002325Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2326 bool AllowRHSConstant) {
2327 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2328
2329 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2330 if (Instruction::isCommutative(Opcode)) {
2331 switch (Opcode) {
2332 case Instruction::Add: // X + 0 = X
2333 case Instruction::Or: // X | 0 = X
2334 case Instruction::Xor: // X ^ 0 = X
2335 return Constant::getNullValue(Ty);
2336 case Instruction::Mul: // X * 1 = X
2337 return ConstantInt::get(Ty, 1);
2338 case Instruction::And: // X & -1 = X
2339 return Constant::getAllOnesValue(Ty);
2340 case Instruction::FAdd: // X + -0.0 = X
2341 // TODO: If the fadd has 'nsz', should we return +0.0?
2342 return ConstantFP::getNegativeZero(Ty);
2343 case Instruction::FMul: // X * 1.0 = X
2344 return ConstantFP::get(Ty, 1.0);
2345 default:
2346 llvm_unreachable("Every commutative binop has an identity constant");
2347 }
2348 }
2349
2350 // Non-commutative opcodes: AllowRHSConstant must be set.
2351 if (!AllowRHSConstant)
Craig Topperc6207612014-04-09 06:08:46 +00002352 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002353
Sanjay Patele85a3002018-07-06 15:18:58 +00002354 switch (Opcode) {
2355 case Instruction::Sub: // X - 0 = X
2356 case Instruction::Shl: // X << 0 = X
2357 case Instruction::LShr: // X >>u 0 = X
2358 case Instruction::AShr: // X >> 0 = X
2359 case Instruction::FSub: // X - 0.0 = X
2360 return Constant::getNullValue(Ty);
2361 case Instruction::SDiv: // X / 1 = X
2362 case Instruction::UDiv: // X /u 1 = X
2363 return ConstantInt::get(Ty, 1);
2364 case Instruction::FDiv: // X / 1.0 = X
2365 return ConstantFP::get(Ty, 1.0);
2366 default:
2367 return nullptr;
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002368 }
2369}
2370
Duncan Sands318a89d2012-06-13 09:42:13 +00002371Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2372 switch (Opcode) {
2373 default:
2374 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002375 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002376
2377 case Instruction::Or:
2378 return Constant::getAllOnesValue(Ty);
2379
2380 case Instruction::And:
2381 case Instruction::Mul:
2382 return Constant::getNullValue(Ty);
2383 }
2384}
2385
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002386/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002387void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002388 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002389}
2390
Chris Lattner3cd8c562002-07-30 18:54:25 +00002391const char *ConstantExpr::getOpcodeName() const {
2392 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002393}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002394
David Blaikie60310f22015-05-08 00:42:26 +00002395GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2396 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2397 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2398 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2399 (IdxList.size() + 1),
2400 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002401 SrcElementTy(SrcElementTy),
2402 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002403 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002404 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002405 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2406 OperandList[i+1] = IdxList[i];
2407}
2408
David Blaikie60310f22015-05-08 00:42:26 +00002409Type *GetElementPtrConstantExpr::getSourceElementType() const {
2410 return SrcElementTy;
2411}
2412
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002413Type *GetElementPtrConstantExpr::getResultElementType() const {
2414 return ResElementTy;
2415}
2416
Chris Lattner3756b912012-01-23 22:57:10 +00002417//===----------------------------------------------------------------------===//
2418// ConstantData* implementations
2419
Chris Lattnere4f3f102012-01-24 04:43:41 +00002420Type *ConstantDataSequential::getElementType() const {
2421 return getType()->getElementType();
2422}
2423
Chris Lattner5d4497b2012-01-24 09:31:43 +00002424StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002425 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002426}
2427
Craig Toppere3dcce92015-08-01 22:20:21 +00002428bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002429 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002430 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002431 switch (IT->getBitWidth()) {
2432 case 8:
2433 case 16:
2434 case 32:
2435 case 64:
2436 return true;
2437 default: break;
2438 }
2439 }
2440 return false;
2441}
2442
Chris Lattner00245f42012-01-24 13:41:11 +00002443unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002444 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2445 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002446 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002447}
2448
2449
Chris Lattnere4f3f102012-01-24 04:43:41 +00002450uint64_t ConstantDataSequential::getElementByteSize() const {
2451 return getElementType()->getPrimitiveSizeInBits()/8;
2452}
2453
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002454/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002455const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002456 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002457 return DataElements+Elt*getElementByteSize();
2458}
2459
2460
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002461/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002462static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002463 for (char I : Arr)
2464 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002465 return false;
2466 return true;
2467}
Chris Lattner030af792012-01-24 05:42:11 +00002468
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002469/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002470/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002471/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002472/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2473Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002474 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002475 // If the elements are all zero or there are no elements, return a CAZ, which
2476 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002477 if (isAllZeros(Elements))
2478 return ConstantAggregateZero::get(Ty);
2479
2480 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002481 auto &Slot =
2482 *Ty->getContext()
2483 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2484 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002485
Chris Lattner3756b912012-01-23 22:57:10 +00002486 // The bucket can point to a linked list of different CDS's that have the same
2487 // body but different types. For example, 0,0,0,1 could be a 4 element array
2488 // of i8, or a 1-element array of i32. They'll both end up in the same
2489 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002490 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002491 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002492 Entry = &Node->Next, Node = *Entry)
2493 if (Node->getType() == Ty)
2494 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002495
Chris Lattner3756b912012-01-23 22:57:10 +00002496 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2497 // and return it.
2498 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002499 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002500
2501 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002502 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002503}
2504
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002505void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002506 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002507 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002508 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002509
Chris Lattner3756b912012-01-23 22:57:10 +00002510 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002511 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002512
2513 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2514
2515 ConstantDataSequential **Entry = &Slot->getValue();
2516
2517 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002518 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002519 // If there is only one value in the bucket (common case) it must be this
2520 // entry, and removing the entry should remove the bucket completely.
2521 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2522 getContext().pImpl->CDSConstants.erase(Slot);
2523 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002524 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002525 // node we care about but keep the bucket around.
2526 for (ConstantDataSequential *Node = *Entry; ;
2527 Entry = &Node->Next, Node = *Entry) {
2528 assert(Node && "Didn't find entry in its uniquing hash table!");
2529 // If we found our entry, unlink it from the list and we're done.
2530 if (Node == this) {
2531 *Entry = Node->Next;
2532 break;
2533 }
2534 }
2535 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002536
Chris Lattner3756b912012-01-23 22:57:10 +00002537 // If we were part of a list, make sure that we don't delete the list that is
2538 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002539 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002540}
2541
Rafael Espindola8c97e192015-02-19 16:08:20 +00002542/// getFP() constructors - Return a constant with array type with an element
2543/// count and element type of float with precision matching the number of
2544/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2545/// double for 64bits) Note that this can return a ConstantAggregateZero
2546/// object.
2547Constant *ConstantDataArray::getFP(LLVMContext &Context,
2548 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002549 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002550 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002551 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002552}
2553Constant *ConstantDataArray::getFP(LLVMContext &Context,
2554 ArrayRef<uint32_t> Elts) {
2555 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2556 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002557 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002558}
2559Constant *ConstantDataArray::getFP(LLVMContext &Context,
2560 ArrayRef<uint64_t> Elts) {
2561 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2562 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002563 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002564}
2565
Chris Lattner20683932012-01-24 14:04:40 +00002566Constant *ConstantDataArray::getString(LLVMContext &Context,
2567 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002568 if (!AddNull) {
2569 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper393ce692017-07-11 15:52:21 +00002570 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002571 }
2572
Chris Lattner20683932012-01-24 14:04:40 +00002573 SmallVector<uint8_t, 64> ElementVals;
2574 ElementVals.append(Str.begin(), Str.end());
2575 ElementVals.push_back(0);
2576 return get(Context, ElementVals);
2577}
Chris Lattner3756b912012-01-23 22:57:10 +00002578
2579/// get() constructors - Return a constant with vector type with an element
2580/// count and element type matching the ArrayRef passed in. Note that this
2581/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002582Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002583 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002584 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002585 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002586}
Chris Lattner20683932012-01-24 14:04:40 +00002587Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002588 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002589 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002590 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002591}
Chris Lattner20683932012-01-24 14:04:40 +00002592Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002593 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002594 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002595 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002596}
Chris Lattner20683932012-01-24 14:04:40 +00002597Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002598 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002599 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002600 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002601}
Chris Lattner20683932012-01-24 14:04:40 +00002602Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002603 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002604 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002605 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002606}
Chris Lattner20683932012-01-24 14:04:40 +00002607Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002608 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002609 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002610 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002611}
2612
2613/// getFP() constructors - Return a constant with vector type with an element
2614/// count and element type of float with the precision matching the number of
2615/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2616/// double for 64bits) Note that this can return a ConstantAggregateZero
2617/// object.
2618Constant *ConstantDataVector::getFP(LLVMContext &Context,
2619 ArrayRef<uint16_t> Elts) {
2620 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2621 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002622 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002623}
2624Constant *ConstantDataVector::getFP(LLVMContext &Context,
2625 ArrayRef<uint32_t> Elts) {
2626 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2627 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002628 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002629}
2630Constant *ConstantDataVector::getFP(LLVMContext &Context,
2631 ArrayRef<uint64_t> Elts) {
2632 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2633 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002634 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002635}
2636
Chris Lattnere9eed292012-01-25 05:19:54 +00002637Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2638 assert(isElementTypeCompatible(V->getType()) &&
2639 "Element type not compatible with ConstantData");
2640 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2641 if (CI->getType()->isIntegerTy(8)) {
2642 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2643 return get(V->getContext(), Elts);
2644 }
2645 if (CI->getType()->isIntegerTy(16)) {
2646 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2647 return get(V->getContext(), Elts);
2648 }
2649 if (CI->getType()->isIntegerTy(32)) {
2650 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2651 return get(V->getContext(), Elts);
2652 }
2653 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2654 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2655 return get(V->getContext(), Elts);
2656 }
2657
Chris Lattner978fe0c2012-01-30 06:21:21 +00002658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002659 if (CFP->getType()->isHalfTy()) {
2660 SmallVector<uint16_t, 16> Elts(
2661 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2662 return getFP(V->getContext(), Elts);
2663 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002664 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002665 SmallVector<uint32_t, 16> Elts(
2666 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2667 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002668 }
2669 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002670 SmallVector<uint64_t, 16> Elts(
2671 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2672 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002673 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002674 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002675 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002676}
2677
2678
Chris Lattnere4f3f102012-01-24 04:43:41 +00002679uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2680 assert(isa<IntegerType>(getElementType()) &&
2681 "Accessor can only be used when element is an integer");
2682 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002683
Chris Lattnere4f3f102012-01-24 04:43:41 +00002684 // The data is stored in host byte order, make sure to cast back to the right
2685 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002686 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002687 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002688 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002689 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002690 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002691 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002692 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002693 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002694 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002695 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002696 }
2697}
2698
Craig Topper0b4b4e32017-07-15 22:06:19 +00002699APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2700 assert(isa<IntegerType>(getElementType()) &&
2701 "Accessor can only be used when element is an integer");
2702 const char *EltPtr = getElementPointer(Elt);
2703
2704 // The data is stored in host byte order, make sure to cast back to the right
2705 // type to load with the right endianness.
2706 switch (getElementType()->getIntegerBitWidth()) {
2707 default: llvm_unreachable("Invalid bitwidth for CDS");
2708 case 8: {
2709 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2710 return APInt(8, EltVal);
2711 }
2712 case 16: {
2713 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2714 return APInt(16, EltVal);
2715 }
2716 case 32: {
2717 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2718 return APInt(32, EltVal);
2719 }
2720 case 64: {
2721 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2722 return APInt(64, EltVal);
2723 }
2724 }
2725}
2726
Chris Lattnere4f3f102012-01-24 04:43:41 +00002727APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2728 const char *EltPtr = getElementPointer(Elt);
2729
2730 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002731 default:
Craig Topperc514b542012-02-05 22:14:15 +00002732 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002733 case Type::HalfTyID: {
2734 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002735 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002736 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002737 case Type::FloatTyID: {
2738 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002739 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002740 }
2741 case Type::DoubleTyID: {
2742 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002743 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002744 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002745 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002746}
2747
Chris Lattnere4f3f102012-01-24 04:43:41 +00002748float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2749 assert(getElementType()->isFloatTy() &&
2750 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002751 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002752}
2753
Chris Lattnere4f3f102012-01-24 04:43:41 +00002754double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2755 assert(getElementType()->isDoubleTy() &&
2756 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002757 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002758}
2759
Chris Lattnere4f3f102012-01-24 04:43:41 +00002760Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002761 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2762 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002763 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002764
Chris Lattnere4f3f102012-01-24 04:43:41 +00002765 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2766}
2767
Matthias Braun50ec0b52017-05-19 22:37:09 +00002768bool ConstantDataSequential::isString(unsigned CharSize) const {
2769 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002770}
Chris Lattner3756b912012-01-23 22:57:10 +00002771
Chris Lattner5dd4d872012-01-24 09:01:07 +00002772bool ConstantDataSequential::isCString() const {
2773 if (!isString())
2774 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002775
Chris Lattner5dd4d872012-01-24 09:01:07 +00002776 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002777
Chris Lattner5dd4d872012-01-24 09:01:07 +00002778 // The last value must be nul.
2779 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002780
Chris Lattner5dd4d872012-01-24 09:01:07 +00002781 // Other elements must be non-nul.
2782 return Str.drop_back().find(0) == StringRef::npos;
2783}
Chris Lattner3756b912012-01-23 22:57:10 +00002784
Craig Topper0b4b4e32017-07-15 22:06:19 +00002785bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002786 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002787
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002788 // Compare elements 1+ to the 0'th element.
2789 unsigned EltSize = getElementByteSize();
2790 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2791 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002792 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002793
Craig Topper0b4b4e32017-07-15 22:06:19 +00002794 return true;
2795}
2796
2797Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002798 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002799 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002800}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002801
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002802//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002803// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002804
Pete Cooper5815b1f2015-06-24 18:55:24 +00002805/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002806/// 'From' to be uses of 'To'. This must update the uniquing data structures
2807/// etc.
2808///
2809/// Note that we intentionally replace all uses of From with To here. Consider
2810/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002811/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002812/// single invocation handles all 1000 uses. Handling them one at a time would
2813/// work, but would be really slow because it would have to unique each updated
2814/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002815///
Mehdi Amini8914d292016-02-10 22:47:15 +00002816void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002817 Value *Replacement = nullptr;
2818 switch (getValueID()) {
2819 default:
2820 llvm_unreachable("Not a constant!");
2821#define HANDLE_CONSTANT(Name) \
2822 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002823 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002824 break;
2825#include "llvm/IR/Value.def"
2826 }
2827
2828 // If handleOperandChangeImpl returned nullptr, then it handled
2829 // replacing itself and we don't want to delete or replace anything else here.
2830 if (!Replacement)
2831 return;
2832
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002833 // I do need to replace this with an existing value.
2834 assert(Replacement != this && "I didn't contain From!");
2835
2836 // Everyone using this now uses the replacement.
2837 replaceAllUsesWith(Replacement);
2838
2839 // Delete the old constant!
2840 destroyConstant();
2841}
2842
Mehdi Amini8914d292016-02-10 22:47:15 +00002843Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002844 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2845 Constant *ToC = cast<Constant>(To);
2846
Talin46e9b442012-02-05 20:54:10 +00002847 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002848 Values.reserve(getNumOperands()); // Build replacement array.
2849
Galina Kistanovafc259902012-07-13 01:25:27 +00002850 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002851 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002852 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002853
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002854 // Keep track of whether all the values in the array are "ToC".
2855 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002856 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002857 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002858 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2859 Constant *Val = cast<Constant>(O->get());
2860 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002861 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002862 Val = ToC;
2863 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002864 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002865 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002866 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002867 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002868
Pete Cooper5815b1f2015-06-24 18:55:24 +00002869 if (AllSame && ToC->isNullValue())
2870 return ConstantAggregateZero::get(getType());
2871
2872 if (AllSame && isa<UndefValue>(ToC))
2873 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002874
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002875 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002876 if (Constant *C = getImpl(getType(), Values))
2877 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002878
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002879 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002880 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002881 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002882}
2883
Mehdi Amini8914d292016-02-10 22:47:15 +00002884Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002885 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2886 Constant *ToC = cast<Constant>(To);
2887
Pete Cooper74510a42015-06-12 17:48:05 +00002888 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002889
Talin46e9b442012-02-05 20:54:10 +00002890 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002891 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002892
2893 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002894 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002895 unsigned NumUpdated = 0;
2896 bool AllSame = true;
2897 unsigned OperandNo = 0;
2898 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2899 Constant *Val = cast<Constant>(O->get());
2900 if (Val == From) {
2901 OperandNo = (O - OperandList);
2902 Val = ToC;
2903 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002904 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002905 Values.push_back(Val);
2906 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002907 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002908
Mehdi Amini8914d292016-02-10 22:47:15 +00002909 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002910 return ConstantAggregateZero::get(getType());
2911
Mehdi Amini8914d292016-02-10 22:47:15 +00002912 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002913 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002914
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002915 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002916 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002917 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002918}
2919
Mehdi Amini8914d292016-02-10 22:47:15 +00002920Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002921 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002922 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002923
Chris Lattnera474bb22012-01-26 20:40:56 +00002924 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002925 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002926 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002927 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002928 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2929 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002930 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002931 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002932 ++NumUpdated;
2933 Val = ToC;
2934 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002935 Values.push_back(Val);
2936 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002937
Pete Cooper5815b1f2015-06-24 18:55:24 +00002938 if (Constant *C = getImpl(Values))
2939 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002940
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002941 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002942 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002943 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002944}
2945
Mehdi Amini8914d292016-02-10 22:47:15 +00002946Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002947 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2948 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002949
Chris Lattner37e38352012-01-26 20:37:11 +00002950 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002951 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002952 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002953 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2954 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002955 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002956 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002957 ++NumUpdated;
2958 Op = To;
2959 }
2960 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002961 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002962 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002963
Pete Cooper5815b1f2015-06-24 18:55:24 +00002964 if (Constant *C = getWithOperands(NewOps, getType(), true))
2965 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002966
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002967 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002968 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002969 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002970}
2971
James Molloyce545682012-11-17 17:56:30 +00002972Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002973 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002974 ArrayRef<Value*> Ops(ValueOperands);
2975
2976 switch (getOpcode()) {
2977 case Instruction::Trunc:
2978 case Instruction::ZExt:
2979 case Instruction::SExt:
2980 case Instruction::FPTrunc:
2981 case Instruction::FPExt:
2982 case Instruction::UIToFP:
2983 case Instruction::SIToFP:
2984 case Instruction::FPToUI:
2985 case Instruction::FPToSI:
2986 case Instruction::PtrToInt:
2987 case Instruction::IntToPtr:
2988 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002989 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002990 return CastInst::Create((Instruction::CastOps)getOpcode(),
2991 Ops[0], getType());
2992 case Instruction::Select:
2993 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2994 case Instruction::InsertElement:
2995 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2996 case Instruction::ExtractElement:
2997 return ExtractElementInst::Create(Ops[0], Ops[1]);
2998 case Instruction::InsertValue:
2999 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3000 case Instruction::ExtractValue:
3001 return ExtractValueInst::Create(Ops[0], getIndices());
3002 case Instruction::ShuffleVector:
3003 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3004
David Blaikie741c8f82015-03-14 01:53:18 +00003005 case Instruction::GetElementPtr: {
3006 const auto *GO = cast<GEPOperator>(this);
3007 if (GO->isInBounds())
3008 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3009 Ops[0], Ops.slice(1));
3010 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3011 Ops.slice(1));
3012 }
James Molloyce545682012-11-17 17:56:30 +00003013 case Instruction::ICmp:
3014 case Instruction::FCmp:
3015 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00003016 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00003017
3018 default:
3019 assert(getNumOperands() == 2 && "Must be binary operator?");
3020 BinaryOperator *BO =
3021 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3022 Ops[0], Ops[1]);
3023 if (isa<OverflowingBinaryOperator>(BO)) {
3024 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3025 OverflowingBinaryOperator::NoUnsignedWrap);
3026 BO->setHasNoSignedWrap(SubclassOptionalData &
3027 OverflowingBinaryOperator::NoSignedWrap);
3028 }
3029 if (isa<PossiblyExactOperator>(BO))
3030 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3031 return BO;
3032 }
3033}