forked from checkedc/checkedc-clang
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathConstraintVariables.cpp
More file actions
1726 lines (1549 loc) · 56.9 KB
/
ConstraintVariables.cpp
File metadata and controls
1726 lines (1549 loc) · 56.9 KB
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
//=--ConstraintVariables.cpp--------------------------------------*- C++-*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Implementation of ConstraintVariables methods.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringSwitch.h"
#include "clang/Lex/Lexer.h"
#include <sstream>
#include "clang/CConv/ConstraintVariables.h"
#include "clang/CConv/ProgramInfo.h"
#include "clang/CConv/CCGlobalOptions.h"
using namespace clang;
std::string ConstraintVariable::getRewritableOriginalTy() const {
std::string OrigTyString = getOriginalTy();
std::string SpaceStr = " ";
std::string AsterixStr = "*";
// If the type does not end with " " or *
// we need to add space.
if (!std::equal(SpaceStr.rbegin(), SpaceStr.rend(), OrigTyString.rbegin()) &&
!std::equal(AsterixStr.rbegin(), AsterixStr.rend(),
OrigTyString.rbegin())) {
OrigTyString += " ";
}
return OrigTyString;
}
bool ConstraintVariable::isChecked(const EnvironmentMap &E) const {
return getIsOriginallyChecked() || anyChanges(E);
}
PointerVariableConstraint *
PointerVariableConstraint::getWildPVConstraint(Constraints &CS) {
static PointerVariableConstraint *GlobalWildPV = nullptr;
if (GlobalWildPV == nullptr) {
CAtoms NewVA;
NewVA.push_back(CS.getWild());
GlobalWildPV =
new PVConstraint(NewVA, "unsigned", "wildvar", nullptr,
false, false, "");
}
return GlobalWildPV;
}
PointerVariableConstraint *
PointerVariableConstraint::getPtrPVConstraint(Constraints &CS) {
static PointerVariableConstraint *GlobalPtrPV = nullptr;
if (GlobalPtrPV == nullptr) {
CAtoms NewVA;
NewVA.push_back(CS.getPtr());
GlobalPtrPV =
new PVConstraint(NewVA, "unsigned", "ptrvar", nullptr,
false, false, "");
}
return GlobalPtrPV;
}
PointerVariableConstraint *
PointerVariableConstraint::getNonPtrPVConstraint(Constraints &CS) {
static PointerVariableConstraint *GlobalNonPtrPV = nullptr;
if (GlobalNonPtrPV == nullptr) {
CAtoms NewVA; // empty -- represents a base type
GlobalNonPtrPV =
new PVConstraint(NewVA, "unsigned", "basevar", nullptr,
false, false, "");
}
return GlobalNonPtrPV;
}
PointerVariableConstraint *
PointerVariableConstraint::getNamedNonPtrPVConstraint(StringRef name,
Constraints &CS) {
CAtoms NewVA; // empty -- represents a base type
return new PVConstraint(NewVA, "unsigned", name, nullptr,
false, false, "");
}
PointerVariableConstraint::
PointerVariableConstraint(PointerVariableConstraint *Ot,
Constraints &CS) :
ConstraintVariable(ConstraintVariable::PointerVariable,
Ot->BaseType, Ot->Name),
FV(nullptr), partOFFuncPrototype(Ot->partOFFuncPrototype) {
this->arrSizes = Ot->arrSizes;
this->ArrPresent = Ot->ArrPresent;
this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints;
this->ValidBoundsKey = Ot->ValidBoundsKey;
this->BKey = Ot->BKey;
// Make copy of the vars only for VarAtoms.
for (auto *CV : Ot->vars) {
if (ConstAtom *CA = dyn_cast<ConstAtom>(CV)) {
this->vars.push_back(CA);
}
if (VarAtom *VA = dyn_cast<VarAtom>(CV)) {
this->vars.push_back(CS.getFreshVar(VA->getName(), VA->getVarKind()));
}
}
if (Ot->FV != nullptr) {
this->FV = dyn_cast<FVConstraint>(Ot->FV->getCopy(CS));
}
this->Parent = Ot;
this->IsGeneric = Ot->IsGeneric;
this->IsZeroWidthArray = Ot->IsZeroWidthArray;
this->OriginallyChecked = Ot->OriginallyChecked;
// We need not initialize other members.
}
PointerVariableConstraint::PointerVariableConstraint(DeclaratorDecl *D,
ProgramInfo &I,
const ASTContext &C) :
PointerVariableConstraint(D->getType(), D, D->getName(),
I, C) { }
PointerVariableConstraint::PointerVariableConstraint(const QualType &QT,
DeclaratorDecl *D,
std::string N,
ProgramInfo &I,
const ASTContext &C,
std::string *inFunc,
bool Generic) :
ConstraintVariable(ConstraintVariable::PointerVariable,
tyToStr(QT.getTypePtr()),N), FV(nullptr),
partOFFuncPrototype(inFunc != nullptr), Parent(nullptr),
IsGeneric(Generic)
{
QualType QTy = QT;
const Type *Ty = QTy.getTypePtr();
auto &CS = I.getConstraints();
// If the type is a decayed type, then maybe this is the result of
// decaying an array to a pointer. If the original type is some
// kind of array type, we want to use that instead.
if (const DecayedType *DC = dyn_cast<DecayedType>(Ty)) {
QualType QTytmp = DC->getOriginalType();
if (QTytmp->isArrayType() || QTytmp->isIncompleteArrayType()) {
QTy = QTytmp;
Ty = QTy.getTypePtr();
}
}
bool IsTypedef = false;
if (Ty->getAs<TypedefType>())
IsTypedef = true;
ArrPresent = false;
bool IsDeclTy = false;
auto &ABInfo = I.getABoundsInfo();
if (D != nullptr) {
if (ABInfo.tryGetVariable(D, BKey)) {
ValidBoundsKey = true;
}
if (D->hasBoundsAnnotations()) {
BoundsAnnotations BA = D->getBoundsAnnotations();
BoundsExpr *BExpr = BA.getBoundsExpr();
if (BExpr != nullptr) {
SourceRange R = BExpr->getSourceRange();
if (R.isValid()) {
BoundsAnnotationStr = getSourceText(R, C);
}
if (D->hasBoundsAnnotations() && ABInfo.isValidBoundVariable(D)) {
assert(ABInfo.tryGetVariable(D, BKey) &&
"Is expected to have valid Bounds key");
ABounds *NewB = ABounds::getBoundsInfo(&ABInfo, BExpr, C);
ABInfo.insertDeclaredBounds(D, NewB);
}
}
}
IsDeclTy = D->getType() == QT; // If false, then QT may be D's return type
if (InteropTypeExpr *ITE = D->getInteropTypeExpr()) {
// External variables can also have itype.
// Check if the provided declaration is an external
// variable.
// For functions, check to see that if we are analyzing
// function return types.
bool AnalyzeITypeExpr = IsDeclTy;
if (!AnalyzeITypeExpr) {
const Type *OrigType = Ty;
if (isa<FunctionDecl>(D)) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
OrigType = FD->getType().getTypePtr();
}
if (OrigType->isFunctionProtoType()) {
const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(OrigType);
AnalyzeITypeExpr = (FPT->getReturnType() == QT);
}
}
if (AnalyzeITypeExpr) {
QualType InteropType = ITE->getTypeAsWritten();
QTy = InteropType;
Ty = QTy.getTypePtr();
SourceRange R = ITE->getSourceRange();
if (R.isValid()) {
ItypeStr = getSourceText(R, C);
assert(ItypeStr.size() > 0);
}
}
}
}
bool VarCreated = false;
bool IsArr = false;
bool IsIncompleteArr = false;
bool IsTopMost = true;
OriginallyChecked = false;
uint32_t TypeIdx = 0;
std::string Npre = inFunc ? ((*inFunc)+":") : "";
VarAtom::VarKind VK =
inFunc ? (N == RETVAR ? VarAtom::V_Return : VarAtom::V_Param)
: VarAtom::V_Other;
while (Ty->isPointerType() || Ty->isArrayType()) {
// Is this a VarArg type?
std::string TyName = tyToStr(Ty);
if (isVarArgType(TyName)) {
// Variable number of arguments. Make it WILD.
vars.push_back(CS.getWild());
VarCreated = true;
break;
}
if (Ty->isCheckedPointerType()) {
OriginallyChecked = true;
ConstAtom *CAtom = nullptr;
if (Ty->isCheckedPointerNtArrayType()) {
// This is an NT array type.
CAtom = CS.getNTArr();
} else if (Ty->isCheckedPointerArrayType()) {
// This is an array type.
CAtom = CS.getArr();
} else if (Ty->isCheckedPointerPtrType()) {
// This is a regular checked pointer.
CAtom = CS.getPtr();
}
VarCreated = true;
assert(CAtom != nullptr && "Unable to find the type "
"of the checked pointer.");
vars.push_back(CAtom);
}
if (Ty->isArrayType() || Ty->isIncompleteArrayType()) {
ArrPresent = IsArr = true;
IsIncompleteArr = Ty->isIncompleteArrayType();
// Boil off the typedefs in the array case.
// TODO this will need to change to properly account for typedefs
bool boiling = true;
while (boiling) {
if (const TypedefType *TydTy = dyn_cast<TypedefType>(Ty)) {
QTy = TydTy->desugar();
Ty = QTy.getTypePtr();
} else if (const ParenType *ParenTy = dyn_cast<ParenType>(Ty)) {
QTy = ParenTy->desugar();
Ty = QTy.getTypePtr();
} else {
boiling = false;
}
}
// See if there is a constant size to this array type at this position.
if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
arrSizes[TypeIdx] = std::pair<OriginalArrType,uint64_t>(
O_SizedArray, CAT->getSize().getZExtValue());
// If this is the top-most pointer variable?
if (hasBoundsKey() && IsTopMost) {
BoundsKey CBKey = ABInfo.getConstKey(CAT->getSize().getZExtValue());
ABounds *NB = new CountBound(CBKey);
ABInfo.insertDeclaredBounds(D, NB);
}
} else {
arrSizes[TypeIdx] = std::pair<OriginalArrType,uint64_t>(
O_UnSizedArray,0);
}
// Iterate.
if (const ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
QTy = ArrTy->getElementType();
Ty = QTy.getTypePtr();
} else {
llvm_unreachable("unknown array type");
}
} else {
// Save here if QTy is qualified or not into a map that
// indexes K to the qualification of QTy, if any.
insertQualType(TypeIdx, QTy);
arrSizes[TypeIdx] = std::pair<OriginalArrType,uint64_t>(O_Pointer,0);
// Iterate.
QTy = QTy.getSingleStepDesugaredType(C);
QTy = QTy.getTypePtr()->getPointeeType();
Ty = QTy.getTypePtr();
}
// This type is not a constant atom. We need to create a VarAtom for this.
if (!VarCreated) {
VarAtom *VA = CS.getFreshVar(Npre + N, VK);
vars.push_back(VA);
// Incomplete arrays are lower bounded to ARR because the transformation
// int[] -> _Ptr<int> is permitted while int[1] -> _Ptr<int> is not.
if (IsIncompleteArr)
CS.addConstraint(CS.createGeq(VA, CS.getArr(), false));
else if (IsArr)
CS.addConstraint(CS.createGeq(CS.getArr(), VA, false));
}
// Prepare for next level of pointer
VarCreated = false;
IsArr = false;
TypeIdx++;
Npre = Npre + "*";
VK = VarAtom::V_Other; // only the outermost pointer considered a param/return
IsTopMost = false;
}
insertQualType(TypeIdx, QTy);
// In CheckedC, a pointer can be freely converted to a size 0 array pointer,
// but our constraint system does not allow this. To enable converting calls
// to functions with types similar to free, size 0 array pointers are made PTR
// instead of ARR.
IsZeroWidthArray = false;
if (D && D->hasBoundsExpr() && !vars.empty() && vars[0] == CS.getArr())
if (BoundsExpr *BE = D->getBoundsExpr())
if (isZeroBoundsExpr(BE, C)) {
IsZeroWidthArray = true;
vars[0] = CS.getPtr();
}
// If, after boiling off the pointer-ness from this type, we hit a
// function, then create a base-level FVConstraint that we carry
// around too.
if (Ty->isFunctionType())
// C function-pointer type declarator syntax embeds the variable
// name within the function-like syntax. For example:
// void (*fname)(int, int) = ...;
// If a typedef'ed type name is used, the name can be omitted
// because it is not embedded like that. Instead, it has the form
// tn fname = ...,
// where tn is the typedef'ed type name.
// There is possibly something more elegant to do in the code here.
FV = new FVConstraint(Ty, IsDeclTy ? D : nullptr, IsTypedef ? "" : N, I, C);
// Get a string representing the type without pointer and array indirection.
BaseType = extractBaseType(D, QT, Ty, C);
bool IsWild = !IsGeneric && (isVarArgType(BaseType) || isTypeHasVoid(QT));
if (IsWild) {
std::string Rsn =
isTypeHasVoid(QT) ? "Default void* type" : "Default Var arg list type";
// TODO: Github issue #61: improve handling of types for variable arguments.
for (const auto &V : vars)
if (VarAtom *VA = dyn_cast<VarAtom>(V))
CS.addConstraint(CS.createGeq(VA, CS.getWild(), Rsn));
}
// Add qualifiers.
std::ostringstream QualStr;
getQualString(TypeIdx, QualStr);
BaseType = QualStr.str() + BaseType;
// Here lets add implication that if outer pointer is WILD
// then make the inner pointers WILD too.
if (vars.size() > 1) {
bool UsedPrGeq = false;
for (auto VI=vars.begin(), VE=vars.end(); VI != VE; VI++) {
if (VarAtom *VIVar = dyn_cast<VarAtom>(*VI)) {
// Premise.
Geq *PrGeq = new Geq(VIVar, CS.getWild());
UsedPrGeq = false;
for (auto VJ = (VI + 1); VJ != VE; VJ++) {
if (VarAtom *VJVar = dyn_cast<VarAtom>(*VJ)) {
// Conclusion.
Geq *CoGeq = new Geq(VJVar, CS.getWild());
CS.addConstraint(CS.createImplies(PrGeq, CoGeq));
UsedPrGeq = true;
}
}
// Delete unused constraint.
if (!UsedPrGeq) {
delete (PrGeq);
}
}
}
}
}
std::string PointerVariableConstraint::extractBaseType(DeclaratorDecl *D,
QualType QT,
const Type *Ty,
const ASTContext &C) {
std::string BaseTypeStr;
bool FoundBaseTypeInSrc = false;
if (!Ty->getAs<TypedefType>() && D && D->getTypeSourceInfo()) {
// Try to extract the type from original source to preserve defines
TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
if (isa<FunctionDecl>(D)) {
FoundBaseTypeInSrc = D->getAsFunction()->getReturnType() == QT;
TL = getBaseTypeLoc(TL).getAs<FunctionTypeLoc>();
// FunctionDecl that doesn't have function type? weird
if (TL.isNull())
FoundBaseTypeInSrc = false;
else
TL = TL.getAs<clang::FunctionTypeLoc>().getReturnLoc();
} else {
FoundBaseTypeInSrc = D->getType() == QT;
}
TypeLoc BaseLoc = getBaseTypeLoc(TL);
if (!BaseLoc.getAs<TypedefTypeLoc>().isNull()) {
FoundBaseTypeInSrc = false;
} else {
// Only use this type if the type passed as a parameter to this constructor
// agrees with the actual type of the declaration.
SourceRange SR = BaseLoc.getSourceRange();
if (FoundBaseTypeInSrc && SR.isValid()) {
BaseTypeStr = getSourceText(SR, C);
// getSourceText returns the empty string when there's a pointer level
// inside a macro. Not sure how to handle this, so fall back to tyToStr.
if (BaseTypeStr.empty())
FoundBaseTypeInSrc = false;
} else
FoundBaseTypeInSrc = false;
}
}
// Fall back to rebuilding the base type based on type passed to constructor
if (!FoundBaseTypeInSrc)
BaseTypeStr = tyToStr(Ty);
return BaseTypeStr;
}
void PointerVariableConstraint::print(raw_ostream &O) const {
O << "{ ";
for (const auto &I : vars) {
I->print(O);
O << " ";
}
O << " }";
if (FV) {
O << "(";
FV->print(O);
O << ")";
}
}
void PointerVariableConstraint::dump_json(llvm::raw_ostream &O) const {
O << "{\"PointerVar\":{";
O << "\"Vars\":[";
bool addComma = false;
for (const auto &I : vars) {
if (addComma) {
O << ",";
}
I->dump_json(O);
addComma = true;
}
O << "], \"name\":\"" << getName() << "\"";
if (FV) {
O << ", \"FunctionVariable\":";
FV->dump_json(O);
}
O << "}}";
}
void PointerVariableConstraint::getQualString(uint32_t TypeIdx,
std::ostringstream &Ss) const {
auto QIter = QualMap.find(TypeIdx);
if (QIter != QualMap.end()) {
for (Qualification Q : QIter->second) {
switch (Q) {
case ConstQualification:
Ss << "const ";
break;
case VolatileQualification:
Ss << "volatile ";
break;
case RestrictQualification:
Ss << "restrict ";
break;
}
}
}
}
void PointerVariableConstraint::insertQualType(uint32_t TypeIdx,
QualType &QTy) {
if (QTy.isConstQualified())
QualMap[TypeIdx].insert(ConstQualification);
if (QTy.isVolatileQualified())
QualMap[TypeIdx].insert(VolatileQualification);
if (QTy.isRestrictQualified())
QualMap[TypeIdx].insert(RestrictQualification);
}
// emitArraySize
// Take an array or nt_array variable, determines if it is
// a constant array, and if so emits the apprioate syntax for a
// stack-based array. This functions also updates various flags.
bool PointerVariableConstraint::emitArraySize(std::stack<std::string> &CheckedArrs,
uint32_t TypeIdx,
// Is the type only an array
bool &AllArrays,
// Are we processing an array
bool &ArrayRun,
bool Nt) const {
bool Ret = false;
if (ArrPresent) {
auto i = arrSizes.find(TypeIdx);
assert(i != arrSizes.end());
OriginalArrType Oat = i->second.first;
uint64_t Oas = i->second.second;
std::ostringstream SizeStr;
if (Oat == O_SizedArray) {
SizeStr << (Nt ? " _Nt_checked" : " _Checked");
SizeStr << "[" << Oas << "]";
CheckedArrs.push(SizeStr.str());
ArrayRun = true;
Ret = true;
} else {
AllArrays = ArrayRun = false;
}
return Ret;
}
return Ret;
}
/* addArrayAnnotiations
* This function takes all the stacked annotations for constant arrays
* and pops them onto the EndStrs, this ensures the right order of annotations
* */
void PointerVariableConstraint::addArrayAnnotations(
std::stack<std::string> &CheckedArrs,
std::deque<std::string> &EndStrs) const {
while(!CheckedArrs.empty()) {
auto NextStr = CheckedArrs.top();
CheckedArrs.pop();
EndStrs.push_front(NextStr);
}
assert(CheckedArrs.empty());
}
// Mesh resolved constraints with the PointerVariableConstraints set of
// variables and potentially nested function pointer declaration. Produces a
// string that can be replaced in the source code.
std::string
PointerVariableConstraint::mkString(const EnvironmentMap &E,
bool EmitName,
bool ForItype,
bool EmitPointee) const {
std::ostringstream Ss;
// This deque will store all the type strings that need to pushed
// to the end of the type string. This is typically things like
// closing delimiters.
std::deque<std::string> EndStrs;
// This will store stacked array decls to ensure correct order
// We encounter constant arrays variables in the reverse order they
// need to appear in, so the LIFO structure reverses these annotations
std::stack<std::string> CheckedArrs;
// Have we emitted the string for the base type
bool EmittedBase = false;
// Have we emitted the name of the variable yet?
bool EmittedName = false;
// Was the last variable an Array?
bool PrevArr = false;
// Is the entire type so far an array?
bool AllArrays = true;
// Are we in a sequence of arrays
bool ArrayRun = false;
if ((EmitName == false && hasItype() == false) || getName() == RETVAR)
EmittedName = true;
uint32_t TypeIdx = 0;
auto It = vars.begin();
// Skip over first pointer level if only emitting pointee string.
// This is needed when inserting type arguments.
if (EmitPointee)
++It;
for (; It != vars.end(); ++It) {
const auto &V = *It;
ConstAtom *C = nullptr;
if (ConstAtom *CA = dyn_cast<ConstAtom>(V)) {
C = CA;
} else {
VarAtom *VA = dyn_cast<VarAtom>(V);
assert(VA != nullptr && "Constraint variable can "
"be either constant or VarAtom.");
C = E.at(VA).first;
}
assert(C != nullptr);
Atom::AtomKind K = C->getKind();
// If this is not an itype
// make this wild as it can hold any pointer type.
if (!ForItype && BaseType == "void")
K = Atom::A_Wild;
if (PrevArr && K != Atom::A_Arr && !EmittedName) {
EmittedName = true;
addArrayAnnotations(CheckedArrs, EndStrs);
EndStrs.push_front(" " + getName());
}
PrevArr = ((K == Atom::A_Arr || K == Atom::A_NTArr)
&& ArrPresent
&& arrSizes.at(TypeIdx).first == O_SizedArray);
switch (K) {
case Atom::A_Ptr:
getQualString(TypeIdx, Ss);
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
AllArrays = false;
if (hasItype() == false) {
EmittedBase = false;
Ss << "_Ptr<";
ArrayRun = false;
EndStrs.push_front(">");
break;
}
LLVM_FALLTHROUGH;
case Atom::A_Arr:
// If this is an array.
getQualString(TypeIdx, Ss);
// If it's an Arr, then the character we substitute should
// be [] instead of *, IF, the original type was an array.
// And, if the original type was a sized array of size K.
// we should substitute [K].
if (emitArraySize(CheckedArrs, TypeIdx, AllArrays, ArrayRun, false))
break;
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
if (hasItype() == false) {
EmittedBase = false;
Ss << "_Array_ptr<";
EndStrs.push_front(">");
break;
}
LLVM_FALLTHROUGH;
case Atom::A_NTArr:
if (emitArraySize(CheckedArrs, TypeIdx, AllArrays, ArrayRun, true))
break;
// This additional check is to prevent fall-through from the array.
if (K == Atom::A_NTArr) {
// If this is an NTArray.
getQualString(TypeIdx, Ss);
// We need to check and see if this level of variable
// is constrained by a bounds safe interface. If it is,
// then we shouldn't re-write it.
if (hasItype() == false) {
EmittedBase = false;
Ss << "_Nt_array_ptr<";
EndStrs.push_front(">");
break;
}
}
LLVM_FALLTHROUGH;
// If there is no array in the original program, then we fall through to
// the case where we write a pointer value.
case Atom::A_Wild:
AllArrays = false;
if (ArrayRun)
addArrayAnnotations(CheckedArrs, EndStrs);
ArrayRun = false;
if (EmittedBase) {
Ss << "*";
} else {
assert(BaseType.size() > 0);
EmittedBase = true;
if (FV) {
Ss << FV->mkString(E);
} else {
Ss << BaseType << " *";
}
}
getQualString(TypeIdx, Ss);
break;
case Atom::A_Const:
case Atom::A_Var:
llvm_unreachable("impossible");
break;
}
TypeIdx++;
}
// If the previous variable was an array or
// if we are leaving an array run, we need to emit the
// annotation for a stack-array
if ((PrevArr || ArrayRun) && !CheckedArrs.empty())
addArrayAnnotations(CheckedArrs, EndStrs);
// If the whole type is an array so far, and we haven't emitted
// a name yet, then emit the name so that it appears before
// the the stack array type.
if (PrevArr && !EmittedName && AllArrays) {
EmittedName = true;
EndStrs.push_front(" " + getName());
}
if (EmittedBase == false) {
// If we have a FV pointer, then our "base" type is a function pointer.
// type.
if (FV) {
Ss << FV->mkString(E);
} else {
Ss << BaseType;
}
}
// Add closing elements to type
for (std::string Str : EndStrs) {
Ss << Str;
}
// No space after itype.
if (!EmittedName)
Ss << " " << getName();
// Final array dropping
if(!CheckedArrs.empty())
addArrayAnnotations(CheckedArrs, EndStrs);
//TODO remove comparison to RETVAR
if (getName() == RETVAR && !ForItype)
Ss << " ";
return Ss.str();
}
bool PVConstraint::addArgumentConstraint(ConstraintVariable *DstCons,
ProgramInfo &Info) {
if (this->Parent == nullptr) {
bool RetVal = false;
if (isPartOfFunctionPrototype()) {
RetVal = argumentConstraints.insert(DstCons).second;
if (RetVal && this->HasEqArgumentConstraints) {
constrainConsVarGeq(DstCons, this, Info.getConstraints(), nullptr,
Same_to_Same, true, &Info);
}
}
return RetVal;
}
return this->Parent->addArgumentConstraint(DstCons, Info);
}
const CVarSet &PVConstraint::getArgumentConstraints() const {
return argumentConstraints;
}
FunctionVariableConstraint::
FunctionVariableConstraint(FunctionVariableConstraint *Ot,
Constraints &CS) :
ConstraintVariable(ConstraintVariable::FunctionVariable,
Ot->OriginalType,
Ot->getName()) {
this->IsStatic = Ot->IsStatic;
this->FileName = Ot->FileName;
this->Hasbody = Ot->Hasbody;
this->Hasproto = Ot->Hasproto;
this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints;
this->IsFunctionPtr = Ot->IsFunctionPtr;
this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints;
this->ReturnVar = Ot->ReturnVar;
// Make copy of ParameterCVs too.
for (auto &ParmPv : Ot->ParamVars)
this->ParamVars.push_back(ParmPv->getCopy(CS));
this->Parent = Ot;
}
// This describes a function, either a function pointer or a function
// declaration itself. Require constraint variables for each argument and
// return, even those that aren't pointer types, since we may need to
// re-emit the function signature as a type.
FunctionVariableConstraint::FunctionVariableConstraint(DeclaratorDecl *D,
ProgramInfo &I,
const ASTContext &C) :
FunctionVariableConstraint(D->getType().getTypePtr(), D,
(D->getDeclName().isIdentifier() ?
D->getName() : ""), I, C)
{ }
FunctionVariableConstraint::FunctionVariableConstraint(const Type *Ty,
DeclaratorDecl *D,
std::string N,
ProgramInfo &I,
const ASTContext &Ctx) :
ConstraintVariable(ConstraintVariable::FunctionVariable,
tyToStr(Ty), N), Parent(nullptr)
{
QualType RT;
Hasproto = false;
Hasbody = false;
FileName = "";
HasEqArgumentConstraints = false;
IsFunctionPtr = true;
// Metadata about function
FunctionDecl *FD = nullptr;
if (D) FD = dyn_cast<FunctionDecl>(D);
if (FD) {
// FunctionDecl::hasBody will return true if *any* declaration in the
// declaration chain has a body, which is not what we want to record.
// We want to record if *this* declaration has a body. To do that,
// we'll check if the declaration that has the body is different
// from the current declaration.
const FunctionDecl *OFd = nullptr;
if (FD->hasBody(OFd) && OFd == FD)
Hasbody = true;
IsStatic = !(FD->isGlobal());
ASTContext *TmpCtx = const_cast<ASTContext *>(&Ctx);
auto PSL = PersistentSourceLoc::mkPSL(D, *TmpCtx);
FileName = PSL.getFileName();
IsFunctionPtr = false;
}
// ConstraintVariables for the parameters
if (Ty->isFunctionPointerType()) {
// Is this a function pointer definition?
llvm_unreachable("should not hit this case");
} else if (Ty->isFunctionProtoType()) {
// Is this a function?
const FunctionProtoType *FT = Ty->getAs<FunctionProtoType>();
assert(FT != nullptr);
RT = FT->getReturnType();
// Extract the types for the parameters to this function. If the parameter
// has a bounds expression associated with it, substitute the type of that
// bounds expression for the other type.
for (unsigned i = 0; i < FT->getNumParams(); i++) {
QualType QT = FT->getParamType(i);
std::string PName = "";
DeclaratorDecl *ParmVD = nullptr;
if (FD && i < FD->getNumParams()) {
ParmVarDecl *PVD = FD->getParamDecl(i);
if (PVD) {
ParmVD = PVD;
PName = PVD->getName();
}
}
bool IsGeneric = ParmVD != nullptr &&
getTypeVariableType(ParmVD) != nullptr;
ParamVars.push_back(new PVConstraint(QT, ParmVD, PName, I, Ctx, &N,
IsGeneric));
}
Hasproto = true;
} else if (Ty->isFunctionNoProtoType()) {
const FunctionNoProtoType *FT = Ty->getAs<FunctionNoProtoType>();
assert(FT != nullptr);
RT = FT->getReturnType();
} else {
llvm_unreachable("don't know what to do");
}
// ConstraintVariable for the return
bool IsGeneric = FD != nullptr && getTypeVariableType(FD) != nullptr;
ReturnVar = new PVConstraint(RT, D, RETVAR, I, Ctx, &N, IsGeneric);
}
void FunctionVariableConstraint::constrainToWild(Constraints &CS) const {
ReturnVar->constrainToWild(CS);
for (const auto &V : ParamVars)
V->constrainToWild(CS);
}
void FunctionVariableConstraint::constrainToWild(Constraints &CS,
const std::string &Rsn) const {
ReturnVar->constrainToWild(CS, Rsn);
for (const auto &V : ParamVars)
V->constrainToWild(CS, Rsn);
}
void FunctionVariableConstraint::constrainToWild
(Constraints &CS, const std::string &Rsn, PersistentSourceLoc *PL) const {
ReturnVar->constrainToWild(CS, Rsn, PL);
for (const auto &V : ParamVars)
V->constrainToWild(CS, Rsn, PL);
}
bool FunctionVariableConstraint::anyChanges(const EnvironmentMap &E) const {
return ReturnVar->anyChanges(E);
}
bool FunctionVariableConstraint::hasWild(const EnvironmentMap &E,
int AIdx) const {
return ReturnVar->hasWild(E, AIdx);
}
bool FunctionVariableConstraint::hasArr(const EnvironmentMap &E,
int AIdx) const {
return ReturnVar->hasArr(E, AIdx);
}
bool FunctionVariableConstraint::hasNtArr(const EnvironmentMap &E,
int AIdx) const {
return ReturnVar->hasNtArr(E, AIdx);
}
ConstraintVariable *FunctionVariableConstraint::getCopy(Constraints &CS) {
return new FVConstraint(this, CS);
}
void PVConstraint::equateArgumentConstraints(ProgramInfo &Info) {
if (HasEqArgumentConstraints) {
return;
}
HasEqArgumentConstraints = true;
constrainConsVarGeq(this, this->argumentConstraints, Info.getConstraints(),
nullptr, Same_to_Same, true, &Info);
if (this->FV != nullptr) {
this->FV->equateArgumentConstraints(Info);
}
}
void FunctionVariableConstraint::equateFVConstraintVars
(ConstraintVariable *CV, ProgramInfo &Info) const {
if (FVConstraint *FVCons = dyn_cast<FVConstraint>(CV)) {
for (auto &PCon : FVCons->ParamVars)
PCon->equateArgumentConstraints(Info);
FVCons->ReturnVar->equateArgumentConstraints(Info);
}
}
void FunctionVariableConstraint::equateArgumentConstraints(ProgramInfo &Info) {
if (HasEqArgumentConstraints) {
return;
}
HasEqArgumentConstraints = true;
// Equate arguments and parameters vars.
this->equateFVConstraintVars(this, Info);
// Is this not a function pointer?
if (!IsFunctionPtr) {
FVConstraint *DefnCons = nullptr;
// Get appropriate constraints based on whether the function is static or not.
if (IsStatic) {
DefnCons = Info.getStaticFuncConstraint(Name, FileName);
} else {
DefnCons = Info.getExtFuncDefnConstraint(Name);
}
assert(DefnCons != nullptr);
// Equate arguments and parameters vars.
this->equateFVConstraintVars(DefnCons, Info);
}
}
void PointerVariableConstraint::constrainToWild(Constraints &CS) const {
ConstAtom *WA = CS.getWild();
for (const auto &V : vars) {
if (VarAtom *VA = dyn_cast<VarAtom>(V))
CS.addConstraint(CS.createGeq(VA, WA, true));
}
if (FV)
FV->constrainToWild(CS);
}
void PointerVariableConstraint::constrainToWild(Constraints &CS,
const std::string &Rsn,
PersistentSourceLoc *PL) const {
ConstAtom *WA = CS.getWild();