aboutsummaryrefslogtreecommitdiff
path: root/lib/CodeGen/Designator.cc
blob: d790d27240fee45e9c11bdde1fbb6cc2018c9690 (plain)
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

// User-defined type registration and addressable designator access.
#include "cps/CodeGen.h"
#include "cps/ArrayHandler.h"
#include "cps/TypeAST.h"

using namespace llvm;
using namespace cps;

// Registers every top-level TYPE declaration before prototypes are emitted.
// Two passes so a pointer TYPE may reference a type declared later
// (TYPE NodePtr = ^Node before TYPE Node — required for linked structures);
// by-value record fields still require their record type to be complete,
// which pass B's source order enforces.
void CodeGen::runTypePrePass(const std::vector<std::unique_ptr<StmtAST>> &Statements, int Phase) {
    std::string Err;

    if (Phase == 0) for (const auto &S : Statements) {
        SaveAndRestore<int> Location(DiagnosticLine, S->getLine());
        bool Ok = true;
        if (auto *C = dynamic_cast<CTypeDeclAST*>(S.get()))
            Ok = Types->defineCAlias(C->getName(), C->getExpression(), Err);
        else if (auto *E = dynamic_cast<EnumTypeDeclAST*>(S.get()))
            Ok = Types->declareUserType(E->getName(), TypeKind::Enum, Err);
        else if (auto *P = dynamic_cast<PointerTypeDeclAST*>(S.get()))
            Ok = Types->declareUserType(P->getName(), TypeKind::Pointer, Err);
        else if (auto *R = dynamic_cast<RecordTypeDeclAST*>(S.get()))
            Ok = Types->declareUserType(R->getName(), TypeKind::Record, Err,
                                        dynamic_cast<ClassTypeDeclAST*>(R) != nullptr);
        if (!Ok) reportError("%s", Err.c_str());
    }

    if (Phase == 1) for (const auto &S : Statements) {
        SaveAndRestore<int> Location(DiagnosticLine, S->getLine());
        bool Ok = true;
        if (auto *E = dynamic_cast<EnumTypeDeclAST*>(S.get())) {
            Ok = Types->defineEnum(E->getName(), E->getValueNames(), Err);
        } else if (auto *P = dynamic_cast<PointerTypeDeclAST*>(S.get())) {
            Ok = Types->definePointer(P->getName(), P->getPointeeTypeName(), Err);
        } else if (auto *R = dynamic_cast<RecordTypeDeclAST*>(S.get())) {
            Ok = Types->defineRecord(R->getName(), R->getFields(), Err);
        }
        if (!Ok) reportError("%s", Err.c_str());
    }

    if (Phase == 2) for (const auto &S : Statements)
        if (auto *Class = dynamic_cast<ClassTypeDeclAST*>(S.get())) registerClassMethods(Class);
}

void CodeGen::registerClassMethods(ClassTypeDeclAST *Class) {
    auto &Methods = ClassMethods[Class->getName()];
    IdentifierSet Names;
    for (const auto &Field : Class->getFields()) {
        Names.insert(Field.Name);
        if (sameIdentifier(Field.Name, "this")) {
            SaveAndRestore<int> Location(DiagnosticLine, Class->getLine());
            reportError("A class field cannot be named this");
        }
    }
    for (const auto &Method : Class->getMethods()) {
        SaveAndRestore<int> Location(DiagnosticLine, Method->getLine());
        const std::string &Name = Method->getProto()->getName();
        if (sameIdentifier(Name, "this")) {
            reportError("A method cannot be named this");
        } else if (Names.count(Name) ||
                   (!Methods[Name].empty() && (!Method->getProto()->isOverload() ||
                                             !Methods[Name].front()->getProto()->isOverload()))) {
            reportError("Duplicate member %s in class %s", Name.c_str(), Class->getName().c_str());
        } else {
            Methods[Name].push_back(Method.get());
        }
    }
}

void CodeGen::emitClassPrototypes(ClassTypeDeclAST *Class) {
    for (const auto &Method : Class->getMethods()) {
        SaveAndRestore<int> Location(DiagnosticLine, Method->getLine());
        if (isRegisteredMethod(Class->getName(), Method->getProto()))
            FuncGen->emitPrototype(Method->getProto());
    }
}

const std::vector<FunctionDefAST *> *CodeGen::findMethod(const std::string &Class, const std::string &Name) const {
    if (Class.find('<') != std::string::npos && !resolveType(Class)) return nullptr;
    auto C = ClassMethods.find(Class);
    if (C == ClassMethods.end()) return nullptr;
    auto M = C->second.find(Name);
    return M == C->second.end() || M->second.empty() ? nullptr : &M->second;
}

bool CodeGen::isRegisteredMethod(const std::string &Class, const PrototypeAST *Method) const {
    const auto *Methods = findMethod(Class, Method->getName());
    if (Methods)
        for (const auto *Candidate : *Methods)
            if (Candidate->getProto() == Method) return true;
    return false;
}

const FuncSig *CodeGen::resolveMethod(const std::string &Class, const std::string &Name,
                                    const std::vector<std::unique_ptr<ExprAST>> &Args,
                                    const ResultContext *Context) {
    const auto *Methods = findMethod(Class, Name);
    if (!Methods) {
        reportError("Type %s has no method %s", Class.c_str(), Name.c_str());
        return nullptr;
    }
    return resolveCall(Methods->front()->getProto()->getLinkName(), Args, nullptr, Context);
}

Value *CodeGen::emitMemberCall(MemberCallExprAST *Call, const ResultContext *Context) {
    SaveAndRestore<int> Location(DiagnosticLine, Call->getLine());
    LValueInfo Receiver;
    if (isObjectLValue(Call->getReceiver())) {
        if (!emitLValue(Call->getReceiver(), Receiver)) return nullptr;
    } else {
        const TypeInfo *Type = getExprTypeInfo(Call->getReceiver());
        if (!Type || !Type->IsClass) {
            reportError("A temporary method receiver must be a class");
            return nullptr;
        }
        Receiver = {materializeOperatorReceiver(emitExpr(Call->getReceiver()), Type), Type->Name};
        if (!Receiver.Addr) return nullptr;
    }
    return emitMethodCall(Receiver.TypeName, Receiver.Addr, Call->getMethod(),
                          Call->getArgs(), Call->getLine(), Context);
}

Value *CodeGen::emitMethodCall(const std::string &Class, Value *Receiver,
                                const std::string &Name,
                                const std::vector<std::unique_ptr<ExprAST>> &ArgExprs, int Line,
                                const ResultContext *Context) {
    SaveAndRestore<int> Location(DiagnosticLine, Line);
    const FuncSig *Sig = resolveMethod(Class, Name, ArgExprs, Context);
    if (!Sig) return nullptr;
    const PrototypeAST *Method = Sig->Prototype;
    if (!Method->isPublic() && !sameIdentifier(CurrentClass, Class)) {
        reportError("Cannot access private method %s of type %s", Name.c_str(), Class.c_str());
        return nullptr;
    }
    std::vector<Value*> Args = {Receiver};
    if (!marshalCallArgs(*Sig, ArgExprs, Line, Args)) return nullptr;
    return FuncGen->emitCall(*Sig, Args);
}

// Looks up a variable that is about to be written, diagnosing unknown names,
// enum values and read-only symbols.
const SymbolInfo *CodeGen::lookupWritableSymbol(const std::string &Name) {
    const SymbolInfo *Info = getSymbolInfo(Name);
    if (!Info) {
        if (Types->lookupEnumConstant(Name)) {
            reportError("Enum value %s is not an assignable location", Name.c_str());
        } else {
            reportError("Unknown variable name %s", Name.c_str());
        }
        return nullptr;
    }
    if (!requireWritable(*Info, Name)) return nullptr;
    return Info;
}

// Resolves a designator (or legacy variable/array-access node) to the address
// of its storage plus the type name stored there. Array indexing goes through
// ArrayHandler's checked pipeline; dereferences emit the null-pointer check.
bool CodeGen::emitLValue(ExprAST *E, LValueInfo &Out) {
    SaveAndRestore<int> Location(DiagnosticLine, E && E->getLine() ? E->getLine() : DiagnosticLine);
    if (auto *Var = dynamic_cast<VariableExprAST*>(E)) {
        const SymbolInfo *Info = lookupWritableSymbol(Var->getName());
        if (!Info) return false;
        if (Info->IsArray) {
            reportError("Whole array %s is not an assignable location; index it", Var->getName().c_str());
            return false;
        }
        Out.Addr = symbolAddress(*Info);
        Out.TypeName = Info->TypeName;
        return true;
    }

    if (auto *Acc = dynamic_cast<ArrayAccessExprAST*>(E)) {
        Out.Addr = Arrays->emitElementAddress(Acc, *this, Out.TypeName);
        return Out.Addr != nullptr;
    }

    auto *D = dynamic_cast<DesignatorExprAST*>(E);
    if (!D) {
        reportError("Expression is not an assignable location");
        return false;
    }

    const SymbolInfo *Info = lookupWritableSymbol(D->getBaseName());
    if (!Info) return false;
    const auto &Accesses = D->getAccesses();
    Value *Addr = symbolAddress(*Info);
    std::string TypeName = Info->TypeName;
    size_t Start = 0;

    if (Info->IsArray) {
        if (Accesses.empty() || Accesses[0].Kind != AccessKind::Index) {
            reportError("Array %s must be indexed before '.' or '^' access", D->getBaseName().c_str());
            return false;
        }
        Addr = Arrays->emitElementAddress(D->getBaseName(), Accesses[0].Indices,
                                          D->getLine(), *this, TypeName);
        if (!Addr) return false;
        Start = 1;
    }

    for (size_t I = Start; I < Accesses.size(); ++I) {
        const DesignatorAccess &A = Accesses[I];
        const TypeInfo *Cur = resolveType(TypeName);
        if (!Cur) {
            reportError("Unknown type %s", TypeName.c_str());
            return false;
        }

        switch (A.Kind) {
        case AccessKind::Field: {
            const RecordPayload *RP = Cur->asRecord();
            if (!RP) {
                reportError("Type %s is not a record; '.%s' is invalid",
                            TypeName.c_str(), A.FieldName.c_str());
                return false;
            }
            const RecordFieldInfo *FI = RP->findField(A.FieldName);
            if (!FI) {
                // The rejected field was already reported with its record.
                if (!RP->Invalid)
                    reportError("Record type %s has no field %s", TypeName.c_str(), A.FieldName.c_str());
                return false;
            }
            if (!FI->IsPublic && !sameIdentifier(CurrentClass, TypeName)) {
                reportError("Cannot access private field %s of type %s",
                            A.FieldName.c_str(), TypeName.c_str());
                return false;
            }
            Addr = Builder->CreateStructGEP(Cur->LLVMType, Addr, FI->Index,
                                            TypeName + "." + A.FieldName);
            TypeName = FI->TypeName;
            break;
        }

        case AccessKind::Deref: {
            const PointerPayload *PP = Cur->asPointer();
            if (!PP) {
                reportError("Cannot dereference a value of type %s ('^' needs a pointer)",
                            TypeName.c_str());
                return false;
            }
            const TypeInfo *Pointee = resolveType(PP->PointeeTypeName);
            if (!Pointee || Pointee->isVoid()) {
                reportError("Cannot dereference a void pointer");
                return false;
            }
            Value *P = Builder->CreateLoad(PointerType::getUnqual(*TheContext), Addr, "deref_ptr");
            RuntimeChecker->emitNullDerefCheck(P, D->getLine());
            Addr = P;
            TypeName = PP->PointeeTypeName;
            break;
        }

        case AccessKind::Index:
            reportError("Cannot index a value of type %s (only declared arrays can be indexed)",
                        TypeName.c_str());
            return false;
        }
    }

    Out.Addr = Addr;
    Out.TypeName = TypeName;
    return true;
}

Value *CodeGen::loadFromLValue(const LValueInfo &LV) {
    const TypeInfo *Info = resolveType(LV.TypeName);
    if (!Info || !Info->LLVMType) {
        reportError("Unknown type %s", LV.TypeName.c_str());
        return nullptr;
    }
    Value *Val = Builder->CreateLoad(Info->LLVMType, LV.Addr);
    return Val;
}