forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstructions.cpp
4813 lines (4204 loc) · 176 KB
/
Instructions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- Instructions.cpp - Implement the LLVM instructions -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements all of the non-inline methods for the LLVM instruction
// classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Instructions.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TypeSize.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <vector>
using namespace llvm;
static cl::opt<bool> DisableI2pP2iOpt(
"disable-i2p-p2i-opt", cl::init(false),
cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
//===----------------------------------------------------------------------===//
// AllocaInst Class
//===----------------------------------------------------------------------===//
Optional<TypeSize>
AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
if (isArrayAllocation()) {
auto *C = dyn_cast<ConstantInt>(getArraySize());
if (!C)
return None;
assert(!Size.isScalable() && "Array elements cannot have a scalable size");
Size *= C->getZExtValue();
}
return Size;
}
//===----------------------------------------------------------------------===//
// SelectInst Class
//===----------------------------------------------------------------------===//
/// areInvalidOperands - Return a string if the specified operands are invalid
/// for a select operation, otherwise return null.
const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
if (Op1->getType() != Op2->getType())
return "both values to select must have same type";
if (Op1->getType()->isTokenTy())
return "select values cannot have token type";
if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
// Vector select.
if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
return "vector select condition element type must be i1";
VectorType *ET = dyn_cast<VectorType>(Op1->getType());
if (!ET)
return "selected values for vector select must be vectors";
if (ET->getElementCount() != VT->getElementCount())
return "vector select requires selected vectors to have "
"the same vector length as select condition";
} else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
return "select condition must be i1 or <n x i1>";
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// PHINode Class
//===----------------------------------------------------------------------===//
PHINode::PHINode(const PHINode &PN)
: Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
ReservedSpace(PN.getNumOperands()) {
allocHungoffUses(PN.getNumOperands());
std::copy(PN.op_begin(), PN.op_end(), op_begin());
std::copy(PN.block_begin(), PN.block_end(), block_begin());
SubclassOptionalData = PN.SubclassOptionalData;
}
// removeIncomingValue - Remove an incoming value. This is useful if a
// predecessor basic block is deleted.
Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
Value *Removed = getIncomingValue(Idx);
// Move everything after this operand down.
//
// FIXME: we could just swap with the end of the list, then erase. However,
// clients might not expect this to happen. The code as it is thrashes the
// use/def lists, which is kinda lame.
std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
// Nuke the last value.
Op<-1>().set(nullptr);
setNumHungOffUseOperands(getNumOperands() - 1);
// If the PHI node is dead, because it has zero entries, nuke it now.
if (getNumOperands() == 0 && DeletePHIIfEmpty) {
// If anyone is using this PHI, make them use a dummy value instead...
replaceAllUsesWith(UndefValue::get(getType()));
eraseFromParent();
}
return Removed;
}
/// growOperands - grow operands - This grows the operand list in response
/// to a push_back style of operation. This grows the number of ops by 1.5
/// times.
///
void PHINode::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e + e / 2;
if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace, /* IsPhi */ true);
}
/// hasConstantValue - If the specified PHI node always merges together the same
/// value, return the value, otherwise return null.
Value *PHINode::hasConstantValue() const {
// Exploit the fact that phi nodes always have at least one entry.
Value *ConstantValue = getIncomingValue(0);
for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
if (ConstantValue != this)
return nullptr; // Incoming values not all the same.
// The case where the first value is this PHI.
ConstantValue = getIncomingValue(i);
}
if (ConstantValue == this)
return UndefValue::get(getType());
return ConstantValue;
}
/// hasConstantOrUndefValue - Whether the specified PHI node always merges
/// together the same value, assuming that undefs result in the same value as
/// non-undefs.
/// Unlike \ref hasConstantValue, this does not return a value because the
/// unique non-undef incoming value need not dominate the PHI node.
bool PHINode::hasConstantOrUndefValue() const {
Value *ConstantValue = nullptr;
for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
Value *Incoming = getIncomingValue(i);
if (Incoming != this && !isa<UndefValue>(Incoming)) {
if (ConstantValue && ConstantValue != Incoming)
return false;
ConstantValue = Incoming;
}
}
return true;
}
//===----------------------------------------------------------------------===//
// LandingPadInst Implementation
//===----------------------------------------------------------------------===//
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, Instruction *InsertBefore)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(const LandingPadInst &LP)
: Instruction(LP.getType(), Instruction::LandingPad, nullptr,
LP.getNumOperands()),
ReservedSpace(LP.getNumOperands()) {
allocHungoffUses(LP.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = LP.getOperandList();
for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
OL[I] = InOL[I];
setCleanup(LP.isCleanup());
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
Instruction *InsertBefore) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
BasicBlock *InsertAtEnd) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
}
void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
ReservedSpace = NumReservedValues;
setNumHungOffUseOperands(0);
allocHungoffUses(ReservedSpace);
setName(NameStr);
setCleanup(false);
}
/// growOperands - grow operands - This grows the operand list in response to a
/// push_back style of operation. This grows the number of ops by 2 times.
void LandingPadInst::growOperands(unsigned Size) {
unsigned e = getNumOperands();
if (ReservedSpace >= e + Size) return;
ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
growHungoffUses(ReservedSpace);
}
void LandingPadInst::addClause(Constant *Val) {
unsigned OpNo = getNumOperands();
growOperands(1);
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(getNumOperands() + 1);
getOperandList()[OpNo] = Val;
}
//===----------------------------------------------------------------------===//
// CallBase Implementation
//===----------------------------------------------------------------------===//
CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertPt) {
switch (CB->getOpcode()) {
case Instruction::Call:
return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
case Instruction::Invoke:
return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
case Instruction::CallBr:
return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
default:
llvm_unreachable("Unknown CallBase sub-class!");
}
}
CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 2> OpDefs;
for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
auto ChildOB = CI->getOperandBundleAt(i);
if (ChildOB.getTagName() != OpB.getTag())
OpDefs.emplace_back(ChildOB);
}
OpDefs.emplace_back(OpB);
return CallBase::Create(CI, OpDefs, InsertPt);
}
Function *CallBase::getCaller() { return getParent()->getParent(); }
unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
}
bool CallBase::isIndirectCall() const {
const Value *V = getCalledOperand();
if (isa<Function>(V) || isa<Constant>(V))
return false;
return !isInlineAsm();
}
/// Tests if this call site must be tail call optimized. Only a CallInst can
/// be tail call optimized.
bool CallBase::isMustTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isMustTailCall();
return false;
}
/// Tests if this call site is marked as a tail call.
bool CallBase::isTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isTailCall();
return false;
}
Intrinsic::ID CallBase::getIntrinsicID() const {
if (auto *F = getCalledFunction())
return F->getIntrinsicID();
return Intrinsic::not_intrinsic;
}
bool CallBase::isReturnNonNull() const {
if (hasRetAttr(Attribute::NonNull))
return true;
if (getRetDereferenceableBytes() > 0 &&
!NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace()))
return true;
return false;
}
Value *CallBase::getReturnedArgOperand() const {
unsigned Index;
if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
if (const Function *F = getCalledFunction())
if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
return nullptr;
}
/// Determine whether the argument or parameter has the given attribute.
bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
assert(ArgNo < arg_size() && "Param index out of bounds!");
if (Attrs.hasParamAttr(ArgNo, Kind))
return true;
if (const Function *F = getCalledFunction())
return F->getAttributes().hasParamAttr(ArgNo, Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
void CallBase::getOperandBundlesAsDefs(
SmallVectorImpl<OperandBundleDef> &Defs) const {
for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
Defs.emplace_back(getOperandBundleAt(i));
}
CallBase::op_iterator
CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
const unsigned BeginIndex) {
auto It = op_begin() + BeginIndex;
for (auto &B : Bundles)
It = std::copy(B.input_begin(), B.input_end(), It);
auto *ContextImpl = getContext().pImpl;
auto BI = Bundles.begin();
unsigned CurrentIndex = BeginIndex;
for (auto &BOI : bundle_op_infos()) {
assert(BI != Bundles.end() && "Incorrect allocation?");
BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
BOI.Begin = CurrentIndex;
BOI.End = CurrentIndex + BI->input_size();
CurrentIndex = BOI.End;
BI++;
}
assert(BI == Bundles.end() && "Incorrect allocation?");
return It;
}
CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
/// When there isn't many bundles, we do a simple linear search.
/// Else fallback to a binary-search that use the fact that bundles usually
/// have similar number of argument to get faster convergence.
if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
for (auto &BOI : bundle_op_infos())
if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
return BOI;
llvm_unreachable("Did not find operand bundle for operand!");
}
assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
OpIdx < std::prev(bundle_op_info_end())->End &&
"The Idx isn't in the operand bundle");
/// We need a decimal number below and to prevent using floating point numbers
/// we use an intergal value multiplied by this constant.
constexpr unsigned NumberScaling = 1024;
bundle_op_iterator Begin = bundle_op_info_begin();
bundle_op_iterator End = bundle_op_info_end();
bundle_op_iterator Current = Begin;
while (Begin != End) {
unsigned ScaledOperandPerBundle =
NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
ScaledOperandPerBundle);
if (Current >= End)
Current = std::prev(End);
assert(Current < End && Current >= Begin &&
"the operand bundle doesn't cover every value in the range");
if (OpIdx >= Current->Begin && OpIdx < Current->End)
break;
if (OpIdx >= Current->End)
Begin = Current + 1;
else
End = Current;
}
assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
"the operand bundle doesn't cover every value in the range");
return *Current;
}
CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID,
OperandBundleDef OB,
Instruction *InsertPt) {
if (CB->getOperandBundle(ID))
return CB;
SmallVector<OperandBundleDef, 1> Bundles;
CB->getOperandBundlesAsDefs(Bundles);
Bundles.push_back(OB);
return Create(CB, Bundles, InsertPt);
}
CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 1> Bundles;
bool CreateNew = false;
for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
auto Bundle = CB->getOperandBundleAt(I);
if (Bundle.getTagID() == ID) {
CreateNew = true;
continue;
}
Bundles.emplace_back(Bundle);
}
return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
}
bool CallBase::hasReadingOperandBundles() const {
// Implementation note: this is a conservative implementation of operand
// bundle semantics, where *any* non-assume operand bundle forces a callsite
// to be at least readonly.
return hasOperandBundles() && getIntrinsicID() != Intrinsic::assume;
}
//===----------------------------------------------------------------------===//
// CallInst Implementation
//===----------------------------------------------------------------------===//
void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
"NumOperands not set up?");
#ifndef NDEBUG
assert((Args.size() == FTy->getNumParams() ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature!");
for (unsigned i = 0; i != Args.size(); ++i)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
llvm::copy(Args, op_begin());
setCalledOperand(Func);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 1 == op_end() && "Should add up!");
setName(NameStr);
}
void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == 1 && "NumOperands not set up?");
setCalledOperand(Func);
assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
setName(NameStr);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
Instruction *InsertBefore)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
init(Ty, Func, Name);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
BasicBlock *InsertAtEnd)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
init(Ty, Func, Name);
}
CallInst::CallInst(const CallInst &CI)
: CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
CI.getNumOperands()) {
setTailCallKind(CI.getTailCallKind());
setCallingConv(CI.getCallingConv());
std::copy(CI.op_begin(), CI.op_end(), op_begin());
std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CI.SubclassOptionalData;
}
CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
Args, OpB, CI->getName(), InsertPt);
NewCI->setTailCallKind(CI->getTailCallKind());
NewCI->setCallingConv(CI->getCallingConv());
NewCI->SubclassOptionalData = CI->SubclassOptionalData;
NewCI->setAttributes(CI->getAttributes());
NewCI->setDebugLoc(CI->getDebugLoc());
return NewCI;
}
// Update profile weight for call instruction by scaling it using the ratio
// of S/T. The meaning of "branch_weights" meta data for call instruction is
// transfered to represent call count.
void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
auto *ProfileData = getMetadata(LLVMContext::MD_prof);
if (ProfileData == nullptr)
return;
auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
!ProfDataName->getString().equals("VP")))
return;
if (T == 0) {
LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
"div by 0. Ignoring. Likely the function "
<< getParent()->getParent()->getName()
<< " has 0 entry count, and contains call instructions "
"with non-zero prof info.");
return;
}
MDBuilder MDB(getContext());
SmallVector<Metadata *, 3> Vals;
Vals.push_back(ProfileData->getOperand(0));
APInt APS(128, S), APT(128, T);
if (ProfDataName->getString().equals("branch_weights") &&
ProfileData->getNumOperands() > 0) {
// Using APInt::div may be expensive, but most cases should fit 64 bits.
APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
->getValue()
.getZExtValue());
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt32Ty(getContext()),
Val.udiv(APT).getLimitedValue(UINT32_MAX))));
} else if (ProfDataName->getString().equals("VP"))
for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
// The first value is the key of the value profile, which will not change.
Vals.push_back(ProfileData->getOperand(i));
uint64_t Count =
mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
->getValue()
.getZExtValue();
// Don't scale the magic number.
if (Count == NOMORE_ICP_MAGICNUM) {
Vals.push_back(ProfileData->getOperand(i + 1));
continue;
}
// Using APInt::div may be expensive, but most cases should fit 64 bits.
APInt Val(128, Count);
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt64Ty(getContext()),
Val.udiv(APT).getLimitedValue())));
}
setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
}
/// IsConstantOne - Return true only if val is constant int 1
static bool IsConstantOne(Value *val) {
assert(val && "IsConstantOne does not work with nullptr val");
const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
return CVal && CVal->isOne();
}
static Instruction *createMalloc(Instruction *InsertBefore,
BasicBlock *InsertAtEnd, Type *IntPtrTy,
Type *AllocTy, Value *AllocSize,
Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createMalloc needs either InsertBefore or InsertAtEnd");
// malloc(type) becomes:
// bitcast (i8* malloc(typeSize)) to type*
// malloc(type, arraySize) becomes:
// bitcast (i8* malloc(typeSize*arraySize)) to type*
if (!ArraySize)
ArraySize = ConstantInt::get(IntPtrTy, 1);
else if (ArraySize->getType() != IntPtrTy) {
if (InsertBefore)
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertBefore);
else
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertAtEnd);
}
if (!IsConstantOne(ArraySize)) {
if (IsConstantOne(AllocSize)) {
AllocSize = ArraySize; // Operand * 1 = Operand
} else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
false /*ZExt*/);
// Malloc arg is constant product of type size and array size
AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
} else {
// Multiply type size by the array size...
if (InsertBefore)
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertBefore);
else
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertAtEnd);
}
}
assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
// Create the call to Malloc.
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *BPTy = Type::getInt8PtrTy(BB->getContext());
FunctionCallee MallocFunc = MallocF;
if (!MallocFunc)
// prototype malloc as "void *malloc(size_t)"
MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
CallInst *MCall = nullptr;
Instruction *Result = nullptr;
if (InsertBefore) {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
InsertBefore);
Result = MCall;
if (Result->getType() != AllocPtrType)
// Create a cast instruction to convert to the right type...
Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
} else {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
Result = MCall;
if (Result->getType() != AllocPtrType) {
InsertAtEnd->getInstList().push_back(MCall);
// Create a cast instruction to convert to the right type...
Result = new BitCastInst(MCall, AllocPtrType, Name);
}
}
MCall->setTailCall();
if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
MCall->setCallingConv(F->getCallingConv());
if (!F->returnDoesNotAlias())
F->setReturnDoesNotAlias();
}
assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
return Result;
}
/// CreateMalloc - Generate the IR for a call to malloc:
/// 1. Compute the malloc call's argument as the specified type's size,
/// possibly multiplied by the array size if the array size is not
/// constant 1.
/// 2. Call malloc with that argument.
/// 3. Bitcast the result of the malloc call to the specified type.
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
/// CreateMalloc - Generate the IR for a call to malloc:
/// 1. Compute the malloc call's argument as the specified type's size,
/// possibly multiplied by the array size if the array size is not
/// constant 1.
/// 2. Call malloc with that argument.
/// 3. Bitcast the result of the malloc call to the specified type.
/// Note: This function does not add the bitcast to the basic block, that is the
/// responsibility of the caller.
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
static Instruction *createFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore,
BasicBlock *InsertAtEnd) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createFree needs either InsertBefore or InsertAtEnd");
assert(Source->getType()->isPointerTy() &&
"Can not free something of nonpointer type!");
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *VoidTy = Type::getVoidTy(M->getContext());
Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
// prototype free as "void free(void*)"
FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
CallInst *Result = nullptr;
Value *PtrCast = Source;
if (InsertBefore) {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
} else {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
}
Result->setTailCall();
if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
Result->setCallingConv(F->getCallingConv());
return Result;
}
/// CreateFree - Generate the IR for a call to the builtin free function.
Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
return createFree(Source, None, InsertBefore, nullptr);
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore) {
return createFree(Source, Bundles, InsertBefore, nullptr);
}
/// CreateFree - Generate the IR for a call to the builtin free function.
/// Note: This function does not add the call to the basic block, that is the
/// responsibility of the caller.
Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
//===----------------------------------------------------------------------===//
// InvokeInst Implementation
//===----------------------------------------------------------------------===//
void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
BasicBlock *IfException, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Invoking a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Invoking a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
llvm::copy(Args, op_begin());
setNormalDest(IfNormal);
setUnwindDest(IfException);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 3 == op_end() && "Should add up!");
setName(NameStr);
}
InvokeInst::InvokeInst(const InvokeInst &II)
: CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
II.getNumOperands()) {
setCallingConv(II.getCallingConv());
std::copy(II.op_begin(), II.op_end(), op_begin());
std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = II.SubclassOptionalData;
}
InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(II->arg_begin(), II->arg_end());
auto *NewII = InvokeInst::Create(
II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
NewII->setCallingConv(II->getCallingConv());
NewII->SubclassOptionalData = II->SubclassOptionalData;
NewII->setAttributes(II->getAttributes());
NewII->setDebugLoc(II->getDebugLoc());
return NewII;
}
LandingPadInst *InvokeInst::getLandingPadInst() const {
return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
}
//===----------------------------------------------------------------------===//
// CallBrInst Implementation
//===----------------------------------------------------------------------===//
void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
ArrayRef<BasicBlock *> IndirectDests,
ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), IndirectDests.size(),
CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
std::copy(Args.begin(), Args.end(), op_begin());
NumIndirectDests = IndirectDests.size();
setDefaultDest(Fallthrough);
for (unsigned i = 0; i != NumIndirectDests; ++i)
setIndirectDest(i, IndirectDests[i]);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
setName(NameStr);
}
void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
if (BasicBlock *OldBB = getIndirectDest(i)) {
BlockAddress *Old = BlockAddress::get(OldBB);
BlockAddress *New = BlockAddress::get(B);
for (unsigned ArgNo = 0, e = arg_size(); ArgNo != e; ++ArgNo)
if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
setArgOperand(ArgNo, New);
}
}
CallBrInst::CallBrInst(const CallBrInst &CBI)
: CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
CBI.getNumOperands()) {
setCallingConv(CBI.getCallingConv());
std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CBI.SubclassOptionalData;
NumIndirectDests = CBI.NumIndirectDests;
}
CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
auto *NewCBI = CallBrInst::Create(
CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
NewCBI->setCallingConv(CBI->getCallingConv());
NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
NewCBI->setAttributes(CBI->getAttributes());
NewCBI->setDebugLoc(CBI->getDebugLoc());
NewCBI->NumIndirectDests = CBI->NumIndirectDests;
return NewCBI;
}
//===----------------------------------------------------------------------===//
// ReturnInst Implementation
//===----------------------------------------------------------------------===//
ReturnInst::ReturnInst(const ReturnInst &RI)
: Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
RI.getNumOperands()) {
if (RI.getNumOperands())
Op<0>() = RI.Op<0>();
SubclassOptionalData = RI.SubclassOptionalData;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(C), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
InsertBefore) {
if (retVal)
Op<0>() = retVal;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)